d3中元素拖拽drag实例

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

                       

参考链接:http://blog.csdn.net/lzhlzz/article/details/42200579
https://github.com/d3/d3-3.x-api-reference/blob/master/Drag-Behavior.md

使用拖拽功能我们可以快速将图标展示成我们需要的样子。

d3.behavior.drag()用来构造一个拖拽行为。如果让元素响应这个行为需要使用call()函数,例如selection.call(drag)

使用drag.on()函数来监听一个事件,函数语法为drag.on(type [, listener]) type表示时间类型,除了drag 还有 dragstartdragend

drag.origin()定义拖拽的原点,默认原点为鼠标点击的位置,这也会造成元素跳动。指定的原点访问器必须返回一个包含被拖动元素开始坐标xy的对象

下面就是一个拖拽元素的实例:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <script src="../d3.v3.js"></script></head><body>    <script>    var width = "100%",        height = 300;    var circles = [{        cx: 150,        cy: 200,        r: 40    }, {        cx: 250,        cy: 200,        r: 40    }];    //添加画布并设置画布大小    var svg = d3.select("body").append("svg")        .attr("width", width)        .attr("height", height)    var drag = d3.behavior.drag()        //定义了元素拖拽行为的原点,设置为圆的圆心位置可以避免明显的元素跳动,第一个参考连接中的例子可以看到明显的跳动        .origin(function() {            var t = d3.select(this);            return {                x: t.attr("cx"),                y: t.attr("cy")            };        })        .on("drag", dragmove);    svg.selectAll("circle")        .data(circles)        .enter()        .append("circle")        .attr("cx", function(d, i) {            return d.cx;        })        .attr("cy", function(d, i) {            return d.cy;        })        .attr("r", function(d, i) {            return d.r;        })        .attr("fill", "lime")        .attr("stroke", "white")        //为元素添加拖拽事件        .call(drag);    //定义拖拽行为,此处为重新设置元素圆心位置    function dragmove(d) {        d3.select(this)            .attr("cx", function() {                return d.cx = d3.event.x            })            .attr("cy", d.cy = d3.event.y)    }    </script></body></html>
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

演示地址:http://justforuse.cn/d3/d3.drag/

扫描二维码关注公众号,回复: 5000389 查看本文章
           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_43682817/article/details/84106936
D3
今日推荐