拖动和缩放文本与Kineticjs(Drag and zoom text with Kineticj

2019-11-02 06:05发布

我想缩放和平移文字是可拖动了。 所有的例子都在图片或形状,似乎我不能适应文本对象。 我的问题是:

  1. 我必须用锚或任何简单的方式放大与Kineticjs文本?

  2. 我发现关于缩放形状的例子和代码崩溃在这里:

      var layer = new Kinetic.Layer({ drawFunc : drawTriangle //drawTriangle is a function defined already }); 

我们可以调用一个函数,而我们正在创造一个层? 我通常会创建一个图层,然后添加功能的结局吧。 任何想法将是巨大的,谢谢。

Answer 1:

I thought of many ways you could do this but this is the one I ended up implementing: jsfiddle

Basically, you have an anchor (which doesn't always have to be there, you can hide and show it if you would like. Let me know if you need help with that) and if you drag the anchor down it increases the fontSize, and if you drag the anchor up it decreases the fontSize.

I followed the exact same anchor tutorial but instead I added a dragBoundFunc to limit dragging to the Y-axis:

var anchor = new Kinetic.Circle({
    x: x,
    y: y,
    stroke: '#666',
    fill: '#ddd',
    strokeWidth: 2,
    radius: 8,
    name: name,
    draggable: true,
    dragOnTop: false,
    dragBoundFunc: function (pos) {
        return {
            x: this.getAbsolutePosition().x,
            y: pos.y
        };
    }
});

And then I updated the updateAnchor() function to only detect the single anchor I added to the group named sizeAnchor:

var mY = 0;

function update(activeAnchor, event) {
  var group = activeAnchor.getParent();
  var sizeAnchor = group.get('.sizeAnchor')[0];
  var text = group.get('.text')[0];

  if (event.pageY < mY) {
    text.setFontSize(text.getFontSize()-1);
  } else {
    text.setFontSize(text.getFontSize()+1);
  }

  sizeAnchor.setPosition(-10, 0);

  mY = event.pageY;
}

Basically mY is used compared to the e.PageY to see if the mouse is moving up or down. Once we can determine the mouse direction, then we can decide if we should increase or decrease the fontSize!

Alternatively, you can use the mousewheel to do the exact same thing! I didn't implement it myself but it's definitely doable. Something like:

  1. Mousewheel down and the fontSize decreases
  2. Mousewheel up and the fontSize increases

Hopefully this emulates "Zooming" a text for you. And I guess being able to drag the text acts as "panning" right?

UPDATE (based on comment below)

This is how you would limit dragging to the Y-Axis using dragBoundFunc:

var textGroup = new Kinetic.Group({
    x: 100,
    y: 100,
    draggable: true,
    dragBoundFunc: function (pos) {
        return {
            x: this.getAbsolutePosition().x,
            y: pos.y
        };
    }
});

See the updated jsfiddle (same jsfiddle as above)



文章来源: Drag and zoom text with Kineticjs