Skip to content

Commit a1064df

Browse files
committed
Build canvas painter
1 parent aa278d5 commit a1064df

1 file changed

Lines changed: 77 additions & 0 deletions

File tree

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

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,83 @@
77
<body>
88
<canvas id="draw" width="800" height="800"></canvas>
99
<script>
10+
11+
// Define Constants
12+
const canvas = document.querySelector("#draw");
13+
const ctx = canvas.getContext("2d");
14+
15+
// Resize Canvas
16+
canvas.width = window.innerWidth;
17+
canvas.height = window.innerHeight;
18+
19+
// Set Defaults
20+
ctx.strokeStyle = "#f00";
21+
ctx.lineJoin = "round";
22+
ctx.lineCap = "round";
23+
ctx.lineWidth = 100;
24+
25+
let isDrawing = false;
26+
let lastX = 0;
27+
let lastY = 0;
28+
let hue = 0;
29+
30+
let direction = true;
31+
32+
function draw(e){
33+
34+
if(!isDrawing) return;
35+
36+
console.log(e);
37+
38+
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
39+
ctx.lineWidth = hue;
40+
ctx.beginPath();
41+
ctx.moveTo(lastX, lastY);
42+
ctx.lineTo(e.offsetX, e.offsetY);
43+
ctx.stroke();
44+
45+
lastX = e.offsetX;
46+
lastY = e.offsetY;
47+
48+
hue++;
49+
50+
if( hue >= 360 ){
51+
52+
hue = 0;
53+
}
54+
55+
if( ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {
56+
57+
direction = !direction;
58+
59+
}
60+
61+
if( direction ){
62+
63+
ctx.lineWidth++;
64+
65+
} else {
66+
67+
ctx.lineWidth--;
68+
69+
}
70+
71+
}
72+
73+
// Drawing Events
74+
canvas.addEventListener('mousedown', (e) => {
75+
76+
isDrawing = true
77+
78+
lastX = e.offsetX;
79+
lastY = e.offsetY;
80+
81+
});
82+
83+
canvas.addEventListener('mousemove', draw);
84+
canvas.addEventListener('mouseup', () => isDrawing = false);
85+
canvas.addEventListener('mouseout', () => isDrawing = false);
86+
1087
</script>
1188

1289
<style>

0 commit comments

Comments
 (0)