HTML5 Canvas Konva Rotation Animation tutorial

获取Konva最新的信息

To animate a shape’s rotation with Konva, we can create a new animation with
Konva.Animation, and define a function which modifies the shape’s rotation with each animation frame.

In this tutorial, we’ll rotate a blue rectangle about the top left corner,
a yellow rectangle about its center, and a red rectangle about an outside point.

For a full list of attributes and methods, check out the Konva.Animation documentation.

Konva Rotation Animation Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Rotation Animation Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}
</style>
</head>
<body>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});

var layer = new Konva.Layer();

/*
* leave center point positioned
* at the default which is the top left
* corner of the rectangle
*/

var blueRect = new Konva.Rect({
x: 50,
y: 75,
width: 100,
height: 50,
fill: '#00D2FF',
stroke: 'black',
strokeWidth: 4
});

/*
* move center point to the center
* of the rectangle with offset
*/
var yellowRect = new Konva.Rect({
x: 220,
y: 75,
width: 100,
height: 50,
fill: 'yellow',
stroke: 'black',
strokeWidth: 4,
offset: {
x: 50,
y: 25
}
});

/*
* move center point outside of the rectangle
* with offset
*/

var redRect = new Konva.Rect({
x: 400,
y: 75,
width: 100,
height: 50,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
offset: {
x: -100,
y: 0
}
});

layer.add(blueRect);
layer.add(yellowRect);
layer.add(redRect);
stage.add(layer);

// one revolution per 4 seconds
var angularSpeed = 90;
var anim = new Konva.Animation(function(frame) {
var angleDiff = (frame.timeDiff * angularSpeed) / 1000;
blueRect.rotate(angleDiff);
yellowRect.rotate(angleDiff);
redRect.rotate(angleDiff);
}, layer);

anim.start();
</script>
</body>
</html>