、それぞれの行をlineWidth
を設定し、stroke()
。ここで
は、調整(以下フィドル)です:
var context = canvas.getContext("2d");
context.strokeStyle = '#000000';
context.beginPath();
context.moveTo(10, 10);
context.lineTo(50, 10);
context.lineWidth = 2;
context.stroke();
//context.save(); no need to do this
context.beginPath();
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.stroke();
context.beginPath();
context.moveTo(10, 50);
context.lineTo(50, 50);
context.lineWidth = 2;
context.stroke();
あなたはあなただけかけてすべてを遅くやり直すすべての行を再描画しますbeginPath()
使用しない場合。同じ太さのすべての線が最初にbeginPath()
を使用した場合。
同じ厚さを持つラインは、例えば1パスなどの下にグループ化されるように、あなたはまた、コードを並べ替えることができます。
context.beginPath(); //begin here
context.lineWidth = 2; //common width for the next two lines
context.moveTo(10, 10);
context.lineTo(50, 10);
context.moveTo(10, 50);
context.lineTo(50, 50);
context.stroke(); //stroke here to draw them
context.beginPath(); //start new path for new thickness
context.lineWidth = 15;
context.moveTo(10, 30);
context.lineTo(50, 30);
context.stroke();
あなたが唯一のパラメータを調整する場合save()
/restore()
コンテキストへの必要はありません(ここでは毎回lineWidth
を設定していますが、この場合はより効率的です)。
必要に応じて同じように機能します
function drawLine(ctx, x1, y1, x2, y2, width, color) {
if (typeof width === 'number') ctx.lineWidth = width;
if (typeof color === 'string') ctx.strokeStyle = color;
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
使用法:
drawLine(context, 0, 0, 100, 100); //width and color is optional
drawLine(context, 0, 0, 100, 100, 10);
drawLine(context, 0, 0, 100, 100, 10, '#f00');
修正しフィドル:
http://jsfiddle.net/AbdiasSoftware/8NzjH/4/
再編成されたバージョン:
http://jsfiddle.net/AbdiasSoftware/8NzjH/5/
"私は太い中間線を次のように描こうとしています:" – Wex
真ん中にあるものだけを太くすることを望んでいませんでした。私はあなたのコードを更新しようとしましたが、最初の2つは厚いhttp://jsfiddle.net/8NzjH/3/ – Hoa