-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlazycanvas.html
80 lines (72 loc) · 2.58 KB
/
lazycanvas.html
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<html>
<head>
<style type="text/css" media="screen">
</style>
<style>
canvas {
border: solid black 1px;
}
</style>
</head>
<h1>Lazy Canvas Context</h1>
<p>
<a href="https://github.com/thomasballinger/dalsegno/blob/master/LazyCanvasCtx.js">Source code on GitHub</a>
</p>
<canvas id="canvas" width="500" height="200"></canvas>
<p>
On this web page the scripts
<code><pre>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
<script src="LazyCanvasCtx.js"></script>
<script>
var ctx = new LazyCanvasCtx('canvas');
</script>
</pre></code>
have been run. Open the JavaScript console to play with this <code>ctx</code> object, which
behaves mostly like a <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">normal canvas 2d context object</a>.
</p>
<p>
For example, try
</p>
<code><pre>
ctx.fillRect(0, 0, 100, 200);
</pre></code>
<p>This should immediately draw a black rectangle.</p>
<p>
But once you set <code>ctx.lazy = true</code> further draw operations will be saved instead of running right away:
</p>
<code><pre>
ctx.lazy = true;
ctx.fillRect(50, 50, 200, 10); // nothing happens!
ctx.strokeStyle="#FF0000";
ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();
</pre></code>
You can run run these queued drawing operations by calling the trigger method:
<code><pre>
ctx.trigger() // all the queued drawing operations occur
</pre></code>
Some interactions, like reading a data property on the context, will force execution of pending operations in order to ensure an up-to-date value is returned.
<code><pre>
ctx.lazy = true;
ctx.fillRect(50, 50, 200, 10); // nothing happens
console.log(ctx.strokeStyle); // implicit .trigger() call, queued operations are run
</pre></code>
<h2>Purpose</h2>
<p>
This might be useful for batching draw operations that logically go together, but could be interrupted by DOM renders that would show the intermediate state.
</p>
<!--There are some odd script tag choices here so that this file works in two situations:
1) on a developer's computer without internet (files served locally)
2) online at https://rawgit.com/thomasballinger/dalsegno/master/lazycanvas.html (so files
that are not part of the repository, so can't be relatively linked, are served from cdns
-->
<script src="Immutable.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>
<!-- one of these two may fail -->
<script src="LazyCanvasCtx.js"></script>
<script>
var ctx = new LazyCanvasCtx('canvas');
</script>
</html>