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>

エレガントでないソリューションのスクリーンショット

それを行うためのネイティブな方法はありますか?「ボックスサイジング」css3属性のようなもの:

canvas {
    box-sizing: border-box;
}

ありがとう。

4

1 に答える 1

3

HTML5 Canvasのストロークは、Adobe IllustratorやSVGの場合と同様に、ストロークしているパスの中央に常に配置されます。ずっと前に、私はあなたが望むように聞こえる新しいSVGプロパティを提案しましたが、この機能はSVGにもCanvasにもありません。ストロークは想定どおりに動作しています。

ただし、これを回避するには、クリッピング領域を使用し、ストロークしようとしているパスと同じようにクリッピングして、公称線幅を2倍にします。

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 に答える