簡體   English   中英

畫布中對角線到角線的漸變

[英]Diagonal corner to corner gradient in canvas

我需要在畫布中從一個角落到另一個角落有一個對角漸變,而不是CSS。

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

第一個框很好,因為它是一個正方形,所以漸變坐標位於左上方和右下方。 有沒有一種方法可以計算下兩個矩形的坐標,以使它們像第一個框一樣獲得從一個角到另一個角的漸變?

將漸變擬合到矩形的4個角

只需輕輕一點就可以完成。

解決方案

該圖顯示了需要完成的工作。

在此處輸入圖片說明

我們需要找到E點和D點的坐標

我們有矩形(假定左上角為(0,0),其具有的寬度和高度W,H。我們發現該角度pheta(左下),其是相同的角度上右下方pheta,我們需要的長度線AB的角 ,它是直角三角形的一部分,我們有斜線 H ,角度為pheta ,所以ABH * 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
});

結果

圖片無需文字。

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM