<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdn.bootcss.com/d3-tip/0.9.1/d3-tip.js"></script>
const svg = d3.select('body').append('svg')
.attr('width', 500)
.attr('height', 500);
let dataSymbol = [d3.symbolCircle, d3.symbolCross, d3.symbolDiamond, d3.symbolSquare,
d3.symbolStar, d3.symbolTriangle, d3.symbolWye];
let color = d3.scaleOrdinal(d3.schemeCategory10);
const symbol = d3.symbol().size(500).type(d => d);
let tip = d3.tip() // 设置tip
.attr('class', 'd3-tip')
.offset([-10, 0])
.html(function (d, i) {
return "<strong>颜色" + color(i) + "<br></strong> <span style='color:#ffeb3b'>" + color(i) + "</span>";
});
svg.call(tip);
svg.append('g')
.attr('transform','translate(100, 100)')
.selectAll('path').data(dataSymbol).enter().append('path')
.attr('d', d => symbol(d))
.attr('stroke', 'black')
.attr('stroke-width', 5)
.attr('transform', (d,i) => 'translate('+ i * 60+','+ 200 +')')
.attr('fill', (d,i) => color(i))
.on('mouseover', function () {
let args = Array.prototype.slice.call(arguments);
d3.select(this).attr('fill', 'red');
tip.show.apply(this, [...args]); //.on('mouseover',tip.show) 没有其他事件程序时这样写,tip.show函数的this值为发生鼠标移入事件的元素。如果事件程序多,写在一个function中时,需要将tip.show的this值指定为同样的元素,即事件函数的this,并将参数传入
})
.on('mouseout', function (a,b,c) {
d3.select(this).attr('fill', color(b)).selectAll('text').remove();
tip.hide();
})