1

I'm using canvas for a project and I have a number of elements that I'm skewing. I'm only skewing on the y value and just want to know what the new width of the image is after skewing (so I can align it with another canvas element). Check out the code below to see what I mean

ctx.save();
//skew the context
ctx.transform(1,0,1.3,0,0,0);
//draw two images with different heights/widths
ctx.drawImage(image,0,0,42,60);
ctx.drawImage(image,0,0,32,25);

The goal would be to know that the 42 by 60 image was now a X by 60 image so I could do some translating before drawing it at 0,0. It's easy enough to measure each image individually, but I have different skew values and heights/widths throughout the project that need to be align. Currently I use this code (works decently for images between 25 and 42 widths):

var skewModifier = imageWidth*(8/6)+(19/3);
var skewAmount = 1.3; //this is dynamic in my app
var width = (skewModifier*skewAmount)+imageWidth;

As images get wider though this formula quickly falls apart (I think it's a sloping formula not a straight value like this one). Any ideas on what canvas does for skews?

4

2 回答 2

7

您应该能够以数学方式推导出它。我相信:

Math.atan(skewAmount)是角度,以弧度表示,某物相对于原点倾斜。

所以 1.3 会使物体倾斜 0.915 弧度或 52 度。

所以这是一个红色的未倾斜对象,旁边是同一个倾斜的对象(涂成绿色)。所以你有一个直角三角形:

在此处输入图像描述

我们知道原点角度(0.915 rads)并且我们知道相邻边长,对于您的两个图像,它是 60 和 25。(红色的高度)。

斜边是偏斜的长边。

对面是三角形底部——它倾斜了多少!

如果我记得的话,切线让我们对面/相邻,所以对于第一个:

tan(0.915) = opposite / 60, 在我们的 JavaScript 代码中解决相反的问题:

opposite = Math.tan(0.915)*60

因此,倾斜对象的底部距离原点大约 77 个像素。让我们检查一下我们在画布中的工作:

http://jsfiddle.net/LBzUt/

在我看来很好!

有问题的三角形当然是画布原点,我画的那个黑点,以及红色矩形的左下角,这是我们在倾斜之前搜索的原始位置。

这是一个有点随意的解释。任何问题?

于 2012-02-14T20:52:05.560 回答
2

以西蒙的小提琴示例更进一步,因此您可以简单地输入度数:

这是小提琴 http://jsfiddle.net/LBzUt/33/

于 2012-10-11T15:28:29.027 回答