HTML and CSS Reference
In-Depth Information
drawImage has best performance when it draws an image with the same scale as original image. It is a good idea
to avoid scaling because it has a performance impact. If you need to draw an image with scaling, you should consider
caching the scaled image with in-memory canvas, which I will describe later in the “In-Memory Canvas” section.
It also has less performance with anti-aliasing, even if the image is the same scale. One might think that
performance impact never happens with images of the same scale, but it can happen if you locate the image at a
nonintegral floating-point position. JavaScript has only floating-point types describing numbers. There is no integer
type inside JavaScript like C, so this happens easily. To fix it, just make the value integer . . . but never use Math.floor
to do this. Math.floor is a built-in function of JavaScript to make numbers integer, but it is much slower than
JavaScript implicit converting such as bit operations. Listing 16-6 shows how to make numbers integer.
Listing 16-6. ToInt
ctx.drawImage(img, x | 0, y | 0);
Some browsers have support to disable anti-aliasing. This is not standardized yet, so please be careful about
compatibility of browsers. Listing 16-7 shows how to disable anti-aliasing
Listing 16-7. ImageSmoothingEnable
ctx.webkitImageSmoothingEnabled = false;
In-Memory Canvas (Offscreen Canvas)
Many games draw the same shapes constantly. You can speed this up a lot if the frequency is expected to be more
than once. drawImage takes a Canvas element as the first argument, like img, so you can use the canvas as a cache.
The canvas used as a cache is not attached to the DOM; it's just created as an element. We call this kind of canvas
“in-memory canvas” or “offscreen canvas.” See Listing 16-8 for an example.
Listing 16-8. In-Memory Canvas
var cache = document.createElement("canvas");
Once you make this canvas and draw shapes used frequently, you just draw the canvas afterwards.
Listing 16-9 shows how to use in-memory canvas. First, prepare the scaled image as cache, and then draw the
cache to gain speed. See Figure 16-6 for an example.
Listing 16-9. In-Memory Canvas Example
onload = function() {
var img = document.createElement("img");
img.onload = function() {
var canvas = document.createElement("canvas");
canvas.width = canvas.height = 300;
document.body.appendChild(canvas);
var ctx = canvas.getContext("2d");
ctx.fillRect(0, 0, 300, 300);
var cache = document.createElement("canvas");
cache.width = img.width / 10;
cache.height = img.height / 10;
cache.getContext("2d").drawImage(img, 0, 0, img.width, img.height, 0, 0, cache.width, cache.height);
 
Search WWH ::




Custom Search