Page 1 of 3
Now available as a paperback or ebook from Amazon.
- Getting Started With Canvas
- Drawing Paths
Extract: Basic Paths
Extract: Bezier Curves
- Stroke and Fill
Extract: Stroke Properties
Extract: Fill and Holes
Extract: Text, Typography & SVG
- Clipping, Compositing and Effects
Extract: Clipping & Basic Compositing
- Generating Bitmaps
Extract: Introduction To Bitmaps
Extract : Animation **NEW!
- WebWorkers & OffscreenCanvas
- Typed Arrays
- Files, blobs, URLs & Fetch
Extract: Blobs & Files
Extract: Read/Writing Local Files
- Image Processing
Extract: The Filter API
- 3D WebGL
- 2D WebGL
Extract: WebGL Convolutions
Bitmaps, gifs, jpegs and so on are common in almost all web pages. With Canvas you now work with bitmaps at the pixel level. It's not difficult, but you need to organize things to make it really easy and a good understanding helps.
The Image Object
The most basic way of getting an image into a web page is the img tag:
<img src=url width="100" height="200">
This loads the bitmap specified by the url into the web page and displays it at 100 by 200 pixels irrespective of its actual size.
<img id="myImage" src=url width="100" height="200">
then you can get a reference to the HTMLImageElement using:
Now you can access the properties including height, width and naturalHeight, naturalWidth which give you the actual size of the bitmap.
You can use an HTMLImageElement that has been created in this way as the source of a bitmap to use with Canvas, but the problem is that the tag will be loaded along with the page and displayed.
creates an HTMLImageElement. You can start it loading a bitmap using:
If you just do this the bitmap will be loaded, but not displayed as the new HTMLImageElement isn't part of the DOM. To make it visible you have to add it to the DOM using one of the many methods provided for doing this. For example:
Where the bitmap appears depends on where it is added to the DOM. How big the image is displayed depends on what you set the height and width properties to. If you don't set them then the image is displayed at its full size, i.e. naturalHeight, naturalWidth.
var img1 = new Image(w,h);
is exactly equivalent to:
If you leave out w and h then the natural size of the bitmap is used. If you leave out h then the height is scaled correctly for the given w. So to load an image into an HTML page you might use something like:
var img1 = new Image(200);
img1.src = "jeep.jpg";
Notice that if you don't want the image to show in the web page you can simply not add it to the DOM.
var img1 = new Image();
img1.src = "jeep.jpg";
img1.width = img1.naturalWidth / 10;
img1.height = img1.naturalHeight / 10;
you will find that it doesn't work.