javascript - HTML Canvas : difference between width/height attribute and width/height style

标签 javascript css html canvas

<分区>

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

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>  

我按如下方式设置 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 属性, Canvas 大小将保持默认大小。

最佳答案

  1. 首先应用 html 属性中的宽度/高度设置,直到加载 css。
  2. 加载 css 后,宽度/高度属性将被忽略并使用其样式定义。
  3. 使用 javascript 调整大小代码后,您将在该事件中调整 Canvas 大小。

关于javascript - HTML Canvas : difference between width/height attribute and width/height style,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35219815/

相关文章:

javascript - 如果 anchor 内部有 iframe,则无法单击 anchor

html - Img 上的文字 - 不使用高度/宽度

html - CSS 表格布局中的 iframe

css - 设置 iframe 样式

javascript - addEventListener ("load")在 Chrome 中无法正常工作?

javascript - 如何将 if/else 语句放入对象键中?

javascript - 将 JSON 数据集的其余值更新为特定值?

java - JSP 不向 JQuery AJAX 返回数据

html - 固定位置重叠绝对位置?

javascript - 重叠选项卡/下拉 div - 链接不起作用 - CSS 或 JS 问题?