I’d like to have a canvas on my html page, with width = 100%. I’d like to then get the width in pixels of the canvas at runtime. Something like:
Canvas c = Canvas.createIfSupported();
c.setWidth("100%");
c.setHeight("100%");
// let's draw a rectangle to fill the whole canvas:
c.getContext2d().rect(0, 0, ?, ?); // <-- what's its actual width/height?
Thanks
It’s (surprisingly)
… no matter what the actual pixel size of the canvas is. The reason is, that 300×150 is the default coordinate space size, see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
You can change this by using
canvas.setCoordinateSpaceWidth()andcanvas.setCoordinateSpaceHeight()to anything you want.Often, people want to draw independently of the actual size of the canvas, so they just set the coordinate space to something like 100×100, and the drawn image gets scaled automatically.
However, you may want to find out about the actual canvas pixel size:
Note, that this must be done in
scheduleDeferred, because the client size will only be known after the browser had a chance to perform the layout.You can use this information to adjust the aspect ratio to match the canvas (which I would recommend, because otherwise you get distorted images)
Or, alternatively, you can also set the coordinate space to match the pixel size, so you can perform pixel-exact drawing on an HTML5 canvas:
After the coordinate space has been set up, you can call
drawMyImage()