JavaScript: Canvas 高度与我设置的值不同

标签 javascript html

我有一个设置为 608 像素高的 Canvas 元素,但是浏览器中 canvas 元素的测量显示 Canvas 元素具有不同的 640 像素高度。

我不知道为什么 canvas 元素显示不同的 640px 高度,即使我将高度设置为 608。我该如何解决?

最佳答案

需要记住的是,canvas 元素有两个高度(和宽度)的概念。

作为 HTML 元素的 Canvas 具有“样式高度”,它描述了 HTML 文档中 canvas 元素的大小。

Canvas 也有它的 2D 可绘制表面,它有自己的“宽度和高度”来描述 Canvas 可绘制区域的分辨率。

这些高度(和宽度)彼此独立,这意味着 Canvas 元素大小和可绘制分辨率可以不同:

const canvas = document.querySelector('canvas');

/* 
Set canvas drawable height to something different of elements styled height 
*/
canvas.height = 608;

/* 
The canvas element is styled to 640px. This is possible because the 
resoultion height is independant of the styled height 
*/
console.log("canvas block height", window.getComputedStyle(canvas).height);

/* 
The resolution of the canvas height is the resoultion's height of the canvas
own drawable surface 
*/
console.log("canvas resolution height", canvas.height);
canvas {
  /* Specify element size in document to height of 640px */
  height:640px;
  outline:1px solid;
}
<canvas />

要确保 Canvas 的高度为 608px,请考虑通过 CSS 进行指定:

canvas {
  height:608px;
}

关于JavaScript: Canvas 高度与我设置的值不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56606603/

相关文章:

php - html表格输入整数类型?

javascript - 保留 SVG 文本的纵横比

android - 如何在 Android 上的 WebView 中嵌入 YouTube 剪辑

javascript - 即使在 jquery 或 javascript 中,如何选择并突出显示鼠标段落中的单词?

javascript - 滚动时的 Jquery 延迟

javascript - 无法使 mongoose 过期/ttl 工作

Javascript ondrag,ondragstart,ondragend

html - div 不拉伸(stretch)内容重叠内容

javascript - AngularJS + Restangular - 调用 .one() 和 .get() 结果是数组?

javascript - 动态更改 MongoDB ReplicaSet 中的 Node