Visitar URL original
08 canvas finis · wesbos/JavaScript30@757d045 · GitHub
Skip to content

Commit 757d045

Browse files
committed
08 canvas finis
1 parent 657673b commit 757d045

1 file changed

Lines changed: 60 additions & 7 deletions

File tree

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

Lines changed: 60 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,68 @@
55
<title>HTML5 Canvas</title>
66
</head>
77
<body>
8-
<canvas id="draw" width="800" height="800"></canvas>
9-
<script>
10-
</script>
8+
<h1>Draw on me!</h1>
9+
<canvas id="draw" width="800" height="800"></canvas>
10+
<script>
1111

12-
<style>
13-
html, body {
14-
margin:0;
12+
let isDrawing = false; // flag to know when mouse is actually clicked down
13+
let lastX = 0;
14+
let lastY = 0;
15+
let hue = 0; // 0-360, resets after 360
16+
let direction = true;
17+
18+
const canvas = document.querySelector('#draw');
19+
const ctx = canvas.getContext('2d'); // where we do all drawing
20+
// resize the canvas
21+
canvas.width = window.innerWidth;
22+
canvas.height = window.innerHeight;
23+
// set paintbrush settings
24+
ctx.strokeStyle = '#BADA55';
25+
ctx.lineJoin = 'round';
26+
ctx.lineCap = 'round';
27+
ctx.lineWidth = 10;
28+
// ctx.globalCompositeOperation = 'multiply'; // subtract, lighten etc
29+
30+
function draw(event) {
31+
if (!isDrawing) {
32+
return; // don't run when not moused down
33+
}
34+
// paint color
35+
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`; // hue, saturation, lightness
36+
37+
ctx.beginPath();
38+
ctx.moveTo(lastX, lastY);
39+
ctx.lineTo(event.offsetX, event.offsetY);
40+
ctx.stroke(); // actually draw
41+
42+
[lastX, lastY] = [event.offsetX, event.offsetY];
43+
hue++;
44+
// increment paint size from 0-100, then back down to 1
45+
if (ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {
46+
direction = !direction; // flip direction
47+
}
48+
if (direction) {
49+
ctx.lineWidth++;
50+
} else {
51+
ctx.lineWidth--;
52+
}
1553
}
16-
</style>
54+
55+
canvas.addEventListener('mousedown', (e) => {
56+
isDrawing = true;
57+
[lastX, lastY] = [e.offsetX, e.offsetY];
58+
});
59+
canvas.addEventListener('mouseup', () => isDrawing = false);
60+
canvas.addEventListener('mouseout', () => isDrawing = false);
61+
canvas.addEventListener('mousemove', draw);
62+
63+
</script>
64+
65+
<style>
66+
html, body {
67+
margin:0;
68+
}
69+
</style>
1770

1871
</body>
1972
</html>

0 commit comments

Comments
 (0)