HTML5 Panning based on Mouse Movement

后端 未结 2 2073
陌清茗
陌清茗 2020-12-19 06:18

I\'m trying to implement functionality to \"pan\" inside a canvas in HTML5 and I am unsure about the best way to go about accomplishing it.

Currently - I am trying t

2条回答
  •  感动是毒
    2020-12-19 06:52

    pimvdb's fiddle shows the concept nicely but doesn't actually work, at least not for me.

    Here's a fixed version: http://jsfiddle.net/VWn6t/173/
    The meat of it is basically the same.

    var startCoords = {x: 0, y: 0};
    var last = {x: 0, y: 0};
    var isDown = false;
    
    canvas.onmousemove = function (e) {
        if(isDown) {
            ctx.setTransform(1, 0, 0, 1,
                             xVal - startCoords.x,
                             yVal - startCoords.y);
        }
    };
    
    canvas.onmousedown = function (e) {
        isDown = true;
        startCoords = {x: e.pageX - this.offsetLeft - last.x,
                       y: e.pageY - this.offsetTop - last.y};
    };
    
    canvas.onmouseup   = function (e) {
        isDown = false;
        last = {x: e.pageX - this.offsetLeft - startCoords.x,
                y: e.pageY - this.offsetTop - startCoords.y};
    };
    

提交回复
热议问题