如何将渐变的底部锚定到它在 HTML5 画布中填充的容器
How can I anchor the bottom of a gradient to the container that it fills in HTML5 Canvas?
我正在尝试在画布的一半处绘制一个渐变,以便渐变覆盖上半部分。
问题是我不知道如何使渐变与"容器"(由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>
渐变填充是相对于画布的,而不是相对于元素的,所以要完成你的任务,你应该做这样的事情。
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>
相关文章:
- html5视频中的Youtube类型注释
- 如何在运行时在HTML5画布中绘制正方形
- 正在检测html5手机中的抖动
- Unicode字符未在HTML5画布中正确呈现
- 通过phonegap中的电子邮件发送存储在html5 localStorage中的信息
- 如何在html5画布中绘制圆形作为单独的画布
- 重定向到具有轨道的html5模式中的正确角度路线
- html5画布中的套索工具
- 什么'是在HTML5画布中创建关键事件的最佳方式
- HTML5模式中的$location需要<基本>
- 在HTML5画布中,是否可以围绕旋转对象旋转对象
- 如何将自定义字体轻松地放入HTML5画布中
- 如何在MVC5中运行时在HTML5 Canvas中显示图像
- 如何在HTML5视频中获得寻找事件的起点
- 在Javascript HTML5+Canvas中处理精灵鼠标点击的最佳方式
- 使用模式在 HTML5/JS 中绘制图像
- 如何在HTML5 / javascript中查找十六进制值的特定位或数字
- 如何在html5/JS中只预加载音频文件的一部分
- HTML5游戏中最有效的视差方式
- 存储在HTML5存储中的引导崩溃的当前状态