我想在html5 canvas元素中使用基於單位/法向矢量的漸變,然後將它們轉換爲所需的結果。但是,我似乎認爲這可能是因爲我缺乏數學。我試圖創建一個從0,0到1,0的簡單線性漸變(即從左到右的簡單單位漸變)。之後,我轉換畫布進行縮放,旋轉和移動漸變。但是,例如,如果給出45DEG的旋轉值,則實際梯度會出現錯誤。右下角的方式非常黑,即漸變看起來不夠「大」。這裏是我的代碼:畫布和單位/正常梯度
var rect = {x: 0, y: 0, w: 500, h: 500};
var rotation = 45 * Math.PI/180;
var sx = 1;
var sy = 1;
var tx = 0;
var ty = 0;
var radial = false;
// Create unit vector 0,0 1,1
var grd = radial ? ctx.createRadialGradient(0, 0, 0, 0, 0, 0.5) : ctx.createLinearGradient(0, 0, 1, 0);
grd.addColorStop(0, 'black');
grd.addColorStop(0.1, 'lime');
grd.addColorStop(0.9, 'yellow');
grd.addColorStop(1, 'black');
// Add our rectangle path before transforming
ctx.beginPath();
ctx.moveTo(rect.x, rect.y);
ctx.lineTo(rect.x + rect.w, rect.y);
ctx.lineTo(rect.x + rect.w, rect.y + rect.h);
ctx.lineTo(rect.x, rect.y + rect.h);
ctx.closePath();
// Rotate and scale unit gradient
ctx.rotate(rotation);
ctx.scale(sx * rect.w, sy * rect.h);
ctx.fillStyle = grd;
// Fill gradient
ctx.fill();
而這裏的小提琴嘗試一下:
好奇的是,改變單位線性漸變向量的一個因素約爲1.41,使梯度看的權利:
ctx.createLinearGradient(0, 0, 1.41, 0)
可以在這個小提琴可以看出:
但我不知道如何計算該因子?
哇,很好的答案。其實,就在幾分鐘之前,我已經想出了線性漸變的中心問題:) – anderswelt