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!