views:

180

answers:

1

How i can get coords of a rendered canvas element? I need them to apply clearRect, fillRect etc to its area.

I get the canvas:

//html
<div><canvas id="canvas_id">some useless text..</canvas></div>

//javascript   
var ctx = document.getElementById('canvas_id').getContext('2d');

Then? there is a way to get top left x, top left y, width and height of this?

@update after moonshadow's answer:

thx for answer, i know that operations are relative to the canvas, but i asked the question because i don't explain myself this behaviour: i have done a test file with a canvas object (http://avastreg.ilbello.com/canvas/test.html).

Here i've put a form in which dimensions for clearRect can be sended through the form. When you trigger mouseover on the canvas (NEWS), it applies clearRect with that coords. On mouseout he refills.

Starting value are :

x = 0, y = 0, w = 200, h = 200. Notice that doesn't work.

Then try something like

x: -10000, y: -10000, w: 50000000, h: 50000000 => it seems a joke but this works!

With other values it goes partially cleared. Why this happens?

+3  A: 

The canvas's width and height are in its offsetWidth and offsetHeight.

I've used code like this in the past to find the top and left of the canvas:

var canvasTop = 0;
var canvasLeft = 0;
var c = document.getElementById('canvas_id');
while( c && ( c != document.body ) )
{
  canvasTop += c.offsetTop;
  canvasLeft += c.offsetLeft;
  c = c.offsetParent;
}

In general, quirksmode.org has a big list of what these properties are called and which browsers support which.

Bear in mind that coordinates for operations on the graphics context, like fillRect, clearRect etc. are relative to the canvas, not the whole document, by default so you don't need to add the canvas's top and left to the coordinates you want to draw at.

moonshadow
thx for the answer, maybe you can solve my problem: check for the updated question (i updated directy it because so it's more visible)
avastreg
Your NEWS text appears to be a child of the canvas, and you are trying to use the draw operations to affect it. Don't do that, the behaviour is undefined; canvas should never have children. Either draw the text into the canvas or overlay an opaque canvas over the text using absolute positioning.
moonshadow
thank you i didn't know it! tomorrow i'll try to fix that!
avastreg