Andrew Howard
Andrew Howard

Reputation: 3082

HTML5 canvas - Full extents of the browser window

What's the best way to get an HTML5 canvas to go to the full extents of the browser?

  1. Position absolute it, with top, left, right and bottom set to zero?
  2. Or have javascript read the document width and height and set the canvas to those dimensions?

Upvotes: 0

Views: 131

Answers (1)

Philipp
Philipp

Reputation: 69663

When you use CSS to control the size of a canvas, the canvas output will be scaled. This makes programming a bit easier because the canvas retains its internal resolution, but the result is that the graphic output gets blurry.

You won't have the problem with blurry graphics when you add an event listener to window.onresize and adjust canvas.width and canvas.height whenever the window is resized, but now your application will have to deal with the additional complexity that the canvas resolution is variable and can change at any time.

To work around the latter problem you can use context.scale in the resize event-handler to adjust the coordinate system of your canvas to the new window-size. This will allow the rest of your code to work with a constant coordinate system. Keep in mind that all transformation functions work cumulative, so multiple calls to scale can have unexpected results. But you can reset all transformations to default by calling context.setTransform(1, 0, 0, 1, 0, 0).

Upvotes: 1

Related Questions