Reputation: 115
I was wondering how to resize a canvas and all of its drawings as the screen size changes. I know it is 100% possible as this game does (resize your browser and it will fit to any ratio).
http://html5games.com/Game/Smarty-Bubbles/d8f24956-dc91-4902-9096-a46cb1353b6f
Do I have to draw all my shapes with % or multiply them all by a % each time they are drawn? I can appreciate having to redraw on a screen size change but how do I affect the canvas and its components?
Upvotes: 1
Views: 687
Reputation: 105035
At the start of the app, save the beginning window width and the beginning canvas size.
var originalWindowWidth=window.innerWidth;
var canvas=document.getElementById('canvas');
var originalCanvasWidth=canvas.width;
var originalCanvasHeight=canvas.height;
Listen for the window resize event
Calculate by how much the window width as changed
scale=window.innerWidth/originalWindowWidth;
If your canvas content is complete & unchanging, you can rescale your canvas with CSS. This way you don't have to redraw the canvas content.
4a. (option#1) Scale using CSS:
// rescale both CSS width & height by the SAME SCALE FACTOR
$('#canvas').css('width',originalCanvasWidth*scale);
$('#canvas').css('width',originalCanvasWidth*scale);
If your canvas content is not complete & unchanging, you should rescale your canvas element itself. This causes all canvas content to be lost so you must redraw it. You can use the context.scale
command to automatically redraw your content at the new scale factor. Using this method is also less likely to result in pixelated content versus resizing with CSS which "stretches" & "squeezes" existing pixels to fit the new CSS size.
4b. (Option#2) Scale the canvas element itself
var canvas=document.getElementById("myCanvas");
var ctx=canvas.getContext("2d");
canvas.width=originalCanvasWidth*scale;
canvas.height=originalCanvasHeight*scale;
context.scale(scale,scale);
// now reissue all the drawing commands
// (no need to adjust coordinates or sizes -- context.scale does that for you!
Upvotes: 1