我有点新的画布,如果这是一个微不足道的问题,这么原谅。
我想要能够按照路径(定义为贝塞尔路径)动画化一个对象,但是我不知道该怎么做。
我看过拉斐尔,但是我无法计算出如何随着时间的推移走上路。
蛋糕JS在演示中看起来很有前途,但我真的在努力的文档,或在这种情况下缺乏。
有没有人有这个工作的例子?
解决方法
使用
this related question中的代码
on my website,而不是更改.style.left等等在回调中,擦除并重新绘制您的画布与项目在新的位置(和可选的旋转)。
请注意,这在内部使用SVG来轻松插入贝塞尔曲线上的点,但您可以使用它为您提供的任何点(包括绘画在画布上)。
如果我的网站关闭,这里是图书馆的当前快照:
function CurveAnimator(from,to,c1,c2){ this.path = document.createElementNS('http://www.w3.org/2000/svg','path'); if (!c1) c1 = from; if (!c2) c2 = to; this.path.setAttribute('d','M'+from.join(',')+'C'+c1.join(',')+' '+c2.join(',')+' '+to.join(',')); this.updatePath(); CurveAnimator.lastCreated = this; } CurveAnimator.prototype.animate = function(duration,callback,delay){ var curveAnim = this; // TODO: Use requestAnimationFrame if a delay isn't passed if (!delay) delay = 1/40; clearInterval(curveAnim.animTimer); var startTime = new Date; curveAnim.animTimer = setInterval(function(){ var now = new Date; var elapsed = (now-startTime)/1000; var percent = elapsed/duration; if (percent>=1){ percent = 1; clearInterval(curveAnim.animTimer); } var p1 = curveAnim.pointAt(percent-0.01),p2 = curveAnim.pointAt(percent+0.01); callback(curveAnim.pointAt(percent),Math.atan2(p2.y-p1.y,p2.x-p1.x)*180/Math.PI); },delay*1000); }; CurveAnimator.prototype.stop = function(){ clearInterval(this.animTimer); }; CurveAnimator.prototype.pointAt = function(percent){ return this.path.getPointAtLength(this.len*percent); }; CurveAnimator.prototype.updatePath = function(){ this.len = this.path.getTotalLength(); }; CurveAnimator.prototype.setStart = function(x,y){ var M = this.path.pathSegList.getItem(0); M.x = x; M.y = y; this.updatePath(); return this; }; CurveAnimator.prototype.setEnd = function(x,y){ var C = this.path.pathSegList.getItem(1); C.x = x; C.y = y; this.updatePath(); return this; }; CurveAnimator.prototype.setStartDirection = function(x,y){ var C = this.path.pathSegList.getItem(1); C.x1 = x; C.y1 = y; this.updatePath(); return this; }; CurveAnimator.prototype.setEndDirection = function(x,y){ var C = this.path.pathSegList.getItem(1); C.x2 = x; C.y2 = y; this.updatePath(); return this; };
…这里是你如何使用它:
var ctx = document.querySelector('canvas').getContext('2d'); ctx.fillStyle = 'red'; var curve = new CurveAnimator([50,300],[350,[445,39],[1,106]); curve.animate(5,function(point,angle) { ctx.clearRect(0,ctx.canvas.width,ctx.canvas.height); ctx.fillRect(point.x-10,point.y-10,20,20); });