Skip to content

Commit 9ec17bf

Browse files
committed
Added Fun with HTML5 Canvas (wesbos#8)
1 parent 98c5bfe commit 9ec17bf

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,57 @@
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+
let isDrawing = false;
13+
let isGrowing = true;
14+
let lastX = 0;
15+
let lastY = 0;
16+
let hue = 0;
17+
18+
// Canvas initialization
19+
canvas.width = window.innerWidth;
20+
canvas.height = window.innerHeight;
21+
ctx.strokeStyle = '#BADA55';
22+
ctx.lineJoin = 'round';
23+
ctx.lineCap = 'round';
24+
ctx.globalCompositeOperation = 'darken';
25+
26+
function draw(e) {
27+
if(!isDrawing) return;
28+
29+
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
30+
31+
// Start
32+
ctx.beginPath();
33+
ctx.moveTo(lastX, lastY);
34+
35+
// Draw
36+
ctx.lineTo(e.offsetX, e.offsetY);
37+
ctx.stroke();
38+
[lastX, lastY] = [e.offsetX, e.offsetY];
39+
40+
// Change color
41+
if (hue > 360) hue = 0;
42+
hue++;
43+
44+
// Change brush size
45+
if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) isGrowing = !isGrowing;
46+
47+
if (isGrowing){
48+
ctx.lineWidth++;
49+
} else {
50+
ctx.lineWidth--;
51+
}
52+
}
53+
54+
canvas.addEventListener('mousemove', draw);
55+
canvas.addEventListener('mouseup', () => isDrawing = false);
56+
canvas.addEventListener('mouseout', () => isDrawing = false);
57+
canvas.addEventListener('mousedown', (e) => {
58+
isDrawing = true;
59+
[lastX,lastY] = [e.offsetX, e.offsetY];
60+
});
1061
</script>
1162

1263
<style>

0 commit comments

Comments
 (0)