使用javascript更新canvas lineJoin和lineCap属性

时间:2017-04-21 15:02:48

标签: javascript select canvas option

如何从列表中选择一个选项时更新lineJoin和lineCap?

https://jsfiddle.net/7cao1r1b/

<select name="line" id="line" onchange="handleUpdate()">
  <option value="round" checked>round</option>
  <option value="miter">miter</option>
</select>

在js:

function handleUpdate() {
  const option = document.querySelector('select').value;
  ctx.strokeStyle = this.value;
  ctx.lineWidth = this.value;
  ctx.lineJoin = option;
  ctx.lineCap = option;
  console.log(option);
}

1 个答案:

答案 0 :(得分:1)

选项ctx.lineJoin仅适用于具有连接的路径。

例如

   ctx.beginPath(); // begins a new path. there is no join from the previous path possible
   ctx.moveTo(100,100);
   ctx.lineTo(100,200;
   // adding a move to means that the lines above is not joined to the one below
   ctx.moveTo(100,200);
   ctx.lineTo(200,200);
   ctx.stroke();

要使用linejoin选项,您需要通过不在线段之间使用moveTo或beginPath来加入路径段,并使用关闭路径将线连接回上一个moveTo

   ctx.beginPath(); 
   ctx.moveTo(100,100);
   ctx.lineTo(100,200; 
   ctx.lineTo(200,200); // a join 
   ctx.stroke();

在您的代码段中,您正确使用了lineCap