canvas矩形拖拽效果

快乐打工仔 分类:实例代码

canvas矩形拖拽效果属于前端实例代码,有关更多实例代码大家可以查看

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

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>

canvas矩形拖拽效果,这样的场景在实际项目中还是用的比较多的,关于canvas矩形拖拽效果就介绍到这了。

回复

我来回复
  • 暂无回复内容