Search code examples
javascripthtmlimagehtml5-canvas

How to flip images horizontally with HTML5


In IE, I can use:

<img src="http://example.com/image.png" style="filter:FlipH">

to implement an image flip horizontally.

Is there any way to flip horizontally in HTML5? (maybe by using canvas?)

thanks all :)


Solution

  • canvas = document.createElement('canvas');
    canvasContext = canvas.getContext('2d');
    
    canvasContext.translate(width, 0);
    canvasContext.scale(-1, 1);
    canvasContext.drawImage(image, 0, 0);
    

    Here's a snippet from a sprite object being used for testing and it produces the results you seem to expect.

    Here's another site with more details. http://andrew.hedges.name/widgets/dev/