Search code examples
javascriptdrawingcanvasdimensions

How to retrieve coords (x,y,w,h) of a rendered canvas element?


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 the 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 the 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 does this happen?


Solution

  • 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.