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?
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.
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.
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%.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With