画布中的对角线到角落渐变

时间:2016-09-20 14:02:30

标签: javascript canvas fabricjs

我需要在画布中从一个角落到另一个角落,而不是css。

Check example : http://jsfiddle.net/58y8b/77/

第一个框很好,因为它是一个正方形,渐变坐标只是左上角和右下角。 有没有办法计算下两个矩形的坐标,这样它们就像第一个盒子一样从一个角落到另一个角落?

1 个答案:

答案 0 :(得分:4)

将渐变拟合到Rectangle的4个角

这可以通过一点点触发来完成。

解决方案

该图显示了需要做的事情。

enter image description here

我们需要找到点 E D

的坐标

我们有矩形(假设左上角是(0,0),宽度和高度 W H 。我们找到角度 pheta (左下角)与右下方的 pheta 角度相同。我们需要 AB 这一行的长度,它是直角三角形的一部分我们有 H 的低位和角度 pheta 。所以 AB H * cos(pheta)。然后我们得到90度的向量对角线,并将其长度设置为 AB 然后找到中心 C 并减去矢量以获得 E 并将矢量添加到中心 C D

要查找对角线的角度,请使用Math.atan2(-H,W)

代码

它的代码来自您提供的小提琴以及rect4

//==========================================================
// NOTE this assumes that the top left of rect is at (0,0)
// if it is not then add the top left coordinate to the
// coordinates of E and D when defining the gradient position
// all else is the same
//-----------------------------------------------------------
// get angle from bottom left to top right
var pheta = Math.atan2(-rect4.height,rect4.width);
// get the length of the line from bottom right to diagonal line
// we got the ang of.
var AB = Math.abs(rect4.height * Math.cos(pheta)); // dont need the abd but cant be bothered
                                                 // explaining why its negative 
// get vector at 90 deg from found angle
var xdx = Math.cos(pheta + Math.PI/2);
var xdy = Math.sin(pheta + Math.PI/2);
// from the center C of rectangle move AB dist back and forward to find
// points E and D
var x1 = rect4.width/2 - xdx * AB;
var y1 = rect4.height/2 - xdy * AB;
var x2 = rect4.width/2 + xdx * AB;
var y2 = rect4.height/2 + xdy * AB;
// Now create the gradient from E to D
rect4.setGradient('fill', {
    type: 'linear',
    x1: x1,
    y1: y1,
    x2: x2,
    y2: y2,
    colorStops: gradient
});

结果

图像不需要单词..

enter image description here