Canvas How to - Horizontally flipped Image on Canvas








Question

We would like to know how to horizontally flipped Image on Canvas.

Answer


<!--from   w  w  w  .  j a  v a 2s.  c o m-->
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>//<![CDATA[ 
window.onload=function(){
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var img = new Image();
img.onload = function () {
    ctx.save();
    ctx.beginPath();
    ctx.translate(canvas.width, 0);
    ctx.scale(-1, 1);
    ctx.drawImage(img, 0, 0);
    ctx.restore();
}
img.src = "http://www.java2s.com/style/download.png";
}//]]>  
</script>
</head>
<body>
  <p>Original Image</p>
  <img src="http://www.java2s.com/style/download.png" width=200
    height=78>
  <p>Horizontally flipped Image on Canvas</p>
  <canvas id="canvas" width=200 height=78></canvas>
</body>
</html>

The code above is rendered as follows: