Click here to Skip to main content
15,886,004 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to display a image multiple times at different locations on a html5 canvas and don't know how to go about doing it. I can draw one image easily but have to find how to do it more than 1 times. Can anyone help me.


what am I doing wrong because it only prints one image on the canvas.

JavaScript
function imageloader() 
{
	//Getting ID's
    imagehtml5canvas = document.getElementById('imagehtml5canvas');
    imagecanvasarea = imagehtml5canvas.getContext("2d");

	xposition = Math.random();
	yposition = Math.random();
	nImages=20;
	
	var CanvasImage = new Image();
	CanvasImage.src = "images/monalisa.jpg"; 		
     CanvasImage.onload = function() {

	
	for(var i=0;i<nImages;i++){
				imagecanvasarea.drawImage(CanvasImage,xposition,yposition,50,50);
		}
    };	  
}
Posted
Updated 3-Aug-13 8:39am
v2
Comments
Graham Breach 3-Aug-13 10:32am    
Call drawImage() multiple times with different X and Y coordinates. I'm not sure why you would have a problem with that.
[no name] 3-Aug-13 14:46pm    
Looks like it's drawing your images 20 times to me. Are you sure it's only once? You probably think it's only once because you are drawing all 20 images at the same location.
Kieran82 3-Aug-13 14:55pm    
I put it x and y position at math .random

1 solution

It seems like it happens because you calculate the random number once and, use the same calculated numbers for the whole of the images. In addition to that, the Math.random function gives a number between 0 to 1. So, in order to get different locations, you can multiply the random results with some value.


Try to calculate the random location inside the loop. Something like:


JavaScript
for(var i=0;i<nImages;i++){
    xposition = Math.random() * 100;
    yposition = Math.random() * 100;
    imagecanvasarea.drawImage(CanvasImage,xposition,yposition,50,50);
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900