HTML5 canvas 绘图旋转

具体分为二两种:中心旋转和参照点旋转

一、中心旋转

function onload () {
        var canvas1 = document.getElementById("c1");
        var ctx1 = canvas1.getContext('2d');
        var image1 = new Image();
        image1.onload = function () {
            //regular rotation about center
            var xpos = canvas1.width/2;
            var ypos = canvas1.height/2;
            ctx1.drawImage(image1,xpos-image1.width/2,ypos-image1.height/2);
            ctx1.save();
            ctx1.translate(xpos,ypos);
            ctx1.rotate(47*Math.PI / 180);//旋转47度
            ctx1.translate(-xpos,-ypos);
            ctx1.drawImage(image1,xpos-image1.width/2,ypos-image1.height/2);
            ctx1.restore();
        }
        image1.src = './img/bird5.png';
    }

二、参照点旋转

HTML5 canvas 绘图旋转_第1张图片

function onloadnew () {
        var canvas = document.getElementById('c2');
        var ctx2 = canvas.getContext("2d");
        var image2 = new Image();
        image2.onload = function () {
            //regular rotation about a point
            var angle = 120*Math.PI/180;//angle of rotation in radians
            var rx = 300, ry = 200; //the rotation x and y
            var px = 300, py = 50; //the objects center x and y
            var radius = ry -py; //the difference in y position or the radius
            var dx = rx + radius * Math.sin(angle);//the draw x
            var dy = ry - radius * Math.cos(angle);//the draw y 
            ctx2.drawImage(image2,300-image2.width/2,50-image2.height/2);
            ctx2.beginPath();
            ctx2.arc(300,50,5,0,Math.PI*2,false);
            ctx2.closePath();
            ctx2.fillStyle = 'rgba(0,255,0,0.25)';
            ctx2.fill();

            ctx2.save();
            ctx2.translate(dx,dy);
            ctx2.rotate(angle);
            ctx2.translate(-dx,-dy);
            ctx2.drawImage(image2,dx - image2.width/2,dy - image2.height/2);
            ctx2.restore;
        }
        image2.src = './img/bird1.png';
    }

 

转载于:https://www.cnblogs.com/dasheng0217/p/6912649.html

你可能感兴趣的:(HTML5 canvas 绘图旋转)