Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scaling canvas element with static resolution

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?

like image 273
ciembor Avatar asked Mar 16 '12 17:03

ciembor


People also ask

Why does my canvas look blurry?

However, the Canvas still looks pixelated. This is because the Canvas is rendering to a bitmap of one size then scaling the bitmap to fit the CSS dimensions. To fix this, we modify the Canvas's bitmap dimensions to match the CSS dimensions using JavaScript.

How do you scale on canvas?

The scale() method scales the current drawing, bigger or smaller. Note: If you scale a drawing, all future drawings will also be scaled. The positioning will also be scaled. If you scale(2,2); drawings will be positioned twice as far from the left and top of the canvas as you specify.

How do I make my canvas fit the screen in HTML?

to set the canvas's width and height both to 100%. We also set the position to absolute and top , left , right , and bottom to 0 to make the canvas fill the screen. Also, we make the html and body elements fill the screen by setting the width and height to 100%.


2 Answers

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; 
}​
like image 186
Loktar Avatar answered Sep 22 '22 20:09

Loktar


Loktar has one way, using CSS, but that might cause some things to look funny. For instance paths scaled using CSS and scaled using the canvas' own transform may look very different (with the CSS ones looking bad and the canvas ones looking smooth). This depends on the browser though and might be perfectly fine. On chrome at least, text scaled this way looks very bad.

Instead I'd recommend looking at what I wrote here about the concept of "model" coordinates: Working with canvas in different screen sizes

Write everything as if the drawing space is 600x300, but keep a canvas that is 300x150.

Before drawing anything use ctx.scale(0.5, 0.5); and everything will look great!

It's quite possible after all to write one canvas app and the have it scale to all sorts of screens, even if you're just targeting one screen size.

like image 39
Simon Sarris Avatar answered Sep 20 '22 20:09

Simon Sarris