Scaling canvas element with static resolution

ciembor picture ciembor · Mar 16, 2012 · Viewed 19.7k times · Source

I have canvas element and I want to scale it down, but without changing it's js logic. Drawing space in js should always be 600x300px, even if it is displayed in HTML as 300x150px. I know, I can resize image with static resolution, but can I do the same with canvas?

Answer

Loktar picture Loktar · Mar 16, 2012

Changing the size using CSS scales it

Live Demo

So basically you set its size for drawing objects, etc, via the width and height properties like so

var canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = 600;
canvas.height = 300;

and then change its displayed size using css

#canvas{
   width: 300px;
   height: 150px; 
}​