javascript HTML5 Canvas Draw Rect - 有不同宽度的边框?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8027601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 Canvas Draw Rect - Got Border of Diff Width?
提问by yeeen
The result of the square border turns out to be different width, it seems that the right and the bottom border's width is 2x wider than the left and the top border's width. Why so weird? I want the border of all sides to have the same width.
结果方形边框的宽度不同,似乎右侧和底部边框的宽度比左侧和顶部边框的宽度宽 2 倍。怎么这么奇怪?我希望所有边的边框具有相同的宽度。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>HTML5 Test</title>
<script type="text/javascript">
function draw () {
var canvas = document.getElementById('rectangle');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.lineWidth = 30;
ctx.fillStyle = "black";
ctx.fillRect(0,0,100,100);
ctx.strokeStyle = "red";
ctx.strokeRect(0,0,100,100);
ctx.restore();
}
</script>
</head>
<body onload="draw()">
<canvas id="rectangle"></canvas>
</body>
</html>
采纳答案by Some Guy
That's because your border is being cut off at the top and the left, because that's where the canvas starts, and if your rectangle starts at (0,0), the left border's left end's x co-ordinate will be -30.
那是因为您的边框在顶部和左侧被切断,因为那是画布的起点,如果您的矩形从 (0,0) 开始,则左边框的左端 x 坐标将为 -30。
Make the starting co-ordinates anything above 30 (so that the end of your borders aren't negative), and it'll work fine.
将起始坐标设为 30 以上的任何值(这样边框的末端就不是负数),它会正常工作。