How to flip images horizontally with HTML5

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

In IE, I can use:


to implement an image flip horizontally.

7条回答
  •  温柔的废话
    2020-11-28 08:12

    Mirror an image or rendering using the canvas.

    Note. This can be done via CSS as well.


    Mirroring

    Here is a simple utility function that will mirror an image horizontally, vertically or both.

    function mirrorImage(ctx, image, x = 0, y = 0, horizontal = false, vertical = false){
        ctx.save();  // save the current canvas state
        ctx.setTransform(
            horizontal ? -1 : 1, 0, // set the direction of x axis
            0, vertical ? -1 : 1,   // set the direction of y axis
            x + (horizontal ? image.width : 0), // set the x origin
            y + (vertical ? image.height : 0)   // set the y origin
        );
        ctx.drawImage(image,0,0);
        ctx.restore(); // restore the state as it was when this function was called
    }
    

    Usage

    mirrorImage(ctx, image, 0, 0, true, false); // horizontal mirror
    mirrorImage(ctx, image, 0, 0, false, true); // vertical mirror
    mirrorImage(ctx, image, 0, 0, true, true);  // horizontal and vertical mirror
    

    Drawable image.

    Many times you will want to draw on images. I like to call them drawable images. To make an image drawable you convert it to a canvas

    To convert an image to canvas.

    function makeImageDrawable(image){
        if(image.complete){ // ensure the image has loaded
            var dImage = document.createElement("canvas"); // create a drawable image
            dImage.width = image.naturalWidth;      // set the resolution
            dImage.height = image.naturalHeight;
            dImage.style.width = image.style.width; // set the display size
            dImage.style.height = image.style.height; 
            dImage.ctx = dImage.getContext("2d");   // get drawing API
                                                    // and add to image
                                                    // for possible later use
            dImage.ctx.drawImage(image,0,0);
            return dImage;
        }
        throw new ReferenceError("Image is not complete.");
     }
    

    Putting it all together

     var dImage = makeImageDrawable(image);  // convert DOM img to canvas
     mirrorImage(dImage.ctx, dImage, 0, 0, false, true); // vertical flip
     image.replaceWith(dImage);  // replace the DOM image with the flipped image
     
    

    More mirrors

    If you wish to be able to mirror along an arbitrary line see the answer Mirror along line

提交回复
热议问题