JS30 Day08 Fun with HTML5 Canvas
요구사항
선수지식
Canvas
width, height
요소만 존재
- 고정크기의 드로잉 영역을 생성하고 하나 이상의 랜더링 컨텍스트를 노출해 컨텐츠를 생성, 출력함
getContext()
를 이용해 그리기 함수를 사용할 수 있음
코드
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
ctx.strokeStyle = '#BADA55';
ctx.lineJoin ='round';
ctx.lineCap ='round';
ctx.lineWidth = 100;
let isDrawing = false;
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;
function draw(e){
if(!isDrawing) return;
ctx.strokeStyle = `hsl(${hue},100%, 50%)`;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
[lastX, lastY] = [e.offsetX, e.offsetY];
hue += 1;
if(hue >= 360){
hue = 0;
}
if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1){
direction = !direction;
}
if(direction)
ctx.lineWidth++;
else
ctx.lineWidth--;
}
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
});
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('click', () => isDrawing = false);