beakr
beakr

Reputation: 5857

How to get the X/Y values of an image drawn on an HTML5 canvas?

Let's say I have an image being drawn on a canvas like so:

myImage = new Image();
canvasContext.drawImage(myImage, 50, 50);
myImage.src = "foo.png"

How do I get the X/Y value of myImage on the canvas?

Upvotes: 1

Views: 353

Answers (1)

user1693593
user1693593

Reputation:

When you draw an image or any other shape on canvas, it just blends in with the rest of the pixels and the canvas does not know what you just drew where.

In order to keep track of where it was drawn you need to maintain this with for example an object array:

function CanvasImage(img, x, y) {
    this.image = img;
    this.x = x;
    this.y = y;
    this.draw = function(ctx) {
        ctx.drawImage(img, x, y);
    }
    return this;
}

Now you can keep track of where the images are drawn by doing:

var myImages = [];
var myCanvasImage = new CanvasImage(img, 50, 50);

myImages.push(myCanvasImage);

myCanvasImage.draw();

When you need the coordinate of the image you can iterate through the array and read the x and y. If you have several images an id can be a nice thing or you can use the src property of the image to identify which image you're dealing with (id is better in case you draw the same image several times to the canvas).

alert(myCanvasImage.x + ' ' +myCanvasImage.y);

Also remember to handle the image in the onload event to be sure the image has loaded properly:

myImage = new Image();
myImage.onload = function() {
    /// continue here...
}
myImage.src = "foo.png";

Upvotes: 1

Related Questions