2

strokeRect (0, 0, canvasWidth, canvasHeight);绘制一个完整的矩形,但线宽减半,这是一个示例:

<canvas></canvas>

<script>
    var canvas = document.getElementsByTagName ("canvas");

    var lineWidth = 10;

    var canvasHeight = canvas[0].height;
    var canvasWidth = canvas[0].width;

    var ctx = canvas[0].getContext ("2d");

    ctx.lineWidth = lineWidth;

    ctx.strokeRect (0, 0, canvasWidth, canvasHeight);
</script>

问题截图

我可以解决这个问题,但并不优雅:

<canvas></canvas>

<script>
    var canvas = document.getElementsByTagName ("canvas");

    var lineWidth = 10;

    var canvasHeight = canvas[0].height - lineWidth;
    var canvasWidth = canvas[0].width - lineWidth;

    var ctx = canvas[0].getContext ("2d");

    ctx.lineWidth = lineWidth;

    lineWidth /= 2;

    ctx.strokeRect (lineWidth, lineWidth, canvasWidth, canvasHeight);
</script>

不雅解的截图

有没有本地方法可以做到这一点?类似于“box-sizing”css3 属性的东西:

canvas {
    box-sizing: border-box;
}

谢谢。

4

1 回答 1

3

HTML5 Canvas 中的笔画(如 Adob​​e Illustrator 或 SVG 中的笔画)始终以它们正在笔画的路径为中心。很久以前我提出了一个新的 SVG 属性,听起来像你想要的,但这个功能既不在 SVG 也不在 Canvas 中。您的中风行为正常。

但是,您可以通过使用剪切区域来解决此问题,剪切到与您将要描边的路径相同并将标称线宽加倍:

function clippedRectStroke( ctx, x, y, w, h ){
  ctx.save();
  ctx.beginPath();
  ctx.moveTo(x,y);
  ctx.lineTo(x,y+h);
  ctx.lineTo(x+w,y+h);
  ctx.lineTo(x+w,y);
  ctx.clip();
  ctx.lineWidth *= 2;
  ctx.strokeRect(x,y,w,h);
  ctx.restore(); 
};

在这里工作演示:http: //jsfiddle.net/Dvz9Y/2/

于 2011-02-06T18:48:24.097 回答