我试图用画布绘制一段路径的动画。基本上,我有一条直线贯穿三个环节。当你在一个链接上悬停时,链接后面的路径部分应该变成正弦波。
我没有问题把整个路径动画成正弦波的形状,但是当我要动画一段路径时,我感到很困惑:
下面我附上了一张参考图片,给出了我想要达到的目标。

下面是我当前用于动画路径的代码的弹奏。我是个菜鸟所以如果这很糟糕的话请原谅我。
https://jsfiddle.net/9mu8xo0L/
这是密码:
class App {
constructor() {
this.drawLine();
}
drawLine() {
this.canvas = document.getElementById('sine-wave');
this.canvas.width = 1000;
this.ctx = this.canvas.getContext("2d");
this.cpY = 0;
this.movement = 1;
this.fps = 60;
this.ctx.moveTo(0, 180);
this.ctx.lineTo(1000, 180);
this.ctx.stroke();
this.canvas.addEventListener('mouseover', this.draw.bind(this));
}
draw() {
setTimeout(() => {
if (this.cpY >= 6) return;
requestAnimationFrame(this.draw.bind(this));
// animate the control point
this.cpY += this.movement;
const increase = (90 / 180) * (Math.PI / 2);
let counter = 0;
let x = 0;
let y = 180;
this.ctx.beginPath();
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
for(let i = 0; i <= this.canvas.width; i += 6) {
this.ctx.moveTo(x,y);
x = i;
y = 180 - Math.sin(counter) * this.cpY;
counter += increase;
this.ctx.lineTo(x, y);
this.ctx.stroke();
}
}, 1000 / this.fps);
}
}发布于 2016-05-02 10:39:59
只需将直线的绘制分为三个部分,将1/3绘制为直线,将中间部分动画化,并添加最后的1/3。
我将演示第一个1/3 +动画,并将最后的1/3作为练习(也将stroke()移出循环之外,以避免每个片段透支)-这里有重构和优化的空间,但在本例中我没有提到-
let x = this.canvas.width / 3; // start of part 2 (animation)
let y = 180;
this.ctx.beginPath();
this.ctx.clearRect(0, x, this.canvas.width, this.canvas.height);
// draw first 1/3
this.ctx.moveTo(0, y);
this.ctx.lineTo(x, y);
// continue with part 2
for(let i = x; i <= this.canvas.width; i += 6) {
x = i;
y = 180 - Math.sin(counter) * this.cpY;
counter += increase;
// add to 2. segment
this.ctx.lineTo(x, y);
}
// stroke line
this.ctx.stroke();https://stackoverflow.com/questions/36980144
复制相似问题