HTML5 Canvas Draw Rect - 得到了Diff宽度的边框?

yee*_*een 8 javascript html5 html5-canvas

方形边框的结果看起来是不同的宽度,似乎右边框和下边框的宽度比左边框和上边框的宽度宽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>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Som*_*Guy 7

这是因为你的边框在顶部和左边被切断,因为那是画布开始的地方,如果你的矩形从(0,0)开始,左边框的左边x坐标将是-30.

使起始坐标超过30(使得边界的末端不是负数),并且它将正常工作.

演示