반응형
HTML5 Canvas
Code
<script>
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;
const 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++;
if (hue >= 360) hue = 0;
if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) direction = !direction;
direction ? ctx.lineWidth++ : 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('mouseout', () => isDrawing = false);
</script>
배운 점 & 느낀 점
canvas api를 처음 사용해보았습니다.
js로 이런 그림까지 그릴 수 있다는게 신기했습니다.
반응형
'공부 정리 > jsChallenge' 카테고리의 다른 글
js challenge day10 (0) | 2023.02.03 |
---|---|
js challenge day 9 (0) | 2023.02.02 |
js challenge day 7 (0) | 2023.01.30 |
js challenge day 6 (0) | 2023.01.27 |
js challenge day 5 (0) | 2023.01.25 |
댓글