跳到主要内容

HTML5 Canvas Konva 停止动画教程

如需使用 Konva 停止动画,可以使用 stop() 方法。 如需重新启动动画,可以再次调用 start()

操作说明: 单击“Start”启动动画,单击“Stop”停止动画。

如需查看完整的属性和方法列表,请参阅 Konva.Animation 文档

import Konva from 'konva';

const stage = new Konva.Stage({
container: 'container',
width: window.innerWidth,
height: window.innerHeight,
});

const layer = new Konva.Layer();
stage.add(layer);

const circle = new Konva.Circle({
x: stage.width() / 2,
y: stage.height() / 2,
radius: 30,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
layer.add(circle);

// add buttons
const container = document.createElement('div');
document.body.appendChild(container);
container.style.position = 'absolute';
container.style.top = '0px';
container.style.left = '0px';

const startBtn = document.createElement('button');
startBtn.textContent = 'Start Animation';
container.appendChild(startBtn);

const stopBtn = document.createElement('button');
stopBtn.textContent = 'Stop Animation';
container.appendChild(stopBtn);

const anim = new Konva.Animation(function(frame) {
circle.x(
amplitude * Math.sin((frame.time * 2 * Math.PI) / period) +
stage.width() / 2
);
}, layer);

const amplitude = 100;
const period = 2000;

startBtn.addEventListener('click', () => anim.start());
stopBtn.addEventListener('click', () => anim.stop());