HTML and CSS Reference
In-Depth Information
var ctx = document.querySelector('canvas').
¬ getContext('2d');
ctx.fillStyle = 'rgb(0, 0, 255)';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.fillStyle = 'rgb(0, 255, 0)';
ctx.fillRect(10, 20, 50, 50); // little square
window.location = ctx.canvas.toDataURL('image/png');
Finally, the toDataURL also takes an optional second argument
that is available only if image/jpg has been implemented to
allow you to specify the quality level of the generated image.
This value would be between 0.0 and 1, with 1 being the highest
quality available—but be careful, as this will affect the size of the
final image, and, in our case, the size of the Base64 data string
generated by the toDataURL method.
Animating your canvas paintings
Yo u ' v e s e e n s o m e b a s i c a n i m a t i o n s u s i n g c a n v a s t h r o u g h o u t
this chapter, but I wanted to explain some of the concepts in
detail here.
Simple animation is mostly about clearing the current canvas
state and drawing the whole thing again. This is very quick to
do, as the canvas is a native drawing API. I'll show you a demo
that takes Bruce's bouncy head and bounces it around the can-
vas area. This example is based on the canvas breakout tutorial
by Bill Mill, but I jazzed it up with Bruce's mug bouncing instead
of a solid black ball.
The Processing JavaScript Library
As you'll find out, it's a blast to navigate around the canvas with a pen
drawing lines and filling shapes, but there are already some libraries
available that make working with the canvas much easier. One such
library is called processing.js ( ) , written by the
author of jQuery, John Resig.
It's not actually a library designed to ease working with canvas, but it in
fact interprets the Processing language in JavaScript, which is in turn
drawn on the canvas element. In many ways, processing.js is a great
tool for visualisation and abstracts away a lot of the more complicated
drawing and animation procedures in the 2D drawing API.
Search WWH ::

Custom Search