学习了canvas的变换之后,就可以做出一个动画效果。通过定时器不断地改变画布坐标的旋转角度,并且对画布的元素进行缩放
效果如下:
代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin:0 ;
padding: 0;
}
html,body{
height: 100%;
overflow: hidden;
}
body{
background: pink;
}
#test{
background: white;
position: absolute;
left:0 ;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<canvas id="test" width="300px" height="300px ">
<span >
您的浏览器不支持画布元素
</span>
</canvas>
<script type="text/javascript">
window.onload = function (){
var flag = 0;
var testNode = document.querySelector("#test")
var scale = 0;
var flagscale = 0;
//判断是否有画笔
if(testNode.getContext){
var ctx = testNode.getContext("2d") ;
ctx.save()
ctx.translate(150,150)
ctx.beginPath()
ctx.fillRect(-50,-50,100,100)
ctx.restore()
setInterval(function(){
flag++
ctx.clearRect(0,0,testNode.width,testNode.height)
ctx.save()
ctx.translate(150,150)
ctx.rotate(flag*Math.PI/180)
if(scale==100){
flagscale =-1
}else if(scale==0){
flagscale=1
}
scale +=flagscale
ctx.scale(scale/50 , scale/50)
ctx.beginPath()
ctx.fillRect(-50,-50,100,100)
ctx.restore()
},1000/60)
}
}
</script>
</body>
</html>