HTML and CSS Reference
In-Depth Information
To get around this, you can check for a property on the window variable called win-
dow.devicePixelRatio , which can give you the multiplier of the ratio of a device to CSS pixels. Using
that multiplier you can scale up the canvas element's pixel size while keeping the CSS size fixed. By adding in
a scale onto the context, your game won't need to know that the <canvas> element has been rescaled, and
you can continue to use CSS pixels to position elements in the game. Listing 15-2 shows how to do this.
Listing 15-2: Rescaling for high-resolution devices
var $canvas = $("#mycanvas"),
Canvas = $canvas[0],
ctx = canvas.getContext("2d");
if (window.devicePixelRatio) {
var pixelWidth = canvas.width,
pixelHeight = canvas.height;
canvas.width = pixelWidth * window.devicePixelRatio;
canvas.height = pixelHeight * window.devicePixelRatio;
$canvas.css({ width: pixelWidth, height: pixelHeight });
ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
}
The code grabs the original width and height properties on the <canvas> element and then rescales the
pixel width and height up by the devicePixelRatio . It then sets the CSS width and height to their original
size, so the canvas element isn't resized. Finally, it uses the scale method (more on transforms later in this
chapter) to scale up all calls on the context.
Grabbing the Rendering Context
The majority of the interesting stuff you might do with the <canvas> tag is done using the element's context,
which as you've seen in a lot of places throughout this topic is retrieved by calling:
var ctx = canvas.getContext("2d");
2-D is the only context currently supported across all modern browsers. All drawing calls are always per-
formed on the context and not the canvas element.
If Canvas isn't supported by the browser, the getContext method won't be present on the canvas element.
As you've also seen earlier in this topic, you can determine whether a browser supports the tag by checking for
the presence of the getContext method on a newly created <canvas> element:
var hasCanvas = document.createElement("canvas").getContext ? true :
false;
You can also check for the presence of the method on an existing <canvas> element on the page.
The variable ctx refers to an arbitrary 2-D rendering context throughout this chapter, but you can of course
stick the context in any variable, and you might have multiple contexts for multiple canvas elements on the
page.
 
 
Search WWH ::




Custom Search