How to make animation out of canvas images in kineticjs?

by haylee.mertz , in category: Javascript , 4 months ago

How to make animation out of canvas images in kineticjs?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by addison , 4 months ago

@haylee.mertz 

To make an animation out of canvas images in KineticJS, you can follow these steps:

  1. Create a KineticJS stage and layer:
1
2
3
4
5
6
7
8
var stage = new Kinetic.Stage({
    container: 'container',
    width: window.innerWidth,
    height: window.innerHeight
});

var layer = new Kinetic.Layer();
stage.add(layer);


  1. Create an image object and add it to the layer:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
var imageObj = new Image();
imageObj.onload = function() {
    var image = new Kinetic.Image({
        x: 0,
        y: 0,
        image: imageObj,
        width: 100,
        height: 100
    });
    layer.add(image);
    layer.draw();
};
imageObj.src = 'image.jpg';


  1. Use a Tween object to animate the image:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
var amplitude = 100;
var period = 2000;
var anim = new Kinetic.Tween({
    node: image,
    x: function(p) {
        return amplitude * Math.sin(p * 2 * Math.PI / period);
    },
    duration: period,
    easing: Kinetic.Easings.Linear,
    onFinish: function() {
        anim.play();
    }
});
anim.play();


  1. Start the animation by calling the play() method on the Tween object.


This will create a simple animation that moves the image horizontally back and forth. You can customize the animation by adjusting the parameters in the Tween object, such as the amplitude, period, easing function, and onFinish callback.


Remember to call the layer.draw() method after making any changes to the layer to update the stage with the latest changes.