javascript - SVG,D3 : Understanding stop offset attribute

标签 javascript svg d3.js linear-gradients

我试图理解“stop”svg 元素的偏移属性,但无法理解它。代码如下:

var vis = d3.select(scalecontainer)
            .append("svg")
            .attr('height', 30)

var gradient = vis.append("linearGradient")
                    .attr("y1", 0)
                    .attr("y2", 0)
                    .attr("x1", "0%")
                    .attr("x2", "100%")
                    .attr("id", "gradient")
                    .attr("gradientUnits", "userSpaceOnUse")

gradient
    .append("stop")
    .attr("offset", "0%")
    .attr("stop-color", "red")

gradient
    .append("stop")
    .attr("offset","33%")
    .attr("stop-color", "yellow")

gradient
    .append("stop")
    .attr("offset", "66%")
    .attr("stop-color", "green")

var rect = vis.append("rect")
            .attr("x", 10)
            .attr("y", 10)
            .attr("width", 100)
            .attr("height", 20)
            .attr("fill", "url(#gradient)");

这是我得到的输出:

enter image description here

难道不应该有“红色”、“黄色”和“绿色”三种不同的均匀间隔的颜色变化吗?我在这里做错了什么?

最佳答案

有 3 种不同的均匀间隔的颜色变量,但您的 rect 的宽度只有 100px,而 linearGradient 的宽度为 svg > 元素。 将两个宽度设置相等,渐变将完全可见。

在矩形内获取完整渐变的最简单方法是设置 .attr("gradientUnits", "objectBoundingBox")。这样,您的渐变将被缩放以适合引用渐变的元素。 所有可能设置的详细说明可以阅读 MDN .

关于javascript - SVG,D3 : Understanding stop offset attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30681773/

相关文章:

javascript - 在react js中添加子函数

javascript - 绘制谷歌地图形状标记对象

javascript - 如何在 svg 的 <g> 标签中获取内部标签?

javascript - 带有文本标签 : How do I keep the hover color even when over text label? 的按钮

javascript - 中心 d3.js JavaScript 绘图

javascript - 如何确定对象中的任何值是否为非空?

javascript - 访问函数作用域外的变量

JavaScript,创建新的 html 元素 : the content of the new created <td> is inserted in old <td>

javascript - 使用 d3.js 为 svg 图表创建标记

javascript - D3 径向图的编程旋转