Skip to main content

HTML5 Canvas Konva 停止动画教程

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

说明: 单击“开始”以启动动画,单击“停止”以停止动画。

有关属性和方法的完整列表,请查看 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);  

// 添加按钮  
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 = '开始动画';  
container.appendChild(startBtn);  

const stopBtn = document.createElement('button');  
stopBtn.textContent = '停止动画';  
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());