Skip to content

Commit e09b40d

Browse files
committed
Completed wesbos#8 - Fun with HTML5 Canvas/index-START.html
1 parent bda9ade commit e09b40d

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

08 - Fun with HTML5 Canvas/index-START.html

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,55 @@
77
<body>
88
<canvas id="draw" width="800" height="800"></canvas>
99
<script>
10+
const canvas = document.querySelector('#draw');
11+
const ctx = canvas.getContext('2d');
12+
canvas.width = window.innerWidth;
13+
canvas.height = window.innerHeight;
14+
ctx.strokeStyle = '#BADA55';
15+
ctx.lineJoin = 'round';
16+
ctx.lineCap = 'round';
17+
ctx.lineWidth = 50;
18+
// ctx.globalCompositeOperation = 'multiply';
19+
20+
21+
let isDrawing = false;
22+
let lastX = 0;
23+
let lastY = 0;
24+
let hue = 0;
25+
let direction = true;
26+
27+
function draw(e) {
28+
if (!isDrawing) return;
29+
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
30+
ctx.beginPath();
31+
32+
ctx.moveTo(lastX, lastY); // Start From
33+
ctx.lineTo(e.offsetX, e.offsetY); // Go To
34+
ctx.stroke();
35+
[lastX, lastY] = [e.offsetX, e.offsetY];
36+
37+
hue++;
38+
if (hue >= 360) {
39+
hue = 0;
40+
}
41+
42+
if (ctx.lineWidth >= 120 || ctx.lineWidth <= 1) {
43+
direction = !direction;
44+
}
45+
if (direction) {
46+
ctx.lineWidth++;
47+
} else {
48+
ctx.lineWidth--;
49+
}
50+
}
51+
canvas.addEventListener('mousedown', (e) => {
52+
isDrawing = true;
53+
[lastX, lastY] = [e.offsetX, e.offsetY];
54+
});
55+
56+
canvas.addEventListener('mousemove', draw);
57+
canvas.addEventListener('mouseup', () => isDrawing = false);
58+
canvas.addEventListener('mouseout', () => isDrawing = false);
1059
</script>
1160

1261
<style>

0 commit comments

Comments
 (0)