简体   繁体   中英

Tweening a Kineticjs Shape

I have a custom shape created in Kineticjs and I need the shape to tween like a line. How would I go about doing this? I've tried creating a Kinetic Tween but that doesn't seem to work correctly.

var grnStripe = new Image();
grnStripe.onload = start;
grnStripe.src = 'images/GreenStripe-01.png';
function start(){
grnLine = new Kinetic.Shape({
    sceneFunc: function (context) {
        var ctx = this.getContext()._context;
        var pattern = context.createPattern(grnStripe, 'repeat');
        ctx.beginPath();
        ctx.moveTo(379.5, 270);
        ctx.lineTo(379.5, 270);
        ctx.strokeStyle = pattern;
        ctx.lineWidth = 2.5;
        ctx.stroke();
    }
});
line_layer.add(grnLine);
line_layer.draw();
}

I want the shape(line) to tween to a height of 310. Again, I've tried to create a Kinetic Tween but it's not seeming to work.

我需要的模拟

Yes, you can Kinetic.Tween a Kinetic.Shape--even a shape with a pattern stroke.

[ A general answer about tweening a Kinetic.Shape ]

The key to tweening a Kinetic.Shape is having sceneFunc change using a Kinetic.Shape property.

For example, this sceneFunc will draw a rectange based on that Kinetic.Shape's x & y properties.

sceneFunc: function(context) {
  var x=this.x();
  var y=this.y();
  context.fillRect(x,y,20,20);
},

Then you can use a Kinetic.Tween to change the Kinetic.Shapes' x/y which in turn will animate the rect.

For example this tween will animate a Kinetic.Shape called myShape from its current x/y to and x/y of [100,100].

tween = new Kinetic.Tween({
    node: myShape, 
    duration: 1,
    x: 100,
    y: 100,
  });

[ A specific answer based on one of your previous questions about pattern-stroked lines ]

The Kinetic.Shape context does not allow you to draw a pattern-stroked line.

As a workaround you can fetch the actual html context which does allow pattern-stroked lines.

A "ghosting problem" when tweening:

However, when you want to tween this pattern-filled line you have a "ghosting" problem because Kinetic actually uses 2 canvases for every layer and your pattern-filled line is incorrectly positioned on that second hit-canvas (a "ghost"). This is to be expected because Kinetic cannot be expected to know what you've drawn on your actual html context.

You can fix this ghosting problem by defining hitFunc in your custom Kinetic.Shape. That allows Kinetic to correctly position your pattern-filled line on its second hit-canvas. The ghosting is gone.

Here is a Fiddle demonstrating the workaround for your pattern-filled line:

http://jsfiddle.net/m1erickson/GpSbd/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM