StackOverflow_17027871: flipping-canvas-not-reversing
Illustration of answer to http://stackoverflow.com/questions/17027871/flipping-canvas-not-reversing.
by Gustavo Carvalho
June 10, 2013
HTML
<h3>Click on the canvas to flip !</h3>
<canvas id="myCanvas"></canvas>
<br />
<br />
<h5>
Image taken from <a href="http://www.freeimages.co.uk/galleries/nature/woodland/index.htm">FreeImages.co.uk</a>.
</h5>
CSS
body { text-align: center; }
canvas { border: 1px solid black; }
JavaScript
/* Define the flipping function */
var flipped = true;
function flipAndDraw(imgSrc) {
flipped = !flipped;
var canvasH = document.getElementById("myCanvas");
var ctxH = canvasH.getContext("2d");
var img = new Image();
img.onload = function () {
canvasH.width = img.width;
canvasH.height = img.height;
if (flipped) {
ctxH.save();
ctxH.scale(1, -1);
ctxH.translate(0, -img.height);
ctxH.drawImage(img, 0, 0);
ctxH.restore();
} else {
ctxH.drawImage(img, 0, 0);
}
};
img.src = imgSrc;
}
/* Add listener for flipping on click */
var imgURL = "http://www.freeimageslive.com/"
+ "galleries/nature/woodland/"
+ "cumbriawoodland02877_small.jpg"
document.getElementById("myCanvas").addEventListener(
"click", function() {
flipAndDraw(imgURL);
});
/* Initialy draw the image on canvas */
flipAndDraw(imgURL);