gpt4 book ai didi

javascript - 使重叠的 d3.js 雷达图元素透明

转载 作者:行者123 更新时间:2023-12-03 03:45:02 25 4
gpt4 key购买 nike

如何使 d3.js 雷达图中的重叠部分透明

下面的雷达图 blob 是使用 d3.js 创建的。红色和绿色相交的空间应该是透明的(这将用于比较之前<->之后)。图表下方的代码片段包含用于创建雷达图的代码。为了简单起见,我没有包含 5 个轴:

enter image description here

/* Original radar chart design created by Nadieh Bremer - VisualCinnamon.com */

////////////////////////// Data //////////////////////////////

var data = [
[//Before - red
{axis:"First",value:0.49},
{axis:"Banana",value:0.79},
{axis:"Scratch",value:0.70},
{axis:"Wheelie",value:0.09},
{axis:"Pantalon",value:0.37},
],[//After - green
{axis:"First",value:0.64},
{axis:"Banana",value:0.44},
{axis:"Scratch",value:0.37},
{axis:"Wheelie",value:0.84},
{axis:"Pantalon",value:0.81},
]
];

//////////////////////// Setup ////////////////////////////////

var margin = {top: 50, right: 50, bottom: 50, left: 50},
width = 300,
height = 300;
var color = d3.scale.ordinal().range(["#CC333F","#53e87d"]);
var radarChartOptions = {
w: width, //Width of the circle
h: height, //Height of the circle
margin: margin, //The margins of the SVG
opacityArea: 0.7, //The opacity of the area of the blob
color: color //Color function
};

//////////////////////// RadarChart ///////////////////////////

RadarChart("#radarChart1", data, radarChartOptions);

/////////////////////////////////////////////////////////
/////////////// The Radar Chart Function ////////////////
/////////////// Written by Nadieh Bremer ////////////////
////////////////// VisualCinnamon.com ///////////////////
/////////// Inspired by the code of alangrafu ///////////
/////////////////////////////////////////////////////////

function RadarChart(id, data, options) {

/////////////////////////////////////////////////////////
/////////////// Prep ////////////////
/////////////////////////////////////////////////////////

var cfg = radarChartOptions;
var allAxis = (data[0].map(function(i, j){return i.axis})), //Names of each axis
total = allAxis.length, //The number of different axes
radius = Math.min(cfg.w/2, cfg.h/2), //Radius of the outermost circle
Format = d3.format('%'), //Percentage formatting
angleSlice = Math.PI * 2 / total; //The width in radians of each "slice"
var rScale = d3.scale.linear() //Scale for the radius
.range([0, radius]);


//////////// Create the container SVG and g /////////////

var svg = d3.select(id).append("svg") //Initiate the radar chart SVG
.attr("width", cfg.w + cfg.margin.left + cfg.margin.right)
.attr("height", cfg.h + cfg.margin.top + cfg.margin.bottom)
.attr("class", "radar"+id);
var g = svg.append("g") //Append a g element
.attr("transform", "translate(" + (cfg.w/2 + cfg.margin.left) + "," + (cfg.h/2 + cfg.margin.top) + ")");



/////////////////////////////////////////////////////////
///////////// Draw the radar chart blobs ////////////////
/////////////////////////////////////////////////////////

//The radial line function
var radarLine = d3.svg.line.radial()
.interpolate("cardinal-closed")
.radius(function(d) { return rScale(d.value); })
.angle(function(d,i) { return i*angleSlice; });


//Create a wrapper for the blobs
var blobWrapper = g.selectAll(".radarWrapper")
.data(data)
.enter().append("g")
.attr("class", "radarWrapper");

//Append the backgrounds
blobWrapper
.append("path")
.attr("class", "radarArea")
.attr("d", function(d,i) { return radarLine(d); })
.style("fill", function(d,i) { return cfg.color(i);})
.style("fill-opacity", cfg.opacityArea);


}//RadarChart function
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<!-- Radar Chart -->
<div class="radar-chart" id="radarChart1"></div>

我发现在 HTML5-Canvas 中重叠元素可以变得透明 (1)。它还可用于将 d3 节点绑定(bind)到它 (2),并且它们可以通过这种方式变得透明。然而,对于像上面的雷达图 Blob 这样更复杂的对象来说,这似乎非常复杂。在 d3 中是否有一个简单的解决方案可以做到这一点? (chart.js(3)里好像有)

附录 - 我已经发现的内容:

  1. 通过将 globalCompositeOperation 模式设置为 'xor',可以使用 HTML5-Canvas 使重叠(非 d3)元素变得透明:

For more about compositing visit https://www.sarasoueidan.com/blog/compositing-and-blending-in-css/

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.globalCompositeOperation = 'xor';

// WITHOUT overlap:
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);

ctx.fillStyle = 'red';
ctx.fillRect(110, 50, 100, 100);

// WITH (transparent) overlap:
ctx.fillStyle = 'blue';
ctx.fillRect(250, 10, 100, 100);

ctx.fillStyle = 'red';
ctx.fillRect(300, 50, 100, 100);
<!-- Original from https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation -->

