HTML5 Canvas绘制矩形-边框宽度不一致怎么办?

8

正方形边框的结果显示出不同的宽度,似乎右侧和底部边框的宽度是左侧和顶部边框宽度的两倍。为什么会这么奇怪?我想让所有边框的宽度都相同。

<!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>

enter image description here

1个回答

7

这是因为你的边框在顶部和左侧被裁剪了,因为画布从那里开始,如果你的矩形从(0,0)开始,左边框的左端点的x坐标将为-30。

将起始坐标设置为大于30(以使边框的末端不为负),它将正常工作。

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接