html - 防止笔画边框溢出路径

标签 html canvas border stroke

planetRect(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>

screenshot of problem

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

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

screenshot of inelegant solution

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

canvas {
    box-sizing: border-box;
}

谢谢。

最佳答案

HTML5 Canvas 中的笔画(如 Adob​​e Illustrator 或 SVG 中一样)始终以它们所笔画的路径为中心。很久以前我proposed一个new SVG property这听起来像你想要的,但这个功能既不在 SVG 中,也不在 Canvas 中。 您的中风表现符合预期。

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

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/

关于html - 防止笔画边框溢出路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4915031/

相关文章:

javascript - 球没有掉进盒子里

javascript - 预加载 SVG 图像

javascript - Canvas lineTo() 在错误的位置绘制 y 坐标

javascript - HTML5 用 Canvas 绘图,旋转线?

html - 您是否使用任何工具进行快速 html/css 开发?

javascript - 如何使用 HTML5 Canvas 函数式样式

iframe - 如何更改 iframe 的边框,使其与背景融为一体,而不是默认边框?

css - 如何在 flex 元素及其容器周围创建 "collapsed"边框?

html - 减少边框长度

html - 不同颜色的 CSS 选择器 nth-child()