forked from marijnh/Eloquent-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path19_2_efficient_drawing.html
More file actions
37 lines (32 loc) · 1.03 KB
/
19_2_efficient_drawing.html
File metadata and controls
37 lines (32 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!doctype html>
<base href="https://eloquentjavascript.net/">
<script src="code/chapter/19_paint.js"></script>
<div></div>
<script>
PictureCanvas.prototype.syncState = function(picture) {
if (this.picture == picture) return;
drawPicture(picture, this.dom, scale, this.picture);
this.picture = picture;
}
function drawPicture(picture, canvas, scale, previous) {
if (previous == null ||
previous.width != picture.width ||
previous.height != picture.height) {
canvas.width = picture.width * scale;
canvas.height = picture.height * scale;
previous = null;
}
let cx = canvas.getContext("2d");
for (let y = 0; y < picture.height; y++) {
for (let x = 0; x < picture.width; x++) {
let color = picture.pixel(x, y);
if (previous == null || previous.pixel(x, y) != color) {
cx.fillStyle = color;
cx.fillRect(x * scale, y * scale, scale, scale);
}
}
}
}
document.querySelector("div")
.appendChild(startPixelEditor({}));
</script>