Skip to content

Commit 7535672

Browse files
committed
Efficient drawing
1 parent 85f75db commit 7535672

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

chapter-19/efficient-drawing.html

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<!DOCTYPE html>
2+
<meta charset="utf-8" />
3+
<script src="paint.js"></script>
4+
5+
<div></div>
6+
<script>
7+
PictureCanvas.prototype.syncState = function (picture) {
8+
if (this.picture == picture) return;
9+
const prevPicture = this.picture;
10+
this.picture = picture;
11+
drawPicture(this.picture, this.dom, scale, prevPicture);
12+
};
13+
14+
function drawPicture(picture, canvas, scale, prevPicture) {
15+
if (canvas.width !== picture.width * scale) {
16+
canvas.width = picture.width * scale;
17+
prevPicture = null;
18+
}
19+
if (canvas.height !== picture.height * scale) {
20+
canvas.height = picture.height * scale;
21+
prevPicture = null;
22+
}
23+
let cx = canvas.getContext('2d');
24+
25+
for (let y = 0; y < picture.height; y++) {
26+
for (let x = 0; x < picture.width; x++) {
27+
if (!prevPicture || prevPicture.pixel(x, y) !== picture.pixel(x, y)) {
28+
cx.fillStyle = picture.pixel(x, y);
29+
cx.fillRect(x * scale, y * scale, scale, scale);
30+
}
31+
}
32+
}
33+
}
34+
35+
document.querySelector('div').appendChild(startPixelEditor({}));
36+
</script>

0 commit comments

Comments
 (0)