HTML and CSS Reference
In-Depth Information
NOTE There is also a webgl context (sometimes available as experimental-webgl depending on the
browser) that exposes the WebGL rendering API, but because most mobile devices don't have WebGL en-
abled, this isn't covered in this topic.
Creating an Image from Canvas
The only other method with good cross-browser support is the canvas.toDataURL method, which returns a
data URL that represents a snapshot image of the current state of the Canvas. This image can generate an <img>
tag or save the image to a server. The method accepts an optional parameter indicating the file type to save,
either "image/png" or "image/jpeg" (Chrome also supports a new image type called "image/webp" ).
If this parameter isn't passed, the method defaults to generating a png. For JPEGs and webp you can also pass
a second optional quality parameter.
To generate images from a canvas tag you could write:
// Generate a PNG image
png = canvas.toDataURL();
png = canvas.toDataURL("image/png");
// Generate a JPG with quality 0.8
jpg = canvas.toDataURL("image/jpeg", 0,8);
You can test the toDataURL method by running the code in Listing 15-3 , which grabs a snapshot every
time you click or touch the Canvas.
Listing 15-3: to-data-url.html
<script src='jquery.min.js'></script>
<canvas id="mycanvas", width="400" height="400"></canvas>
<div id='snapshots'></div>
var canvas = $("#mycanvas")[0],
ctx = canvas.getContext("2d");
function randInt(max) {
return Math.floor(Math.random() * max);
function drawRandomRectangle() {
var r = randInt(255), g = randInt(255), b = randInt(255),
s = randInt(100), x = randInt(400), y = randInt(400);
ctx.fillStyle = "rgb(" + r + "," + g + "," + b + ")";
$(canvas).on("click touchstart",function(e) {
var url = canvas.toDataURL("image/png");
$("<img>").({ src: url, width: 100, height:100
Search WWH ::

Custom Search