Javascript HTML5画布绘制不同宽度的矩形边框?

Javascript HTML5画布绘制不同宽度的矩形边框?,javascript,html,html5-canvas,Javascript,Html,Html5 Canvas,方形边框的结果是不同的宽度,似乎右侧和底部边框的宽度是左侧和顶部边框宽度的2倍。为什么这么奇怪?我希望所有边的边界都具有相同的宽度 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>HTML5 Test</title> <script type="text/javascript"> function draw () {

方形边框的结果是不同的宽度,似乎右侧和底部边框的宽度是左侧和顶部边框宽度的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>

HTML5测试
函数图(){
var canvas=document.getElementById('rectangle');
var ctx=canvas.getContext('2d');
ctx.save();
ctx.lineWidth=30;
ctx.fillStyle=“黑色”;
ctx.fillRect(0,0100);
ctx.strokeStyle=“红色”;
ctx.strokeRect(0,0100);
ctx.restore();
}

这是因为您的边框在顶部和左侧被切断,因为画布从这里开始,如果矩形从(0,0)开始,则左侧边框的左端x坐标将为-30

使起始坐标大于30(这样边界的终点就不会为负),这样就可以正常工作