Visitar URL original
Day 8: Add drawing on Canvas · wesbos/JavaScript30@3d7179c · GitHub
Skip to content

Commit 3d7179c

Browse files
committed
Day 8: Add drawing on Canvas
This was pretty cool, it's wild how easy it is to get started with something as seemingly complicated as canvas with a great teacher.
1 parent e74bf18 commit 3d7179c

2 files changed

Lines changed: 68 additions & 0 deletions

File tree

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8">
5+
<title>HTML5 Canvas</title>
6+
</head>
7+
<body>
8+
<canvas id="draw" width="800" height="800"></canvas>
9+
<script src="day-08.js">
10+
</script>
11+
12+
<style>
13+
html, body {
14+
margin:0;
15+
}
16+
</style>
17+
18+
</body>
19+
</html>
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
const canvas = document.querySelector('#draw');
2+
const ctx = canvas.getContext('2d');
3+
4+
canvas.width = window.innerWidth;
5+
canvas.height = window.innerHeight;
6+
ctx.strokeStyle = '#b51f24';
7+
ctx.lineJoin = 'round';
8+
ctx.lineCap = 'round';
9+
ctx.lineWidth = 50;
10+
11+
let isDrawing = false;
12+
let lastX = 0;
13+
let lastY = 0;
14+
let hue = 0;
15+
let direction = true;
16+
17+
function draw(e) {
18+
if(!isDrawing) return; { // stop when not moused down
19+
console.log(e);
20+
ctx.strokeStyle = `hsl(${hue}, 100%, 50%)`;
21+
ctx.beginPath();
22+
ctx.moveTo(lastX, lastY);
23+
ctx.lineTo(e.offsetX, e.offsetY);
24+
ctx.stroke();
25+
[lastX, lastY] = [e.offsetX, e.offsetY];
26+
27+
hue++;
28+
if( hue >= 360) {
29+
hue = 0;
30+
}
31+
if( ctx.lineWidth >= 100 || ctx.lineWidth <= 1) {
32+
direction = !direction;
33+
}
34+
if(direction) {
35+
ctx.lineWidth++;
36+
} else {
37+
ctx.lineWidth--;
38+
}
39+
40+
}
41+
}
42+
43+
canvas.addEventListener('mousemove', draw);
44+
canvas.addEventListener('mousedown', (e)=> {
45+
isDrawing = true;
46+
[lastX, lastY] = [e.offsetX, e.offsetY];
47+
});
48+
canvas.addEventListener('mouseup', ()=> isDrawing = false);
49+
canvas.addEventListener('mouseout', ()=> isDrawing = false);

0 commit comments

Comments
 (0)