如何画一个渐变色的圆?比如,从黄色到蓝色的渐变。
通常,要创建一个黄色的圆圈,我们可以使用以下代码:
var cdata=[50,40];
var xscale=40;
var xspace =50;
var yscale=70;
var svg = d3.select("body")
.append("svg")
.attr("width", 1600)
.attr("height", 1600);
var circle = svg.selectAll("circle")
.data(cdata)
.enter()
.append("circle");
var circleattr = circle
.attr("cx", function(d) {
xscale = xscale+xspace;
return xscale;
})
.attr("cy", function(d) {
yscale=yscale+xspace+10;
return yscale;
})
.attr("r", function(d) {
return d;
})
.style("fill","yellow");
最佳答案
您必须先在 SVG 中定义渐变,然后用指向渐变元素的 SVG 链接填充圆圈。
// Define the gradient
var gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("spreadMethod", "pad");
// Define the gradient colors
gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", "#a00000")
.attr("stop-opacity", 1);
gradient.append("svg:stop")
.attr("offset", "100%")
.attr("stop-color", "#aaaa00")
.attr("stop-opacity", 1);
// Fill the circle with the gradient
var circle = svg.append('circle')
.attr('cx', width / 2)
.attr('cy', height / 2)
.attr('r', height / 3)
.attr('fill', 'url(#gradient)');
A jsFiddle与完整的例子。关于如何在 MDN Tutorial 中定义 SVG 渐变的更多详细信息.结果图像:
关于javascript - 用渐变颜色绘制一个 D3 圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20837147/