Scaling canvas element with static resolution

那年仲夏 提交于 2019-12-05 00:29:43

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; 
}​
Simon Sarris

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!