【问题标题】:KonvaJS how to change the line style?KonvaJS 如何改变线条样式?
【发布时间】:2021-08-17 09:51:24
【问题描述】:

我正在尝试用鼠标创建绘图板。

使用 KonvaJS,我可以画一条线或一个箭头。 如何更改线条的样式和箭头的末端?

我使用 Konva。 Arrow 和 Konva.Line 正是我所需要的。

例子:

【问题讨论】:

标签: konvajs


【解决方案1】:

有很多方法可以实现这样的形状。

(1) 您可以使用Konva.Path 并手动生成带有SVG 路径的data 属性(通过鼠标移动)。

(2) 您可以使用Konva.TextShape 将箭头绘制为一组符号(如点或破折号)。

(3) 您可以使用Custom Shape 使用原生 2d 画布 API 进行绘制。

这是一个包含所有这些的演示:

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight
});

const layer = new Konva.Layer();
stage.add(layer);

const getAngle = (points) => {
  const dx = points[1].x - points[0].x;
  const dy = points[1].y - points[0].y;
  const angle = Math.atan2(dy, dx);
  return Konva.Util.radToDeg(angle);
}

const createPathArrow = () => {
  return new Konva.Path({
    x: 50,
    y: 50,
    stroke: 'red',
    fill: 'red',
    data: 'M 0 0 L 100 0 L 80 -10 L 90 0 L 80 10 L 100 0'
  })
};



const createTextPathArrow = (points) => {
  const [p1, p2] = points;
  const group = new Konva.Group({
    x: 50,
    y: 150
  });
  group.add(new Konva.TextPath({
    stroke: 'red',
    text: '| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | ',
    data: `M ${p1.x} ${p1.y} L ${p2.x} ${p2.y}`
  }));
  group.add(new Konva.Text({
    x: p2.x,
    y: p2.y,
    text: '➤',
    fill: 'red',
    fontSize: 25,
    offsetY: 25 / 2,
    offsetX: 25 / 2,
    rotation: getAngle(points)
  }))
  return group;
};

const createSceneArrow = () => {
  return new Konva.Shape({
    x: 50,
    y: 250,
    stroke: 'red',
    length: 100,
    arcSize: 10,
    sceneFunc: (ctx, shape) => {
      const arcSize = shape.getAttr('arcSize');
      const number = shape.getAttr('length') / arcSize;
      ctx.beginPath();
      for(var i = 0; i < number; i++) {
          ctx.moveTo(i * arcSize, 0);
          const midX = (i * arcSize + arcSize / 2);
          const midY = 0;
          if (i % 2 === 0) {
            ctx.arc(midX, midY, arcSize / 2, Math.PI, 0, 1);            
          } else {
            ctx.arc(midX, midY, arcSize / 2, Math.PI, 0);            
          }
      }
      ctx.fillStrokeShape(shape);
    }
  })
}

const points = [{x: 0, y: 0}, {x: 100, y: 30}];

layer.add(createPathArrow());
layer.add(createTextPathArrow(points));
layer.add(createSceneArrow())
<script src="https://unpkg.com/konva@^8/konva.min.js"></script>
<div id="container"></div>

【讨论】:

  • 我使用 Konva.TextPath 作为线条,使用 Konva.Image 作为箭头。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-27
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
相关资源
最近更新 更多