gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:35:15 25 4
gpt4 key购买 nike

我有一个设置为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com