Skip to content

Commit 1bbfef7

Browse files
committed
08: add my JavaScript code
Signed-off-by: Soshi Katsuta <soshi.katsuta@gmail.com>
1 parent 6320c80 commit 1bbfef7

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

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

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@
66
</head>
77
<body>
88
<canvas id="draw" width="800" height="800"></canvas>
9-
<script>
10-
</script>
9+
<script src="index.js"></script>
1110

1211
<style>
1312
html, body {
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Painter {
2+
constructor(ctx) {
3+
ctx.strokeStyle = '#BADA55';
4+
ctx.lineJoin = 'round';
5+
ctx.lineCap = 'round';
6+
this.ctx = ctx;
7+
8+
this.MIN_LINE_WIDTH = 1;
9+
this.MAX_LINE_WIDTH = 100;
10+
11+
this.isDrawing = false;
12+
this.lastX = this.lastY = 0;
13+
this.hue = 0;
14+
this.direction = true;
15+
}
16+
17+
draw(e) {
18+
if (!this.isDrawing) { return; }
19+
20+
const ctx = this.ctx;
21+
ctx.strokeStyle = `hsl(${this.hue}, 100%, 50%)`;
22+
ctx.beginPath();
23+
ctx.moveTo(this.lastX, this.lastY);
24+
ctx.lineTo(e.offsetX, e.offsetY);
25+
ctx.stroke();
26+
27+
[this.lastX, this.lastY] = [e.offsetX, e.offsetY];
28+
this.hue < 360 ? this.hue++ : this.hue = 0;
29+
30+
if (ctx.lineWidth <= this.MIN_LINE_WIDTH || ctx.lineWidth >= this.MAX_LINE_WIDTH) {
31+
this.direction = !this.direction;
32+
}
33+
this.direction ? ctx.lineWidth++ : ctx.lineWidth--;
34+
}
35+
36+
startDrawing(e) {
37+
this.isDrawing = true;
38+
[this.lastX, this.lastY] = [e.offsetX, e.offsetY];
39+
}
40+
41+
stopDrawing() {
42+
this.isDrawing = false;
43+
}
44+
}
45+
46+
const canvas = document.querySelector('#draw');
47+
canvas.width = window.innerWidth;
48+
canvas.height = window.innerHeight;
49+
const painter = new Painter(canvas.getContext('2d'));
50+
[
51+
{ eventType: 'mousemove', callback: e => painter.draw(e) },
52+
{ eventType: 'mousedown', callback: e => painter.startDrawing(e) },
53+
{ eventType: 'mouseup', callback: () => painter.stopDrawing() },
54+
{ eventType: 'mouseout', callback: () => painter.stopDrawing() }
55+
].forEach(({eventType, callback}) => canvas.addEventListener(eventType, callback));

0 commit comments

Comments
 (0)