我已经将我的问题简化为一个带有<canvas>元素的基本HTML文档:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {
border: 1px solid #ff5500;
background-color: black;
}
canvas {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canv" style='width:1024px;height:768px'>
</canvas>
</body>
</html>但是,无论我如何设置width和height (使用像素、百分比或视图单元),无论是否设置样式(例如style='width:1024px;height:768px'),无论我调整浏览器窗口的大小,开发控制台总是报告宽度x高度为300x150。这是为什么,我该怎么处理?
下面是dev控制台的输出:
var c = document.getElementById("canv");
undefined
c.style.width
"1024px"
c.style.height
"768px"
c.width
300
c.height
150同样的行为在Chromium和Firefox中都会发生。
我在width和clientWidth之间发现了很多关于Stack溢出和web的问题,还有一个关于Fabric.js的类似问题,但是没有回答这个特定的问题。
发布于 2018-09-17 17:50:12
我认为您所指的宽度和高度--是html属性而不是css。
它们可以这样修改;
<canvas width="1024" height="768" style="border:1px solid black;">
</canvas>
发布于 2018-09-17 17:50:56
您必须在JS中更改canv.width或.height,或者在HTML中直接设置属性。不需要任何CSS或JS。
示例:
var can = document.querySelector("#testC");
var can2 = document.querySelector("#testC2");
console.log("Canvas before JS: ", can.width, "x", can.height);
console.log("Canvas in HMTL: ", can2.width, "x", can2.height);
can.width = 600;
can.height = 600;
console.log("Canvas after JS: ", can.width, "x", can.height);
console.log("Canvas in HMTL: ", can2.width, "x", can2.height);<canvas id="testC" width="300" height="300">
<canvas id="testC2" width="600" height="600">
这将记录:
Canvas before JS: 300x300
Canvas in HMTL: 600x600
Canvas after JS: 600x600
Canvas in HMTL: 600x600https://stackoverflow.com/questions/52373175
复制相似问题