How to flip images horizontally with HTML5

前端 未结 7 1190
暖寄归人
暖寄归人 2020-11-28 07:14

In IE, I can use:


to implement an image flip horizontally.

7条回答
  •  情话喂你
    2020-11-28 07:52

    I came across this page, and no-one had quite written a function to do what I wanted, so here's mine. It draws scaled, rotated, and flipped images (I used this for rending DOM elements to canvas that have these such transforms applied).

    var myCanvas = document.getElementById("myCanvas");
    var ctx = myCanvas.getContext("2d");
    var img = document.getElementById("myimage.jpg"); //or whatever
    var deg = 13; //13 degrees rotation, for example
    var flip = "true";
    
    function drawImage(img, x, y, width, height, deg, flip){
        //save current context before applying transformations
        ctx.save();
        //convert degrees to radians
        if(flip == "true"){ 
            var rad = deg * Math.PI / 180;
        }else{
            var rad = 2*Math.PI - deg * Math.PI / 180;
        }
        //set the origin to the center of the image
        ctx.translate(x + width/2, y + height/2);
        //rotate the canvas around the origin
        ctx.rotate(rad);
        if(flip == "true"){
            //flip the canvas
            ctx.scale(-1,1);
        }
        //draw the image    
        ctx.drawImage(img, -width/2, -height/2, width, height);
        //restore the canvas
        ctx.restore();
    }
    

提交回复
热议问题