HTML5画布上的多个点/颜色渐变 [英] Multiple points/colors gradient on HTML5 canvas
问题描述
我想用在不同位置的几种不同颜色创建的渐变来填充html5画布上的形状,例如
I would like to fill a shape on a html5 canvas with a gradient created from several differents colors at different positions, like on this picture.
您对我该怎么做有任何想法吗?
Do you have any ideas on how I could do that?
推荐答案
稍作搜索,我从Mozilla开发网络中找到了这个示例
Searching a little I have found this example from Mozilla Development Network
function draw() {
var ctx = document.getElementById('canvas').getContext('2d');
var radgrad = ctx.createRadialGradient(0,0,1,0,0,150);
radgrad.addColorStop(0, '#A7D30C');
radgrad.addColorStop(1, 'rgba(1,159,98,0)');
var radgrad2 = ctx.createRadialGradient(0,150,1,0,150,150);
radgrad2.addColorStop(0, '#FF5F98');
radgrad2.addColorStop(1, 'rgba(255,1,136,0)');
var radgrad3 = ctx.createRadialGradient(150,0,1,150,0,150);
radgrad3.addColorStop(0, '#00C9FF');
radgrad3.addColorStop(1, 'rgba(0,201,255,0)');
var radgrad4 = ctx.createRadialGradient(150,150,1,150,150,150);
radgrad4.addColorStop(0, '#F4F201');
radgrad4.addColorStop(1, 'rgba(228,199,0,0)');
ctx.fillStyle = radgrad4;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad3;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad2;
ctx.fillRect(0,0,150,150);
ctx.fillStyle = radgrad;
ctx.fillRect(0,0,150,150);
}
基于此,您可以将每个像元绘制为放射状渐变,并使用完全透明的颜色作为其最终步骤,以便与其他像元更好地融合.
Based int this, you could draw each cell as a radial gradient and use a total transparent color as its final step so it blend better with other cells.
没有它,我认为您将需要根据距每个像元的距离来计算每个像素的颜色.
Without it, I think that you will need to calculate each pixel color based on how far from each cell they are.
通常,如果在制作voronoi纹理时,先将表面划分为网格,然后为每个顶点分配颜色,然后对像素的颜色进行插值,并与形成其单元的顶点的距离进行插值.
Normally if when you make a voronoi texture, you divide the surface in a mesh and then assign a color to each vertex, then you interpolate the color of a pixel with the distance to the vertext that form its cell.
另请参见 http://www.raymondhill.net/voronoi/rhill-voronoi. html 来实现html5中真正的voronoi.它是开源的,并根据MIT许可证进行了许可,因此您可以使用它.
Also see http://www.raymondhill.net/voronoi/rhill-voronoi.html for an implementation of real voronoi in html5. It's open source and licensed under The MIT License, so you can use it.
这篇关于HTML5画布上的多个点/颜色渐变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!