如何在fabricjs中停止或暂停动画



我正在尝试使用FabricJs停止或暂停矩形的动画。然而,我试图在谷歌上搜索一个文档,没有太多关于如何实现它的信息。我将感谢的任何帮助

const canvas = new fabric.Canvas('c', {
selection: false
});
var hasAnimationStarted = false;
document.getElementById('button').onclick = startAnimation;
var rect = new fabric.Rect({
left: 10,
top: 10,
fill: "#FF0000",
stroke: "#000",
width: 50,
height: 50,
});
canvas.add(rect);
function startAnimation() {
if (hasAnimationStarted === false) {
hasAnimationStarted === true;
document.getElementById('button').innerText = 'Stop Animation';
rect.animate({
left: 250,
}, {
onChange: canvas.renderAll.bind(canvas),
duration: 6000,
onComplete: function() {
hasAnimationStarted === false;
document.getElementById('button').innerText = 'Start Animation';
},
abort: function() {
}
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.min.js"></script>
<canvas id="c" width="300" height="300" style="border: 2px solid green;"></canvas>
<button id="button">
Start Animation
</button>

从动画的abort方法返回一个truthy值,它将停止动画。

DEMO

const canvas = new fabric.Canvas('c', {
selection: false
});
let hasAnimationStarted = false;
document.getElementById('startAnim').onclick = startAnimation;
const rect = new fabric.Rect({
left: 10,
top: 10,
fill: "#FF0000",
stroke: "#000",
width: 50,
height: 50,
});
canvas.add(rect);
function startAnimation() {
if (hasAnimationStarted) {
stopAnimation();
} else {
hasAnimationStarted = true;
document.getElementById('startAnim').innerText = 'Stop Animation';
rect.animate({
left: 250,
}, {
onChange: canvas.requestRenderAll.bind(canvas),
duration: 6000,
onComplete: stopAnimation,
abort: () => !hasAnimationStarted
});
}
}
function stopAnimation() {
hasAnimationStarted = false;
document.getElementById('startAnim').innerText = 'Start Animation';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.0.0/fabric.min.js"></script>
<canvas id="c" width="300" height="300" style="border: 2px solid green;"></canvas>
<button id="startAnim">
Start Animation
</button>

最新更新