在 Squares/Triangles 上调整形状描边位置

Adjust shape stroke position on Squares/Triangles

我需要在正方形(矩形 class)和三角形(直线 class)上设置描边位置,就像在此处为圆形所做的那样: GitHub issue with example

我想使用第一个解决方案sceneFunc。我很难弄清楚如何对正方形和三角形做同样的事情。

有什么想法吗?

提前致谢。

const square = new Konva.Shape({
  x: 50,
  y: 30,
  stroke: 'rgba(0,0,0,0.5)',
  strokeWidth: 20,
  fill: 'green',
  draggable: true,
  width: 100,
  height: 100,
  sceneFunc: (ctx, shape) => {
    ctx.rect(0, 0, shape.width(), shape.height());
    // first stroke
    ctx.strokeShape(shape);
    // then fill
    ctx.fillShape(shape);
  }
});
layer.add(square);

const triangle = new Konva.Shape({
  x: 250,
  y: 30,
  stroke: 'rgba(0,0,0,0.5)',
  strokeWidth: 20,
  fill: 'green',
  draggable: true,
  sceneFunc: (ctx, shape) => {
    ctx.beginPath();
    ctx.moveTo(0, 0);
    ctx.lineTo(50, 100);
    ctx.lineTo(-50, 100);
    ctx.closePath();
    // first stroke
    ctx.strokeShape(shape);
    // then fill
    ctx.fillShape(shape);
  }
});
layer.add(triangle);

演示:https://jsbin.com/fumacupoku/edit?html,js,output