Skew transformation HTML5 canvas
Asked Answered
U

2

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!

Ubangishari answered 2/4, 2012 at 19:8 Comment(0)
L
9

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

Largent answered 2/4, 2012 at 19:10 Comment(1)
A true legend, someone needs to make a cheat sheet for matrix transforms ...Harslet
T
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);
Tramontane answered 4/10, 2022 at 6:36 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.