HTML5 Canvas resolution and size relation
Same sizes, different resolutions.
by Sub Lines
HTML
<!-- The HTML attributes describe the LOGICAL SIZE of the canvas -->
<!-- The second and third canvases are based on the size of the first one -->
<p>This canvas has full-resolution</p>
<canvas id="canvas1" width=400 height=200></canvas>
<p>This canvas has 50% the resolution</p>
<canvas id="canvas2"></canvas>
<p>This canvas has 25% the resolution</p>
<canvas id="canvas3"></canvas>
CSS
/* The CSS properties describe the VISUAL SIZE of the canvas */
html{min-height: 100%; min-width: 100%;}
body {min-height: 100%; min-width: 100%; margin: 0;}
canvas {
width: 400px;
height: 200px;
}
JavaScript
var canvas1 = document.getElementById("canvas1");
var ctx1 = canvas1.getContext("2d");
var canvas2 = document.getElementById("canvas2");
var ctx2 = canvas2.getContext("2d");
var canvas3 = document.getElementById("canvas3");
var ctx3 = canvas3.getContext("2d");
var scaleFactor1=0.50;
var scaleFactor2=0.25;
var img = document.createElement("img");
img.onload = function () {
// draw the first image full-size
ctx1.drawImage(img, 0, 0);
canvas2.width=canvas1.width*scaleFactor1;
canvas2.height=canvas1.height*scaleFactor1;
// draw a scaled-down image into the second canvas
ctx2.drawImage(img, 0,0,img.width,img.height,
0,0,img.width*scaleFactor1,img.height*scaleFactor1);
canvas3.width=canvas1.width*scaleFactor2;
canvas3.height=canvas1.height*scaleFactor2;
// draw a scaled-down image into the second canvas
ctx3.drawImage(img, 0,0,img.width,img.height,
0,0,img.width*scaleFactor2,img.height*scaleFactor2);
}
img.src = "http://placehold.it/400x200";