首页 > 代码库 > canvas缓动3
canvas缓动3
这次缓动的是旋转旋转,写完之后才知道原来rotate是绕原点旋转,而且还带着rect本身的X与Y一起,所以我采用了translate达到位移效果,以免旋转到画布外面去,画完之后效果惨不忍睹,原来是忘记还原变形了,最后加上了save和restore才让效果达到
var canvas = document.getElementById("canvas");
var cxt=canvas.getContext("2d");
var RectX=0,RectY=0,esaing=0.01;
var rotation=0,targetrotation=360;
function draw(){
cxt.beginPath();
cxt.clearRect(0,0,canvas.width,canvas.height);
cxt.fillStyle="red";
cxt.save()
cxt.translate(50,50);
rotation+=(targetrotation-rotation)*esaing;
console.log(rotation)
cxt.rotate(rotation*Math.PI/180)
cxt.rect(0,0,20,20);
cxt.fill();
cxt.restore()
cxt.closePath();
var id = requestAnimationFrame(draw);
if(targetrotation-rotation<=0.1)
{
cancelAnimationFrame(id);
}
}
draw();
canvas缓动3