Image transforms

by Gustavo Carvalho

HTML

<canvas id="canvas" width=100 height=100></canvas>
<button id="flipX">flipX</button>
<button id="flipY">flipY</button>
<button id="rotate">rotate</button>
<button id="save">save</button>
<div id="savedImg"></div>

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var sx = 1, // x scale
    sy = 1, // y scale
    angle = 0; // rotation angle


    // Sample graphics
    ctx.beginPath();
    ctx.rect(10, 10, 20, 50);
    ctx.fillStyle = 'yellow';
    ctx.fill();
    ctx.lineWidth = 7;
    ctx.strokeStyle = 'black';
    ctx.stroke();

var img = new Image();
img.src = canvas.toDataURL("image/png");
//img.src = "https://dl.dropboxusercontent.com/u/37981960/Images/so/smallcar.png";

img.onload = function () {
    canvas.width = img.width;
    canvas.height = img.height;
    ctx.drawImage(img, 0, 0);
}

function drawScaled(image, sx, sy) {
    canvas.width = image.width;
    canvas.height = image.height;

    var tx = sx >= 0 ? 0 : canvas.width;
    var ty = sy >= 0 ? 0 : canvas.height;

    ctx.save();
    ctx.translate(tx, ty);
    ctx.scale(sx, sy);
    ctx.drawImage(image, 0, 0);
    ctx.restore();
}

function drawRotated(image, angle){
    canvas.width = image.width;
    canvas.height = image.height;
    ctx.save();
    ctx.translate(canvas.width/2, canvas.height/2);
    ctx.rotate(angle);
    ctx.translate(-(canvas.width/2), -(canvas.height/2));
    ctx.drawImage(image, 0, 0);
    ctx.restore();
}

function convertCanvasToImage(canvas) {
    var image = new Image();
    image.src = canvas.toDataURL("image/png");
    return image;
}

// configure buttons and actions

var button1 = document.getElementById("flipX");
button1.onclick = function () {
    flipX();
}
var button2 = document.getElementById("flipY");
button2.onclick = function () {
    flipY();
}
var button3 = document.getElementById("save");
button3.onclick = function () {
    save();
}
var button4 = document.getElementById("rotate");
button4.onclick = function () {
    rotate(img, Math.PI/2);
}

function flipX() {
    sx*=-1;
    drawScaled(img, sx, 1);
}

function flipY() {
    sy*=-1;
    drawScaled(img, 1, sy);
}

function rotate(){
    angle += Math.PI/2;
    drawRotated(img,...