【发布时间】:2020-12-29 09:17:30
【问题描述】:
我有一个项目需要重新创建某个圆环图。该图表由蓝色部分组成,悬停时需要弹出并更改颜色。我在网上找到了一些关于如何重新创建此动画的文档:documentation。
问题是我试图在我的 Vue 组件中实现这个解决方案,但是当我在图表内外徘徊时它不断抛出错误。
当我将鼠标悬停在图表中时,出现以下错误:Cannot read property 'startAngle' of undefined 在以下行:path.transition().attr("d", d3.arc().innerRadius(radius * 0.7).outerRadius(radius * 1.08));。我似乎无法理解为什么会发生此错误,因为我没有使用 startAngle 函数。
当我将鼠标移出图表时,我在if (!thisPath.classed("clicked")) { 线上也收到以下错误node.getAttribute is not a function。
这是我第一次使用 D3.JS,我仍在尝试了解有关该库的很多信息。我喜欢你可以创建多少不同的图表
这是我的组件的完整代码:
<template>
<div class="p-3 flex flex-col items-center h-full">
<div class="w-full flex-1 h-full">
<div ref="chart" class="flex justify-center h-full"></div>
</div>
</div>
</template>
<script>
import * as d3 from "d3";
export default {
name: "DoughnutChartItem",
props: {
data: {
type: Array,
required: true
},
height: {
type: Number,
required: true
},
width: {
type: Number,
required: true
}
},
mounted() {
// // set the dimensions and margins of the graph
// var width = 450;
// var height = 450;
var margin = 50;
// The radius of the pieplot is half the width or half the height (smallest one). I subtract a bit of margin.
var radius = Math.min(this.width, this.height) / 2 - margin;
// append the svg object to the div called 'chart'
var svg = d3
.select(this.$refs["chart"])
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.attr("viewBox", `0 0 ${this.width} ${this.height}`)
.append("g")
.attr(
"transform",
"translate(" + this.width / 2 + "," + this.height / 2 + ")"
);
// // Create dummy data
// var data = { a: 9, b: 20, c: 30, d: 8, e: 12 };
// set the color scale
var color = d3
.scaleOrdinal()
.domain(Object.keys(this.data))
.range(["#206BF3"]);
// Compute the position of each group on the pie:
var pie = d3.pie().value(function(d) {
return d[1];
});
var data_ready = pie(Object.entries(this.data));
// Build the pie chart: Basically, each part of the pie is a path that we build using the arc function.
svg
.selectAll("whatever")
.data(data_ready)
.enter()
.append("path")
.attr(
"d",
d3
.arc()
.innerRadius(100) // This is the size of the donut hole
.outerRadius(radius)
)
.attr("fill", function(d) {
return color(d.data[0]);
})
.attr("stroke", "black")
.style("stroke-width", "2px")
.style("opacity", 0.7);
svg.on("mouseover", () => {
this.pathAnim(radius, d3.select(this), 1);
});
svg.on("mouseout", () => {
var thisPath = d3.select(this);
if (!thisPath.classed("clicked")) {
this.pathAnim(radius, thisPath, 0);
}
});
},
methods: {
pathAnim(radius, path, dir) {
switch (dir) {
case 0:
path
.transition()
.duration(500)
.ease("bounce")
.attr(
"d",
d3
.arc()
.innerRadius(radius * 0.7)
.outerRadius(radius)
);
break;
case 1:
console.log(
path.transition().attr(
"d",
d3
.arc()
.innerRadius(radius * 0.7)
.outerRadius(radius * 1.08)
)
);
// path.transition().attr(
// "d",
// d3
// .arc()
// .innerRadius(radius * 0.7)
// .outerRadius(radius * 1.08)
// );
break;
}
}
}
};
</script>
</script>
【问题讨论】:
标签: javascript vue.js animation d3.js charts