绘制带有渐变颜色的D3圆 [英] Draw a D3 circle with gradient colours

查看:90
本文介绍了绘制带有渐变颜色的D3圆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用渐变颜色绘制圆?说,从黄色到蓝色的渐变.

通常,要创建一个黄色的圆圈,我们可以使用以下代码:

  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).进入().append("circle");var circleattr =圆.attr("cx",function(d){xscale = xscale + xspace;返回xscale;}).attr("cy",function(d){yscale = yscale + xspace + 10;返回yscale;}).attr("r",function(d){返回d;}).style("fill","yellow"); 

解决方案

您必须先在SVG中定义渐变,然后用指向渐变元素的SVG链接填充圆.

 //定义渐变var梯度= 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");//定义渐变颜色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);//用渐变填充圆var circle = svg.append('circle').attr('cx',width/2).attr('cy',高度/2).attr('r',高度/3).attr('fill','url(#gradient)'); 

带有完整示例的 jsFiddle . MDN教程.结果图像:

How to draw a circle with gradient color? Say, a gradient from yellow to blue.

Normally, to create a circle in yellow we can use the following code:

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");

解决方案

You have to define the gradient in the SVG first, and then fill the circle with an SVG link to the gradient element.

// 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 with the complete example. More details on how to define SVG gradients in the MDN Tutorial. The resulting image:

这篇关于绘制带有渐变颜色的D3圆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