我试图实现的是围绕自定义形状本身显示变压器。我直接从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();
})
Run Code Online (Sandbox Code Playgroud)
在此示例中,您可以看到,如果单击对象,则变压器将出现在角落。您仍然可以使用它来操纵对象,但是它并不围绕对象本身。
任何帮助表示赞赏!提前致谢。
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
};
}
Run Code Online (Sandbox Code Playgroud)
演示:http : //jsbin.com/lazuhowezi/2/edit?js,输出