5

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!

2 Answers2

8

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

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0

Canvas can't support direct transform; instead use the below code:

ctx.lineWidth = 100;
ctx.strokeStyle = "rgba(255, 255, 255, 0.5)";
ctx.strokeRect(0, 0, 640, 480);
ctx.lineWidth = 4;
ctx.strokeStyle = "#5E81AB";
ctx.strokeRect(50, 50, 540, 380);
Aaron Meese
  • 1,670
  • 3
  • 22
  • 32