D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
benkimball
Full window
Github gist
Circle dragging with snap-to-edge
<!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title>Docking Bubbles</title> <style type="text/css" media="screen"> .bubble { stroke: steelblue; stroke-width: 1; fill: rgba(120, 40, 255, 0.3); } </style> </head> <body> <svg width="960" height="500"></svg> <script src="https://d3js.org/d3.v4.min.js"></script> <script type="text/javascript"> var words = ["Hello", "I", "am", "a", "docking", "bubble"]; var svg = d3.select("svg"), width = +svg.attr('width'), height = +svg.attr('height'), radius = 80; var bubbles = d3.range(6).map(function(obj, ix) { return { text: words[ix], x: Math.round(Math.random() * (width - radius * 2) + radius), y: Math.round(Math.random() * (height - radius * 2) + radius) }; }); var bubble = svg.selectAll('.bubble') .data(bubbles) .enter().append('circle') .attr('class', 'bubble') .attr('cx', function(d) { return d.x; }) .attr('cy', function(d) { return d.y; }) .attr('r', radius) .call(d3.drag() .on('drag', dragged)); function dragged(d) { var dest = {x: d3.event.x, y: d3.event.y}; if(dest.x <= radius) { dest.x = 0 }; // lock to left edge if(dest.x >= width - radius) { dest.x = width; } // lock to right edge if(dest.y <= radius) { dest.y = 0; }; // lock to top edge if(dest.y >= height - radius) { dest.y = height; } // lock to bottom edge d3.select(this).attr('cx', d.x = dest.x).attr('cy', d.y = dest.y); } </script> </body> </html>
https://d3js.org/d3.v4.min.js