本文简介
- 主管:XX过来一下,给这张图片做出轨迹效果来。
- 我:好的,主管,马上完成。
效果
技术
使用fabric的animate
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/510/fabric.min.js"></script>
</head>
<body>
<canvas id="c" width="300" height="300" style="border: 2px solid green;"></canvas>
<button id="startAnim">
Start Animation
</button>
<script>
const canvas = new fabric.Canvas('c', {
selection: false
});
let hasAnimationStarted = false;
document.getElementById('startAnim').onclick = startAnimation;
const line = new fabric.Line(
[
50, 50, // 起始点坐标
50, 50 // 结束点坐标
], {
stroke: 'red', // 笔触颜色
}
)
canvas.add(line)
function startAnimation() {
if (hasAnimationStarted) {
stopAnimation();
} else {
hasAnimationStarted = true;
document.getElementById('startAnim').innerText = 'Stop Animation';
line.animate({
x2: 50,
y2: 250
}, {
onChange: canvas.requestRenderAll.bind(canvas),
duration: 2000,
onComplete: stopAnimation,
abort: () => {
return !hasAnimationStarted
}
});
}
}
function stopAnimation() {
hasAnimationStarted = false;
document.getElementById('startAnim').innerText = 'Start Animation';
}
</script>
</body>
</html>
总结
- 设置线路的x2和y2是类似于增加;设置left或者top类似于直接跳到...
- 动画的停止关键是abort