texturing with context2d

by gamealchemist

HTML

<canvas id='cv' width=600 height=300></canvas>
<canvas id='cropCv' width=600 height=200></canvas>
<br>
<br>
Original Image : <br>
<img src='http://cdn.cutestpaw.com/wp-content/uploads/2013/09/l-White-Bunny.jpg' id='bunny' />

JavaScript

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

var cropCanvas = document.getElementById('cropCv');
var cropCtx = cropCanvas.getContext('2d');
cropCanvas.width = bunny.width;
cropCanvas.height = bunny.height;
cropCtx.drawImage(bunny, 0, 0);

var debug = false;

// --------------------------------------------

function rasterizeTriangle(v1, v2, v3, mirror) {
    var fv1 = {
        x: 0,
        y: 0,
        u: 0,
        v: 0
    };
    fv1.x = v1.x;
    fv1.y = v1.y;
    fv1.u = v1.u;
    fv1.v = v1.v;
    ctx.save();
    // Clip to draw only the triangle
    ctx.beginPath();
    ctx.moveTo(v1.x, v1.y);
    ctx.lineTo(v2.x, v2.y);
    ctx.lineTo(v3.x, v3.y);
    ctx.clip();
    // compute mirror point and flip texture coordinates for lower-right triangle
    if (mirror) {
        fv1.x = fv1.x + (v3.x - v1.x) + (v2.x - v1.x);
        fv1.y = fv1.y + (v3.y - v1.y) + (v2.y - v1.y);
        fv1.u = v3.u;
        fv1.v = v2.v;
    }
    // 
    var angleX = Math.atan2(v2.y - fv1.y, v2.x - fv1.x);
    var angleY = Math.atan2(v3.y - fv1.y, v3.x - fv1.x);
    var scaleX = lengthP(fv1, v2);
    var scaleY = lengthP(fv1, v3);
    var cos = Math.cos,
        sin = Math.sin;
    // ----------------------------------------
    //     Transforms
    // ----------------------------------------
    // projection matrix (world relative to center => screen)
    var transfMatrix = [];
    transfMatrix[0] = cos(angleX) * scaleX;
    transfMatrix[1] = sin(angleX) * scaleX;
    transfMatrix[2] = cos(angleY) * scaleY;
    transfMatrix[3] = sin(angleY) * scaleY;
    transfMatrix[4] = fv1.x;
    transfMatrix[5] = fv1.y;
    ctx.setTransform.apply(ctx, transfMatrix);
    // !! draw !!
    ctx.drawImage(bunny, fv1.u, fv1.v, v2.u - fv1.u, v3.v - fv1.v,
    0, 0, 1, 1);
    //
    ctx.restore();
};



var v1 = {
    x: 200 + 20,
    y: 20,
    u: 0,
    v: 0
};

var v2 = {
    x: 200 + 240,
    y: 50,
    u: bunny.width,
    v: 0
};

var v3 = {
    x: 200 +...