Animation
Konva.Animation
In Konva, use Konva.Animation constructor to make an animation. The constructor takes two arguments:
- an update function
- an optional layer, or array of layers
The update function will be called in each animation frame, and Konva.Animation will pass it a frame object which contains 3 properties:
- time property : the number of milliseconds that the animation has been running
- timeDiff property : the number of milliseconds that have passed since the last frame
- frameRate property : the current frame rate in frames per second
HTML5 Canvas Konva Animation Template:
The update function should contain logic to update shape properties, such as position, rotation, scale, width, height, radius, colors, etc.
Once the animation has been created, we can start it at anytime with the start() method.
Moving
In this example, we will make a red ball move forth and back horizontally.
HTML part
Add the Konva js code and prepare an element with a specific id for Konva drawing.
<script src="https://unpkg.com/konva@3.4.1/konva.min.js"></script>
<div id="container"></div>
2
JS part
Use Shape.move({x:dx, y:dy})
function to move the ball,
where (dx, dy) is the moving vector.
var stage = new Konva.Stage( { // Create a stage
container: 'container', width: 500, height: 100
});
var layer = new Konva.Layer(); // Create a layer
var circle = new Konva.Circle({ // Create the red ball
x:30, y:50, radius:10, fill:'red'
});
layer.add(circle); // Add the ball to the layer
stage.add(layer); // Add the layer to the stage
var speed = 0.2; // ball speed: pixels per ms
var anim = new Konva.Animation(function(frame)
{
// timeDiff * speed = move distance
circle.move({x: frame.timeDiff*speed, y:0});
// if move to boundary, then change the speed sign
if (circle.x()>470 || circle.x()<30) {
speed = -speed;
}
}, layer);
anim.start() // start the animation
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Result
If the red ball is disappeared, then click HTML/JavaScript tab, and go back to the Result tab.
Rotation
Use Shape.rotation(angle)
function to set the shape with rotaion = angle degrees. The rotation center is the Shape's (x, y). You can use the offset property to shift the Shape so that the
rotation center is shifted from the left top point.
← Basic Shapes Webduino →