简体   繁体   中英

HTML5: Resizing a canvas

All this time I worked on an app in a 800x480 resolution (popular phone resolution).

My canvas HTML:

<canvas id="main" width="800" height="480">

Now to make it fullscreen for other resolutions, I do the following after a resize event:

$('#main').css('height', window.innerHeight);
$('#main').css('width', window.innerWidth);

This works but the problem is I can't maintain the aspect ratio this way. 800x480 is 4:3, but if I run this app on a 5:3 phone, some things (especially circles) will look stretched.

Is there any way to make it look good on all resolutions without having to create a unique set of images and code for every aspect ratio?

CSS properties width and height stretch the canvas, in order to scale the board, you must use .attr instead of .css , this will work, but, something to note:

If you want the canvas to look perfect on mobile phones, too, you must pay attention to window.devicePixelRatio .

What's devicePixelRatio

MDN:

The devicePixelRatio property returns the ratio between physical pixels and device independent pixels in the current display.

What does it mean? it means how many pixels does a device show, in one physical pixel.

If a device's pixel ratio is 2, it means two graphical pixels are drawn in a single physical pixel.

In order to make your canvas look perfect, you must do this trick:

set width and height of canvas to the amount you want multiplied by devicePixelRatio, ie

$('canvas').attr({
  'width': window.innerWidth*devicePixelRatio,
  'height': window.innerHeight*devicePixelRatio
});

Then, scale your canvas down with CSS:

$('canvas').css({
  'width': window.innerWidth + 'px',
  'height': window.innerHeight + 'px'
});

It seems innerWidth and innerHeight are not right at first, I tried wrapping the code in a 100 milisecond setTimeout and it worked, I guess you can reduce the delay to something like 10 miliseconds, test it.

Fiddle: http://jsfiddle.net/mdibaiee/7o4tLr4L/

To test on your mobile: http://fiddle.jshell.net/mdibaiee/7o4tLr4L/show/

You can use @media for different resolutions like tablets and phones for example

@media only screen and (max-device-width : 640px) {
/* Styles */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM