css - 使用 CSS 时 Canvas 被拉伸(stretch),但使用 "width"/"height"属性正常

标签 css html canvas height width

我有 2 个 Canvas ,一个使用 HTML 属性 widthheight 来调整大小,另一个使用 CSS:

<canvas id="compteur1" width="300" height="300" onmousedown="compteurClick(this.id);"></canvas>
<canvas id="compteur2" style="width: 300px; height: 300px;" onmousedown="compteurClick(this.id);"></canvas>

Compteur1 显示应该是这样,但不是 compteur2。内容是使用 JavaScript 在 300x300 Canvas 上绘制的。

为什么会有显示差异?

alt text

最佳答案

似乎 widthheight 属性决定了 Canvas 坐标系的宽度或高度,而 CSS 属性只决定了它所在的框的大小将显示出来。

这在 HTML specification 中有解释。 :

The canvas element has two attributes to control the size of the element’s bitmap: width and height. These attributes, when specified, must have values that are valid non-negative integers. The rules for parsing non-negative integers must be used to obtain their numeric values. If an attribute is missing, or if parsing its value returns an error, then the default value must be used instead. The width attribute defaults to 300, and the height attribute defaults to 150.

关于css - 使用 CSS 时 Canvas 被拉伸(stretch),但使用 "width"/"height"属性正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2588181/

相关文章:

css - 表单中的下拉按钮

带有填充的 HTML 列表,试图找出包装

html - 水平居中带有左浮动、左对齐元素的列表

javascript - 在我的具体情况下,如何将 3 个盒子并排放置?

jquery - 在另一个元素悬停动画后更改背景图像

javascript - Three.js,appendChild 和返回

html - 将 Bootstrap 的自定义文件输入光标设置为指针

php - 无法在 php echo 中对齐 css - jquery 不工作

javascript - 使用 Canvas 的 id 调整大小?

javascript - 在 HTML Canvas 上获取填充和描边的单个阴影