Konvajs定制形状和变形金刚

时间:2018-05-28 17:48:21

标签: konvajs

我想要实现的是在自定义形状周围显示变压器。我直接从API文档中获取了代码,用于创建自定义形状和添加变换器。变换器适用于矩形,圆形等,但对于自定义形状,它看起来似乎不正确。

这是一个演示应用程序的链接,其中包含自定义形状和变换器的问题: https://jsfiddle.net/5zpua740/

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

var layer = new Konva.Layer();

/*
* create a triangle shape by defining a
* drawing function which draws a triangle
*/
var triangle = new Konva.Shape({
  sceneFunc: function (context) {
    context.beginPath();
    context.moveTo(120, 150);
    context.lineTo(320, 180);
    context.quadraticCurveTo(250, 200, 360, 270);
    context.closePath();

    // Konva specific method
    context.fillStrokeShape(this);
  },
  fill: '#00D2FF',
  stroke: 'black',
  strokeWidth: 4,
  draggable: true
});

// add the triangle shape to the layer
layer.add(triangle);

// add the layer to the stage
stage.add(layer);

stage.on('click', function (e) {
  // if click on empty area - remove all transformers
  if (e.target === stage) {
    stage.find('Transformer').destroy();
    layer.draw();
    return;
  }

  // remove old transformers
  // TODO: we can skip it if current rect is already selected
  stage.find('Transformer').destroy();

  // create new transformer
  var tr = new Konva.Transformer();
  layer.add(tr);
  tr.attachTo(e.target);
  layer.draw();
})

在此示例中,您可以看到,如果单击对象,变换器将出现在角落中。您仍然可以使用它来操纵对象,但它不在对象本身周围。

任何帮助表示赞赏!提前致谢。

1 个答案:

答案 0 :(得分:3)

Konva无法检测自定义形状的边界框。但我们可以简单地帮助它。我们只需要定义一个方法getSelfRect

该方法应返回形状的边界框而不应用变换(如形状没有旋转,没有缩放并放置在x = 0,y = 0)。

我们可以通过查看sceneFunc:

来做到这一点
triangle.getSelfRect = function() {
  return {
    // sceneFunc started from moving to 120, 150 point
    // so it is our top left point
    x: 120, 
    y: 150,
    // the bottom right point finished with quadraticCurveTo
    // I will use the coordinates to calculate size of the shape
    width: 360 - 120,
    height: 270 - 150
  };
}

演示:http://jsbin.com/lazuhowezi/2/edit?js,output