<style>
body {
background-image: url("http://www.scri8e.com/stars/PNG_Clouds/zc06.png?filename=./zc06.png");
}
</style>

<canvas id="canvas" width="400" height="200" ></canvas>

  • d3.js 节点也可以通过 HTML5-Canvas 使用 getContext("2d") 进行可视化。重叠的实现方式与上面(1)相同。然而,据我了解,这需要重新创建 Javascript 中的每个元素,然后在其上绑定(bind) d3 数据。例如,对于圆形,必须在 HTML5-Canvas 上下文中重新创建弧形元素,如 this example by Mike Bostock 所示。 :

    context = canvas.getContext("2d"); ...

    context.arc(element.getAttribute("x"), element.getAttribute("y"), element.getAttribute("radius"), 0, 2 * Math.PI);
  • 这是 chartjs 中可能的实现(见下图)

  • enter image description here

    最佳答案

    您的描述意味着您将始终有两个图表(“之前 -> 之后”)。

    此解决方案使用 SVG 蒙版。虽然使用更多图表是可行的,但它会变得更加复杂。您必须构建 <mask>动态元素。

    /* Original radar chart design created by Nadieh Bremer - VisualCinnamon.com */

    ////////////////////////// Data //////////////////////////////

    var data = [
    [//Before - red
    {axis:"First",value:0.49},
    {axis:"Banana",value:0.79},
    {axis:"Scratch",value:0.70},
    {axis:"Wheelie",value:0.09},
    {axis:"Pantalon",value:0.37},
    ],[//After - green
    {axis:"First",value:0.64},
    {axis:"Banana",value:0.44},
    {axis:"Scratch",value:0.37},
    {axis:"Wheelie",value:0.84},
    {axis:"Pantalon",value:0.81},
    ]
    ];

    //////////////////////// Setup ////////////////////////////////

    var margin = {top: 50, right: 50, bottom: 50, left: 50},
    width = 300,
    height = 300;
    var color = d3.scale.ordinal().range(["#CC333F","#53e87d"]);
    var radarChartOptions = {
    w: width, //Width of the circle
    h: height, //Height of the circle
    margin: margin, //The margins of the SVG
    opacityArea: 0.7, //The opacity of the area of the blob
    color: color //Color function
    };

    //////////////////////// RadarChart ///////////////////////////

    RadarChart("radarChart", data, radarChartOptions);

    function RadarChart(id, data, options) {

    var cfg = radarChartOptions;
    var allAxis = (data[0].map(function(i, j){return i.axis})), //Names of each axis
    total = allAxis.length, //The number of different axes
    radius = Math.min(cfg.w/2, cfg.h/2), //Radius of the outermost circle
    Format = d3.format('%'), //Percentage formatting
    angleSlice = Math.PI * 2 / total; //The width in radians of each "slice"
    var rScale = d3.scale.linear() //Scale for the radius
    .range([0, radius]);

    var svg = d3.select('#' + id) //Initiate the radar chart SVG
    .attr("width", cfg.w + cfg.margin.left + cfg.margin.right)
    .attr("height", cfg.h + cfg.margin.top + cfg.margin.bottom)
    .attr("class", "radar"+id);

    svg.select('#bg').attr('r', radius);

    var dx = cfg.w/2 + cfg.margin.left,
    dy = cfg.h/2 + cfg.margin.top;

    svg.selectAll('mask')
    .attr('x', -dx)
    .attr('y', -dy);

    var source = svg.select('#radarSource')
    var wrapper = svg.select('#radarWrapper')
    .attr("transform", "translate(" + dx + "," + dy + ")");

    //The radial line function
    var radarLine = d3.svg.line.radial()
    .interpolate("cardinal-closed")
    .radius(function(d) { return rScale(d.value); })
    .angle(function(d,i) { return i*angleSlice; });


    //Draw the blobs
    source.selectAll("path")
    .data(data)
    .enter().append("path")
    .attr("id", function(d,i) {return 'area' + i;})
    .attr("d", function(d,i) { return radarLine(d); });

    //render and apply masks
    wrapper.selectAll("use")
    .data(data)
    .enter().append("use")
    .attr("xlink:href", function(d,i) {return '#area' + i;})
    .attr("mask", function(d,i) {return 'url(#mask' + i + ')';})
    .style("fill", function(d,i) { return cfg.color(i);})
    .style("fill-opacity", cfg.opacityArea);


    }//RadarChart function
    <script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
    <!-- Radar Chart -->
    <svg id="radarChart" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
    <circle id="bg" />
    <g id="radarSource" />
    <mask id="mask0" maskUnits="userSpaceOnUse">
    <use xlink:href="#bg" fill="white" />
    <use xlink:href="#area1" fill="black" />
    </mask>
    <mask id="mask1" maskUnits="userSpaceOnUse">
    <use xlink:href="#bg" fill="white" />
    <use xlink:href="#area0" fill="black" />
    </mask>
    </defs>
    <g id="radarWrapper" />
    </svg>

    关于javascript - 使重叠的 d3.js 雷达图元素透明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45437080/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com