canvas画布实现拖拽操作

想请问一下,在画布上画出了一个网络图由点和线构成,那么改如何拖动这个画布改变位置呢?能不能在canvas这个标签上绑定事件?

我写了个demo,你看看。

<body style="position: relative;">
    <canvas id="myCanvas" 
        width="200" 
        height="100" 
        style="border:1px solid #c3c3c3;position:absolute;top:50px;left: 50px;">
        Your browser does not support the canvas element.
    </canvas>
<script>
    var c = document.getElementById("myCanvas");
    var cxt = c.getContext("2d");
    cxt.moveTo(10,10);
    cxt.lineTo(150,50);
    cxt.lineTo(10,50);
    cxt.stroke();
    c.onmousedown = function(args){
        var evt = args || event;
        var StartX = evt.clientX;
        var StartY = evt.clientY;
        document.onmousemove = function(ev){   
            var iEvent = ev||event; 
            let left = iEvent.clientX - StartX;
            let top = iEvent.clientY - StartY;
            c.style.left = left + 50 + 'px';
            c.style.top = top + 50 +'px';
        }
        document.onmouseup = function(){  
            document.onmousedown = null;  
            document.onmousemove = null;  
        };  
        return false;  
    }
</script>
</body>
<canvas id="myCanvas" 
        width="200" 
        height="100" 
        style="border:1px solid #c3c3c3;position:absolute;top:50px;left: 50px;">
        Your browser does not support the canvas element.
</canvas>

<script>
    var myCanvas = document.getElementById("myCanvas");
    var cxt = myCanvas.getContext("2d");
    cxt.moveTo(10,10);
    cxt.lineTo(150,50);
    cxt.lineTo(10,50);
    cxt.stroke();
    myCanvas.onmousedown = function(args){
        var evt = args || event;
        var offsetX = evt.clientX - myCanvas.offsetLeft;//鼠标按下的瞬间相对于myCanvas元素的位置(x)
        var offsetY = evt.clientY - myCanvas.offsetTop;
        document.onmousemove = function(ev){   
            var iEvent = ev ||event; 
            myCanvas.style.left = iEvent.clientX - offsetX + 'px';
            myCanvas.style.top = iEvent.clientY - offsetY + 'px';
        }
    }
    document.onmouseup = function(){  
        document.onmousedown = null;  
        document.onmousemove = null;  
    };  
</script>

 

一楼这个是触边问题,触边后松开鼠标,还是能拖动;二楼这个是拖动整个画布,而不是画布中的某一个图形