Canvas sizing incorrectly on loading

假如想象 提交于 2020-01-06 19:58:53

问题


I have a canvas webpage that functionally works but occasionally sizes incorrectly on start up. Says I have declared a canvas html tag like this:

<canvas id="main_canvas"></canvas>

And I have included a javascript file that takes care of the sizing using jquery

$(function() {
    var canvas = $('canvas')[0];

    var DISPLAY_WIDTH = window.innerWidth-10,
        DISPLAY_HEIGHT = 620,

Occasionally after the page loads the canvas size is squeezed into a very small area and all objects rendered is stacked upon each other, if I refresh however this problem no longer persists. I use the inspect element tool and found that while the sizing problem happens I have the html code

<canvas id="main_canvas" width="-10" height="620"></canvas>

Seems for some unknown reason the window.innerwidth is not acquired and the width is simply set to -10 and causes the problem. But the jquery declaration $(function(){}) should only execute after the page loads and I don't think I can use window.innerWidth just in the html tag. And I don't want to set the width to some other numerical value since this problem might as well happen again and I simply get that numerical width as my canvas width.

Anyway can tell me some fix? Thanks


回答1:


What if you put it all in the

$(document).ready(function()

function? Quote:

Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded. (Source: http://www.learningjquery.com/2006/09/introducing-document-ready)



来源:https://stackoverflow.com/questions/11643826/canvas-sizing-incorrectly-on-loading

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