Skew transformation HTML5 canvas

user551761 picture user551761 · Apr 2, 2012 · Viewed 13.9k times · Source

I'm trying to implement skew transformation using the "x" axis with HTML5 canvas, but my code fails... Here is my JavaScript:

function init() {
    var canvas = document.getElementById('skewTest'),
        context = canvas.getContext('2d'),
        angle = Math.PI / 4;
    img = document.createElement('img');
    img.src = 'img.gif';
    img.onload = function () {
        context.setTransform(1, Math.tan(angle), 1, 1, 0, 0);
        context.clearRect(0, 0, 200, 200);
        context.drawImage(img, 0, 0, 100, 100);
    }
}

I'll be very glad if I see working example in JsFiddle.

Thank you in advance!

Answer

kennytm picture kennytm · Apr 2, 2012

The correct matrix of skewing in only one direction is

    context.setTransform(1, Math.tan(angle), 0, 1, 0, 0);
    //                                       ^

With the number at ^ being 1, you are skewing the image in the y-direction by 45° as well.

Sample: http://jsbin.com/etecay/edit#html,live