javascript/javascript30

[javascript30]Fun with HTML5 Canvas

소영 2021. 7. 15. 19:34
Fun with HTML5 Canvas

마우스를 누르면서 이동하면 그라데이션으로 획이 그려진다.

 

1. canvas 사용법 알아보기

2. canvas 관련 메서드 .lineJoin / .lineCap / .getContext 등 알아보기

3.초기 true값 false변경 작성 방법

코드
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>HTML5 Canvas</title>
</head>
<body>
<canvas id="draw" width="800" height="800"></canvas>
<script>
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');//.getContext() 메서드를 호출해야 그리기 함수 사용이 가능하다
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = '#BADA55';
ctx.lineJoin = 'round';//선 꺾이는 부분 모서리 설정
ctx.lineCap = 'round';//선 끝 부분 모서리 설정
ctx.lineWidth = 100;
// ctx.globalCompositeOperation = 'multiply';

let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;

function draw(e) {
  if (!isDrawing) return; // stop the fn from running when they are not moused down 마우스 다운 되지 않은 상태에서 fn 멈추기
  console.log(e);
  ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;//hue를 점진적으로 숫자를 증가시켜 그라데이션을 만든다
  ctx.beginPath();//새경로 시작
  // start from
  ctx.moveTo(lastX, lastY);//움직임
  // go to
  ctx.lineTo(e.offsetX, e.offsetY);//그리기
  ctx.stroke();//획 넣기
  [lastX, lastY] = [e.offsetX, e.offsetY];//초기화 0부터 시작하기

  hue++;
  if (hue >= 360) {
    hue = 0;
  }
  if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {
    direction = !direction;//lineWidth 값이 100초과 1이하이면 direction을 false로 바꾼다
  }

  if(direction) {
    ctx.lineWidth++;//true일때 lineWidth값 증가
  } else {
    ctx.lineWidth--;//false일때 lineWidth값 감소
  }

}

canvas.addEventListener('mousedown', (e) => {
  isDrawing = true;
  [lastX, lastY] = [e.offsetX, e.offsetY];//초기화 0부터 시작하기
});


canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);

</script>

<style>
  html, body {
    margin: 0;
  }
</style>

</body>
</html>

 

알게 된 문법

canvas를 사용할 때 쓰는 메서드들

.getContext

var canvas = document.getElementById('tutorial');

var ctx = canvas.getContext('2d');

 

canvas를 사용할때 기본 메서드

.getContext() 메서드를 호출해야 그리기 함수 사용이 가능하다


.lineJoin() / .lineCap()

.lineJoin() : canvas 선 꺾이는 부분 모서리 설정

.lineCap() :  canvas 선 끝 부분 모서리 설정


.beginPath()

새경로를 시작할때 사용함


.moveTo() / .lineTo() / .stroke()

.moveTo(x좌표,y좌표) : canvas 움직임

.lineTo(x좌표,y좌표) : canvas 그리기

.stroke() : 획 넣기


javascript 문법(초기화)

let isDrawing = false;

전역변수로 false로 셋팅해 놓고

마우스로 클릭하기 전에는 함수가 실행되지 않도록 한다.

->>  if (!isDrawing) return;

 

이벤트가 실행되길 원하면 실행되길 원하는 동기에 작성한다.

->> isDrawing = true;


let direction = true;

lineWidth값을 점진적으로 크게 하기위해 사용한 변수

 

lineWidth값의 크기가 너무 커지거나(100이상), 너무 작아지면(1이하) direction의 값을 false값으로 변경

direction = !direction

 

true와 false에 조건 달기

if(direction) {

ctx.lineWidth++;//true일때 lineWidth값 증가

} else {

ctx.lineWidth--;//false일때 lineWidth값 감소

}

let hue = 0

https://mothereffinghsl.com/ 에서 보면 알듯

hsl(${hue},100%,50%) 이렇게 첫번째 인자만 변경하면 색이 바뀐다

그리고

아래에 hue++ 작성 하면 점진적으로 숫자가 커진다


[lastX, lastY] = [e.offsetX, e.offsetY]

let lastX = 0;

let lastY = 0;

이렇게 변수를 초기화 시킨 이후 그리면,

이전에 그린 것과 선이 이어지지 않고 다시 처음부터 그릴 수 있다.