How to flip images horizontally with HTML5

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

In IE, I can use:


to implement an image flip horizontally.

相关标签:
7条回答
  • 2020-11-28 08:15

    For anyone stumbling upon this. If you want to do more complex drawing, the other scale-based answers don't all work. By 'complex' i mean situations where things are more dynamic, like for games.

    The problem being that the location is also flipped. So if you want to draw a small image in the top left corner of the canvas and then flip it horizontally, it will relocate to the top right.

    The fix is to translate to the center of where you want to draw the image, then scale, then translate back. Like so:

    if (flipped) {
      ctx.translate(x + width/2, y + width/2);
      ctx.scale(-1, 1);
      ctx.translate(-(x + width/2), -(y + width/2));
    }
    ctx.drawImage(img, x, y, width, height);
    

    Here x and y are the location you want to draw the image, and width and height are the width and height you want to draw the image.

    0 讨论(0)
提交回复
热议问题