Until now we have created our own shapes and
applied styles to them. One of the more exciting features of Importing images into a canvas is basically a two step process: Let's take a look at how to do this. is the ability to use images. These can be used to do dynamic photo compositing or as backdrops of graphs, for sprites in games, and so forth. External images can be used in any format supported by the
browser, such as PNG, GIF, or JPEG. You can even use the image produced by other canvas elements on the same page as the source!
HTMLImageElement
object or to another canvas element as a source. It is also possible to use images by providing a URL.drawImage[]
function.
Getting images to draw
The canvas API is able to use any of the following data types as an image source:
HTMLImageElement
These are images created using the Image[]
constructor, as well as any
And here's some CSS to make things look nice:
body {
background: 0 -100px repeat-x url[bg_gallery.png] #4f191a;
margin: 10px;
}
img {
display: none;
}
table {
margin: 0 auto;
}
td {
padding: 15px;
}
Tying it all together is the JavaScript to draw our framed images:
function draw[] {
// Loop through all images
for [const image of document.images] {
// Don't add a canvas for the frame image
if [image.getAttribute['id'] !== 'frame'] {
// Create canvas element
const canvas = document.createElement["canvas"];
canvas.setAttribute["width", 132];
canvas.setAttribute["height", 150];
// Insert before the image
image.parentNode.insertBefore[canvas, image];
ctx = canvas.getContext["2d"];
// Draw image to canvas
ctx.drawImage[image, 15, 20];
// Add frame
ctx.drawImage[document.getElementById["frame"], 0, 0];
}
}
}
Controlling image scaling behavior
As mentioned previously, scaling images can result in fuzzy or blocky artifacts due to the scaling process. You can use the drawing context's
imageSmoothingEnabled
property to control the use of image smoothing algorithms when scaling images within your context. By default, this is true
, meaning images will be smoothed when scaled. You can disable this feature like this:
ctx.mozImageSmoothingEnabled = false;
ctx.webkitImageSmoothingEnabled = false;
ctx.msImageSmoothingEnabled = false;
ctx.imageSmoothingEnabled = false;
- « Previous
- Next »