Html Canvas : difference between width/height attribute and width/height style [duplicate]

女生的网名这么多〃 提交于 2020-01-25 01:25:05

问题


I have seen various answers on canvas resize but could not understand the problem I am facing. Following is the canvas element rendered on my web app.

Before Rendering: 

    <canvas id="g_5" resize></canvas>

After Rendering:

     <canvas id="g_5"  resize width="1076" height="306" style="-webkit-user-select: none; touch-action: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); width: 1148.38px; height: 300px;"></canvas>  

I am setting height and width of canvas as follows:

        var canvas = document.getElementById(canvasId);
        var context = canvas.getContext('2d');
        var width = <someWidth>;  //=1076 in this case
        var height = <someHeight>; //=306 in this case
        canvas.width = width;
        canvas.height = height;

After doing this, width/height in style supersedes the attribute width/height and hence canvas uses style's height/width.

My questions are:

  1. Why there are two different width/height?
  2. How to set them to have same value
  3. If I remove resize attribute from canvas element, canvas size stays to default size.

回答1:


  1. Setting width/height in html attributes is being applied first until the css is loaded.
  2. After css is loaded the width/height attributes is ignored and use its style definition.
  3. After using the javascript resize code then you'll get the canvas resized in that event.


来源:https://stackoverflow.com/questions/35219815/html-canvas-difference-between-width-height-attribute-and-width-height-style

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