starscape
starscape

Reputation: 2973

HTML5/Javascript - How to get the coordinates of a shape/image on the canvas?

Say I drew a rectangle on the canvas. Surely there is some sort of built in method to get the XY coordinates, and dimensions of that rectangle? But after some googling I came up with nothing. And just to clarify, I am not talking about the coordinates of the canvas element itself, but rather a shape/image that is drawn unto the canvas.

Any help is appreciated.

Upvotes: 2

Views: 7152

Answers (3)

Ben
Ben

Reputation: 10146

Basically, you should be using canvas as a means to output graphics to the screen and the rest of your logic goes straight into the JavaScript that powers your game/application. The best way to go about making something like this is to create objects and assign properties to them; in its simplest form that can look like this:

function Player(x, y)
{
    this.x = x;
    this.y = y;
}

var examplePlayerObject = new Player(20, 20);

By extending this object via prototyping you can create multiple copies of an object that has the exact same functions; such as draw. Drawing the player in this instance could just be a red square that is 20px*20px.

Player.prototype.draw = function()
{
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = 'red';
    context.fillRect(this.x, this.y, 20, 20);
}

Then, you should have an update step with some means of clearing what is on the screen and redrawing the parts which have changed.

function animationStep()
{
    examplePlayerObject.x++;
    examplePlayerObject.y++;
    examplePlayerObject.draw();
}

This animation step should run each frame; look into requestAnimationFrame for smooth animation. Paul Irish has a good shim for older browsers. Add in requestAnimationFrame(animationStep) at the end of that function and you will have a red square moving slowly across the screen. Good luck!

Upvotes: 0

Ivan Kuckir
Ivan Kuckir

Reputation: 2549

Canvas is 2D table (Array) of numbers (= pixels = colors). When drawing into canvas, you are just editing this table. When you draw into canvas (= change numbers in table), what should be the coordinates of your adjustment?

If you are drawing rectangles only and you can define the coordinates for your rectangle, you must know your coordinates inside a program, because you have just drawn it.

If you want your image to be separated into some "objects" (shapes), you should use SVG.

Upvotes: 1

George
George

Reputation: 4257

If you're talking about a 2D canvas drawing, then the drawing maps 1:1 with screen coordinates, so it is just location of <canvas> + location of the drawing.

To clarify, drawing on a <canvas> basically just changes the pixels of the canvas - after you draw to it, you can't reference the drawn object the same way you can reference an html element.

Upvotes: 1

Related Questions