javascript - HTML5: Resizing a canvas -
all time worked on app in 800x480 resolution (popular phone resolution).
my canvas html:
<canvas id="main" width="800" height="480">
now make fullscreen other resolutions, following after resize event:
$('#main').css('height', window.innerheight); $('#main').css('width', window.innerwidth);
this works problem can't maintain aspect ratio way. 800x480 4:3, if run app on 5:3 phone, things (especially circles) stretched.
is there way make on resolutions without having create unique set of images , code every aspect ratio?
css properties width
, height
stretch canvas, in order scale board, must use .attr
instead of .css
, work, but, note:
if want canvas perfect on mobile phones, too, must pay attention window.devicepixelratio
.
what's devicepixelratio
mdn:
the devicepixelratio property returns ratio between physical pixels , device independent pixels in current display.
what mean? means how many pixels device show, in 1 physical pixel.
if device's pixel ratio 2, means 2 graphical pixels drawn in single physical pixel.
in order make canvas perfect, must trick:
set width , height of canvas amount want multiplied devicepixelratio, i.e
$('canvas').attr({ 'width': window.innerwidth*devicepixelratio, 'height': window.innerheight*devicepixelratio });
then, scale canvas down css:
$('canvas').css({ 'width': window.innerwidth + 'px', 'height': window.innerheight + 'px' });
it seems innerwidth
, innerheight
not right @ first, tried wrapping code in 100 milisecond settimeout , worked, guess can reduce delay 10 miliseconds, test it.
fiddle: http://jsfiddle.net/mdibaiee/7o4tlr4l/
to test on mobile: http://fiddle.jshell.net/mdibaiee/7o4tlr4l/show/
Comments
Post a Comment