gpt4 book ai didi

javascript - 谁能告诉我为什么这不是创建一个正方形?

转载 作者:行者123 更新时间:2023-12-04 23:35:19 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Canvas is stretched when using CSS but normal with "width" / "height" properties

(9 个回答)


2年前关闭。




我正在按照一个教程来学习 Canvas ,而且我很早就被困住了。

这是代码:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

context.lineWidth = 3;
context.strokeStyle = "blue";
context.lineJoin = "square";
context.strokeRect(10,10,200,200);
#canvas{
border: 1px solid black;
display: block;
width: 900px;
height: 600px;
margin: 0 auto;
}
<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
<title>HTML Canvas</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css">
</head>

<body>

<canvas id="canvas"></canvas>

<script src="script.js" type="text/javascript"></script>

</body>
</html>


看起来它应该很简单,但它并没有达到我的预期。任何人都可以建议吗?

最佳答案

heightwidth最初应该在 HTML 或通过 DOM 属性而不是 CSS 中设置 Canvas 的大小,以避免调整大小。

来自 MDN :

Indeed, the element has only two attributes, width and height. These are both optional and can also be set using DOM properties. When no width and height attributes are specified, the canvas will initially be 300 pixels wide and 150 pixels high. The element can be sized arbitrarily by CSS, but during rendering the image is scaled to fit its layout size: if the CSS sizing doesn't respect the ratio of the initial canvas, it will appear distorted.



因此,您的正方形也被调整为与 Canvas 相同的大小,并且不再完全适合其中。

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

context.lineWidth = 3;
context.strokeStyle = "blue";
context.lineJoin = "square";
context.strokeRect(10,10,200,200);
#canvas{
border: 1px solid black;
display: block;
margin: 0 auto;
}
<canvas id="canvas" height="600" width="900"></canvas>

关于javascript - 谁能告诉我为什么这不是创建一个正方形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59582490/

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