Wikia

JavaScript Wiki

Watchlist Recent changes

Canvas

The HTML5 tag <canvas> can be used to draw vector graphics using JavaScript.

Contents

getContextEdit

To draw graphics on a canvas you have to get the context, like this:

var canvas = document.getElementById("canvas");  
var context = canvas.getContext("2d");


FunctionsEdit

drawImage()Edit

drawImage() imports an image file to the canvas:

var myImage= new Image();
myImage.src="my_image.png";
context.drawImage(myImage,0,0);

You can use every format supported by the HTML <img> tag.

rotate()Edit

The rotate() function rotates the coordinate system for the canvas:

context.rotate(Math.PI / 180);

The value must be in radians.

If you want to rotate only one element (an image for instance), you have to save and restore the context like this:

context.save();
context.rotate(Math.PI / 180);
context.drawImage(myImage,0,0);
context.restore();
//The rest of the drawing will not be rotated.

strokeRect()Edit

You can use strokeRect(x, y, width, height) to draw a rectangle.

//We first define the color with the strokeStyle property.
context.strokeStyle="#900";
//Then we draw the rectangle.
context.strokeRect(20,30,100,50);

getImageData() and putImagedata() Edit

If you want to manipulate individual pixels, you can use the getImageData() to retrieve a set of pixels, and putImageData to place it within the array. These two functions use the ImageData object, where pixels may be accessed in a single array.

External links Edit

Pages on JavaScript Wiki

Add a Page
75pages on
this wiki
Advertisement | Your ad here

Latest Photos

Add a Photo
17photos on this wiki
See more >

Recent Wiki Activity

See more >

Around Wikia's network

Random Wiki