javascript - 如何在点上应用渐变蒙版
问题描述
我想为我的情节上的所有点应用渐变蒙版,但不是每个点。该梯度应该从起点到最大点呈放射状变化。
我的意思的例子如下,我想实现与此完全相似的东西:
我试图像这样对所有圈子进行分组:
this.svg.append("g").attr('class', 'items-container')
.selectAll('circle')
.data(this.data.suppliers)
.enter()
.append('circle')
.attr(..) //added proper cx,cy,r so got circles in proper point
然后我尝试创建渐变:
var defs = this.svg.append('defs');
var gradient = defs
.append('linearGradient')
.attr('id', 'svgGradient')
.attr('x1', '0%')
.attr('x2', '100%')
.attr('y1', '0%')
.attr('y2', '100%');
gradient
.append('stop')
.attr('class', 'start')
.attr('offset', '0%')
.attr('stop-color', 'red')
.attr('stop-opacity', 1);
gradient
.append('stop')
.attr('class', 'end')
.attr('offset', '100%')
.attr('stop-color', 'blue')
.attr('stop-opacity', 1);
并将其应用于组:
this.svg
.select('.items-container')
.style("fill","url(#svgGradient)")
但它不起作用。你能帮帮我吗?
解决方案
这对我来说似乎是一个XY 问题。据我所知,您不需要 a<mask>
或类似的东西。您所需要的只是根据克拉值填充圆圈,克拉值从 0 到 3。
话虽这么说,而且由于您的颜色序列可能是interpolateViridis,我建议您只需使用顺序比例......
const colorScale = d3.scaleSequential(d3.interpolateViridis)
.domain([0, 3]);
...并根据克拉值(此处为x
属性)填充您的圈子:
circleSelection.style("fill", d => colorScale(d.x))
这是一个演示:
const svg = d3.select("svg");
const data = d3.range(120).map(function(d, i) {
return {
y: 14*d3.easeCubic(i/120) + (Math.random()*(6*i/120)),
x: i / 40
}
});
const yScale = d3.scaleLinear()
.range([280, 20])
.domain([0, 20]);
const xScale = d3.scaleLinear()
.range([30, 480])
.domain([0, 3]);
const colorScale = d3.scaleSequential(d3.interpolateViridis)
.domain([0, 3]);
const circles = svg.selectAll(null)
.data(data)
.enter()
.append("circle")
.attr("r", 6)
.attr("cx", d => xScale(d.x))
.attr("cy", d => yScale(d.y))
.style("stroke", "dimgray")
.style("fill", d => colorScale(d.x));
svg.append("g")
.attr("transform", "translate(30,0)")
.call(d3.axisLeft(yScale))
svg.append("g")
.attr("transform", "translate(0,280)")
.call(d3.axisBottom(xScale))
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg width="500" height="300"></svg>
推荐阅读
- 3d - Zbrusch Core - 无法雕刻到圆柱体上
- html - 这个定制的引导代码是否需要我缺少的东西?
- javascript - 多动作 API 最佳实践/设计模式
- laravel - 模型的关系并向用户显示余额
- javascript - 如何将流媒体服务价格数组转换为按服务长度分类的对象数组?
- php - 如果用户有名字,如何显示某些内容,如果没有,如何显示其他内容
- javascript - 不使用 getElementById 的多个元素 onclick 的 JS 函数
- javascript - 生成 PDF 并且 PDF 存储在生成它的位置
- r - 如何一次汇总多个列?
- sql - 我如何从一个直通表中查询一条记录,并从 sequelize 中的其他两个表中获取数据?