canvas矩形拖拽效果

2018-7-9 13:44| 作者: admin| 查看: 473| 评论: 0|来自: 蚂蚁部落

本章节分享一下使用canvas实现的拖拽效果。

代码实例如下:

[HTML] 纯文本查看 复制代码运行代码
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>蚂蚁部落</title>
<script>
window.onload = function() {
  var can = document.getElementById('box'),
    gd = can.getContext('2d'),
    x = 0,
    y = 0,
    w = 100,
    h = 100;
  gd.fillStyle = 'red';
  gd.fillRect(x, y, w, h);
  can.onmousedown = function(ev) {
    var ev = ev || window.event;
    var downx = ev.clientX;
    var downy = ev.clientY;
    if (downx > x && downy < x + w && downy > y && downy < y + h) {
      var disx = downx - x;
      var disy = downy - y;
      can.onmousemove = function(ev) {
        var ev = ev || window.event;
        x = ev.clientX - disx;
        y = ev.clientY - disy;
        gd.clearRect(0, 0, can.width, can.height);
        gd.fillRect(x, y, w, h);
      }
 
      can.onmouseup = function() {
        can.onmousemove = null;
        can.onmouseup = null;
      }
      return false;
    }
  }
}
</script>
</head>
<body>
<canvas id="box" width="800" height="800"></canvas>
</body>
</html>

鲜花

握手

雷人

路过

鸡蛋

最新评论

返回顶部