Changing The Clicked Image In The Canvas
i am making this simple canvas . it has three images in it (identical images). i want to change only the clicked image. what i am trying to do is save the image order in a array .
Solution 1:
This is how I would do it. Basically you need to store the x,y,width,height
of each image. You need these values so that when you click within the canvas you can check the bounds of each image against the x and y of the mouse click. After that its easy to reference which image was clicked. Hopefully the following code is enough to get you on the right track.
var canvas = document.getElementById("myCanvas"),
ctx = canvas.getContext("2d");
ctx.fillStyle = "#f00";
ctx.strokeStyle = "#0f0";
var images = [];
images.push({x : 10, y : 10, width:50, height:50}, {x : 70, y : 10, width:50, height:50}, {x : 130, y : 10, width:50, height:50});
//draw some rects, this would be your imagesfor(var i = 0; i < images.length; i++){
ctx.fillRect(images[i].x, images[i].y, images[i].width, images[i].height);
}
canvas.onclick = function(e){
var x = 0,
y = 0;
if (e.pageX || e.pageY) {
x = e.pageX;
y = e.pageY;
}
else {
x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
}
x -= canvas.offsetLeft;
y -= canvas.offsetTop;
// This is where you go through all the images, and check the x and y from the mouse event against your images.for(var i = 0; i < images.length; i++){
if(x > images[i].x && x < images[i].x + images[i].width && y > images[i].y && y < images[i].y + images[i].height){
ctx.strokeRect(images[i].x, images[i].y, images[i].width, images[i].height);
alert('Image ' + i + ' selected');
}
}
}
Post a Comment for "Changing The Clicked Image In The Canvas"