+ 2
How should I draw images on a canvas?
I saw an example of drawing an image on a canvas on W3schools, but it used an image that was added to the HTML-body with an img-tag. Is it possible to draw an image on a canvas without adding it as a visible image to the body? I saw also at W3schools an example where an image was drawn on the canvas, but the image was written in JS, but I didn't understand it totally. So, is it possible to do it in an easier way, by drawing the image in an image editor and adding it directly to the page, and if not, what is the most effective/fastest way to write it in JS with ImageData.data (and how does it work)?
3 Answers
+ 1
Just use the Image constructor:
var img = Image();
img.src = "http://example.com/image.png";
//You have to wait until the image has
//loaded before you can draw it:
img.onload = function() {
//Then you can draw it on your canvas
//Assuming you have the context of the
//canvas in a variable called c
c.drawImage(img, x, y, img.width, image.height);
//Replace x and y with coordinates.
//You can of course change the width
//and height as well.
};
If you want to use it in a frame loop, you should probably create a variable to tell if the image has loaded yet, then check that variable in the loop.
0
drawing an image in an editor and implement it with <img> is the normal way to do it. no canvas required. you might want to repeat the html course to recognize the correct usage...
doing a web research on the topic of drawing with javascript might lead you to the solution much quicker and structured than asking it here.
0
error on line 1 , I asked how to draw an image on a canvas, not how to use the img-tag. I know how to use an img-tag, but it doesn't work if I want to, as example, change the position of the image. And the HTML canvas lesson on SL doesn't teach how to draw images on a canvas.