Html 画布:宽度/高度属性和宽度/高度样式之间的差异



我已经在画布调整大小上看到了各种答案,但无法理解我面临的问题。以下是在我的 Web 应用程序上呈现的画布元素。

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>  

我设置画布的高度和宽度如下:

        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;
完成此操作后,样式中的宽度/高度

将取代属性宽度/高度,因此 canvas 使用样式的高度/宽度。

我的问题是:

  1. 为什么有两种不同的宽度/高度?
  2. 如何将它们设置为具有相同的值
  3. 如果我从 canvas 元素中删除resize属性,画布大小将保持为默认大小。
  1. html 属性中设置宽度/高度首先应用,直到加载 css。
  2. 加载 css 后,宽度/高度属性将被忽略并使用其样式定义。
  3. 使用 javascript 调整大小代码后,您将在该事件中调整画布大小。

最新更新