我正在尝试在画布中间绘制一个渐变,以便渐变覆盖上半部分。
问题是我无法弄清楚如何使渐变排列
'container'(由fillRect()
控制的形状) - 当我将容器推到正确的位置时,渐变停留在画布的底部;而不是它正在填充的容器的底部。
渐变的底部应该从它填充的容器的底部开始,而不是从画布的底部开始。我怎样才能做到这一点?
//not sliding gradient container upward
function paintC1() {
var canvas = document.getElementById('canvas-1');
var context = canvas.getContext('2d');
var height = canvas.height;
var width = canvas.width;
var grd = context.createLinearGradient(width, 0, width, height);
grd.addColorStop(0.5, 'rgba(0,174,239,0)');
grd.addColorStop(0.85, 'rgba(0,174,239,0.6)');
grd.addColorStop(1, 'rgba(0,174,239,1)');
context.fillStyle = grd;
context.fillRect(0, 0, width, height);
}
/* for comparison */
//sliding gradient container up
function paintC2() {
var canvas = document.getElementById('canvas-2');
var context = canvas.getContext('2d');
var height = canvas.height;
var width = canvas.width;
var grd = context.createLinearGradient(width, 0, width, height);
grd.addColorStop(0.5, 'rgba(0,174,239,0)');
grd.addColorStop(0.85, 'rgba(0,174,239,0.6)');
grd.addColorStop(1, 'rgba(0,174,239,1)');
context.fillStyle = grd;
context.fillRect(0, -50, width, height);
}
paintC1();
paintC2();
<canvas id="canvas-1" style="width:250px; height:500; border-style:solid; float:left; margin-right:10px;"></canvas>
<canvas id="canvas-2" style="width:250px; height:500; border-style:solid; float:left; margin-right:10px;"></canvas>
答案 0 :(得分:0)
渐变填充是相对于画布而不是元素,所以为了完成你的任务你应该做这样的事情。
var grd = context.createLinearGradient(width, -50, width, height -50);
否则你必须翻译上下文:
var canvas = document.getElementById('c');
var context = canvas.getContext('2d');
var gradient = context.createLinearGradient(0, 0, 0, 30);
var sampleW = 100;
var sampleH = 30;
gradient.addColorStop(0.5, 'rgba(0,174,239,0)');
gradient.addColorStop(0.85, 'rgba(0,174,239,0.6)');
gradient.addColorStop(1, 'rgba(0,174,239,1)');
var translations= [[30, 150],[100, 110],[170, 70],[240, 30]];
context.font = '12px verdana bold';
for (var i = 0; i < translations.length; i++) {
var t= translations[i];
context.save();
// gradient is defined at the origin,
// so we have to move the origin
context.translate(t[0], t[1])
context.fillStyle = gradient;
context.fillRect(0, 0, sampleW, sampleH);
context.strokeRect(0, 0, sampleW, sampleH);
context.restore();
}
<canvas id="c" width="500" height="500"></canvas>