用canvas实现方块的放大旋转效果

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
        body{background: #ccc;}
        #oc{background: #fff;}
    </style>
</head>
<body>
<!--canvas 设置宽高需要在 html的属性中-->
<canvas id="oc" width="400" height="400">浏览器不支持该标记!</canvas>
<script>
    //获取画板
    var oC = document.getElementById('oc');
    //设置画板的2d效果
    var oGC = oC.getContext('2d');
    //1.定义变量
    var num = 0;//旋转的参数
    var num2 = 0;//放大缩小的参数
    var value = 1;//表示是放大还是缩小  1 :放大   -1:缩小
    var timer = null;
    timer = setInterval(function(){
        num++;
        //保存初始画布
        oGC.save();
        //清除画布
        oGC.clearRect(0,0,oC.width,oC.height);
        //位置的移动
        oGC.translate(150,150);
        //放大缩小
        if(num2 == 100){
            value = -1;//缩小
        }else if(num2 ==0){
            value = 1;//放大
        }
        num2 +=value;
        oGC.scale(num2/50,num2/50);
        //旋转
        oGC.rotate(num*Math.PI/180);
        //位移
        oGC.translate(-50,-50);
        //画方块
        oGC.fillRect(0,0,100,100);
        //将初始画布还原
        oGC.restore();
    },10);
</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_39634880/article/details/80375284