How to flip images horizontally with HTML5

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

In IE, I can use:


to implement an image flip horizontally.

7条回答
  •  醉话见心
    2020-11-28 08:01

    I like Eschers function above. I have made it a little neater and better. I have added flop (vertically) besides flip. Also a possibility to draw/rotate around the center of the image instead of top left. Finally, the function does not require all arguments. img, x and y are required but the rest are not.

    If you were using something like context.drawImage(...), you can now just use drawImage(...) and add the rotate/flip/flop functionality explained here:

    function drawImage(img, x, y, width, height, deg, flip, flop, center) {
    
    context.save();
    
    if(typeof width === "undefined") width = img.width;
    if(typeof height === "undefined") height = img.height;
    if(typeof center === "undefined") center = false;
    
    // Set rotation point to center of image, instead of top/left
    if(center) {
        x -= width/2;
        y -= height/2;
    }
    
    // Set the origin to the center of the image
    context.translate(x + width/2, y + height/2);
    
    // Rotate the canvas around the origin
    var rad = 2 * Math.PI - deg * Math.PI / 180;    
    context.rotate(rad);
    
    // Flip/flop the canvas
    if(flip) flipScale = -1; else flipScale = 1;
    if(flop) flopScale = -1; else flopScale = 1;
    context.scale(flipScale, flopScale);
    
    // Draw the image    
    context.drawImage(img, -width/2, -height/2, width, height);
    
    context.restore();
    }
    

    Examples:

    var myCanvas = document.getElementById("myCanvas");
    var context = myCanvas.getContext("2d"); // i use context instead of ctx
    
    var img = document.getElementById("myImage"); // your img reference here!
    
    drawImage(img, 100, 100); // just draw it 
    drawImage(img, 100, 100, 200, 50); // draw it with width/height specified
    drawImage(img, 100, 100, 200, 50, 45); // draw it at 45 degrees
    drawImage(img, 100, 100, 200, 50, 0, true); // draw it flipped
    drawImage(img, 100, 100, 200, 50, 0, false, true); // draw it flopped
    drawImage(img, 100, 100, 200, 50, 0, true, true); // draw it flipflopped
    drawImage(img, 100, 100, 200, 50, 45, true, true, true); // draw it flipflopped and 45 degrees rotated around the center of the image :-)
    

提交回复
热议问题