How to horizontally flip an image

前端 未结 3 926
误落风尘
误落风尘 2021-01-19 05:59

How can i draw only two images with reversing I don\'t know how to reverse. Pls help.

    var canvas = document.createElement(\'canvas\');
          


        
3条回答
  •  青春惊慌失措
    2021-01-19 06:16

    Mirror an image

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

    // arguments
    // ctx : the context on which to draw the mirrored image
    // image : the image to mirror
    // x,y : the top left of the rendered image
    // horizontal : boolean if true mirror along X
    // vertical : boolean if true mirror along y
    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
    

    More mirrors

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

提交回复
热议问题