Skip to content

Instantly share code, notes, and snippets.

@zawarudo
Last active December 25, 2015 09:29
Show Gist options
  • Save zawarudo/6953976 to your computer and use it in GitHub Desktop.
Save zawarudo/6953976 to your computer and use it in GitHub Desktop.
D3 ping effect on mouseover.
<html>
<head>
<script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<div id="chart">
</div>
<script type="text/javascript">
var margin = {top: 50, right: 50, bottom: 50, left: 50},
w = 960 - margin.left - margin.right,
h = 500 - margin.top - margin.bottom,
//Circle Settings
influence = 70,//Ring of influence size
r = 10,
color = '#CC6600',
//Ping Animation Variables
interval = 2000, //2 seconds
pingSet = false;//Flag for preventing multiple ping effects
//Generate Dataset
var vertices = d3.range(30).map(function(d) {
return [Math.random() * w, Math.random() * h, Math.random() * influence];
});
var svg = d3.select("#chart")
.append("svg:svg")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom);
var points = svg.append("svg:g").attr("id", "points");
//Our pinging circle
var hoverpoint = svg.append("svg:g")
.append("svg:circle")
.style("fill","none")
.style("stroke-width", "3px");
//Plot Points
points.selectAll("circle")
.data(vertices)
.enter().append("svg:circle")
.attr("id", function(d, i) {
return "point-"+i; })
.attr("cx", function(d) {
return d[0]; })
.attr("cy", function(d) {
return d[1]; })
.attr("influence", function(d){
return d[2]; })
.attr("fill", color)
.attr("r", r)
.on('mouseover', function(){
//Set hover circle on top of current point position
hoverpoint
.attr("cx" , this.getAttribute("cx"))
.attr("cy" , this.getAttribute("cy"))
.attr("influence", this.getAttribute("influence"));
//Animate Ping
if(!pingSet) {//Preventing multiple ping effects
pingSet = true;
d3.timer(ping(),interval);
}
} )
.on('mouseout', function(){
pingSet = false;
});
var ping = function() {
return function() {
if(pingSet){
//Check to make sure we aren't pinging backwards
var influence = hoverpoint.attr('influence');
var radius = ( r > influence ? 0 : r);
hoverpoint
.attr("stroke", "#FF0000")//Red
.attr("r", r)
.attr("stroke-width", "15px")
.transition() //Trigger Animation
.attr("stroke-width", "3px")
.attr("r", influence)
.attr("stroke", "#FFFAFA")//Light Red
.duration(interval);
//callback
d3.timer(ping(hoverpoint),interval);
return true;
}
}
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment