Canvas Draw
// ์บ๋ฒ์ค์ ๊ทธ๋ฆผ๊ทธ๋ฆฌ๊ธฐ
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;
// ctx.globalCompositeOperation = 'multiply';
let isDrawing = false; // ๊ทธ๋ฆผ์ ๊ทธ๋ฆฐํ์ ๋ง์ฐ์ค๋ฅผ ๋ ์๋ ๋ฉ์ถฐ์ผํ๋ฏ๋ก
let lastX = 0;
let lastY = 0;
let hue = 0;
let direction = true;
function draw(e) {
if (!isDrawing) return; // mouse down ์๋๋ฉด ํจ์์คํ์ ๋ฉ์ถฐ๋ผ
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;// ๋ํ์ ์ค๊ณฝ์ ์์ ์ค์
ctx.beginPath(); // ์บ๋ฒ์ค๋ฅผ ์์ํ ๋ ์๋ก์ด path๋ฅผ ๋ง๋ค๊ธฐ ์ํด ์ฌ์ฉ
// start from
ctx.moveTo(lastX, lastY);
// go to
ctx.lineTo(e.offsetX, e.offsetY); //e.offsetX, e.offsetY ๋ง์ฐ์ค ์ด๋์ ๋ฐ๋ผ EventListener๋ฅผ ๊ฑธ์ด ๋์ ์ด๋ฒคํธ ๊ฐ์ฒด -> ๋ง์ฐ์ค ์์น๋ฅผ ๋ฐํ ํ๊ณ draw ํจ์์์ ์ด๋ฅผ ์ฌ์ฉ
ctx.stroke(); // ์ค๊ณฝ์ ์ ์ด์ฉํ์ฌ ๋ํ์ ๊ทธ๋ฆฌ๋ ํจ์
[lastX, lastY] = [e.offsetX, e.offsetY];
hue++;
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); // ๋ง์ฐ์ค๊ฐ ์์ง์ผ๋ draw ํจ์ ์คํ
canvas.addEventListener('mouseup', () => isDrawing = false);
canvas.addEventListener('mouseout', () => isDrawing = false);
canvas.addEventListener("mousedown", (e) => {
if (e.which === 1) {
isDrawing = true;
[lastX, lastY] = [e.offsetX, e.offsetY];
} else if (e.which === 3) {
// canvas ์ง์ฐ๋ ๋ถ๋ถ
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
});
<canvas id="draw" width="100%" height="100vh"></canvas>
Last updated
Was this helpful?