我正在使用下面的代码来绘制一条线,并且它工作得很好:
var centerX = $("#myCanvas").width()/ 2;
var centerY = $("#myCanvas").height()/ 2;
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle = 'white';
ctx.fill();
ctx.beginPath();
ctx.moveTo(0,centerY );
ctx.lineTo( centerX*2,centerY);
ctx.stroke();
现在我想在画线的时候给它动画,但是我不知道怎么做,我试着用动画来做,但是我不能.Can任何人的帮助?
这也是小提琴的链接:
小提琴
发布于 2014-07-23 15:12:31
您可以使用线性插值(lerping)从开始到结束计算直线上的点。
var cx=canvas.width/2;
var cy=canvas.height/2;
var pct=0.50;
// calc the value that is x% between a & b
var lerp=function(a,b,x){ return(a+x*(b-a)); };
// use lerping to calc the value of x at the midpoint (50%) of the line
var x=lerp(0,cx*2,pct);
然后,可以用循环从开始到结束递增地画一条线.。
function animate(){
if(pct<100){requestAnimationFrame(animate);}
var x=lerp(0,cx*2,pct/100);
drawLine(0,cy,x,cy);
pct++;
}
下面是示例代码和演示:http://jsfiddle.net/m1erickson/6P6jx/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cx=canvas.width/2;
var cy=canvas.height/2;
var lerp=function(a,b,x){ return(a+x*(b-a)); };
var pct=0;
animate();
function animate(){
if(pct<100){requestAnimationFrame(animate);}
var x=lerp(0,cx*2,pct/100);
drawLine(0,cy,x,cy);
pct++;
}
function drawLine(x0,y0,x1,y1){
ctx.beginPath();
ctx.moveTo(x0,y0);
ctx.lineTo(x1,y1);
ctx.stroke();
}
}); // end $(function(){});
</script>
</head>
<body>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
https://stackoverflow.com/questions/24913875
复制相似问题