Skip to content

Commit 3d8481f

Browse files
committed
very simple paint brush
1 parent a465ea0 commit 3d8481f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

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

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,65 @@
77
<body>
88
<canvas id="draw" width="800" height="800"></canvas>
99
<script>
10+
// set up drawing parameters
11+
var lastX = 0;
12+
var lastY = 0;
13+
var isDrawing = false;
14+
var maxWidth = 50;
15+
var minWidth = 5;
16+
var hue = 1;
17+
var direction = 1;
18+
19+
// set up canvas
20+
var canvas = document.getElementById('draw');
21+
var ctx = canvas.getContext('2d');
22+
ctx.canvas.width = window.innerWidth;
23+
ctx.canvas.height = window.innerHeight;
24+
ctx.lineWidth = minWidth;
25+
ctx.strokeStyle = 'red';
26+
ctx.lineJoin = 'round';
27+
ctx.lineCap = 'round';
28+
29+
var stopDrawing = function() {
30+
isDrawing = false;
31+
}
32+
33+
var startDrawing = function(e) {
34+
isDrawing = true;
35+
lastX = e.offsetX;
36+
lastY = e.offsetY;
37+
}
38+
39+
var draw = function(e) {
40+
if (!isDrawing) {
41+
return;
42+
}
43+
// handle the drawing
44+
ctx.strokeStyle = 'hsl(' + hue.toString() + ', 100%, 50%)';
45+
ctx.beginPath();
46+
ctx.moveTo(lastX, lastY);
47+
ctx.lineTo(e.offsetX, e.offsetY);
48+
ctx.stroke();
49+
50+
// reset current location
51+
lastX = e.offsetX;
52+
lastY = e.offsetY;
53+
54+
// make the line change widths
55+
if (ctx.lineWidth > maxWidth || ctx.lineWidth < minWidth) {
56+
direction *= -1;
57+
}
58+
ctx.lineWidth += direction;
59+
60+
// draw in rainbow colors
61+
hue += 0.25;
62+
hue %= 360;
63+
}
64+
65+
canvas.addEventListener('mousedown', startDrawing);
66+
canvas.addEventListener('mousemove', draw);
67+
canvas.addEventListener('mouseup', stopDrawing);
68+
canvas.addEventListener('mouseout', stopDrawing);
1069
</script>
1170

1271
<style>

0 commit comments

Comments
 (0)