Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - HTML5 Panning based on Mouse Movement

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 to detect where the mouse is on the canvas, and if it is within 10% of an edge, it will move in that direction, as shown:

Current Edge Detection:

canvas.onmousemove = function(e)
{
    var x = e.offsetX;
    var y = e.offsetY;
    var cx = canvas.width;
    var cy = canvas.height;
    if(x <= 0.1*cx && y <= 0.1*cy)
    {
         alert("Upper Left"); 
         //Move "viewport" to up and left (if possible)
    }
    //Additional Checks for location
}

I know I could probably accomplish this by creating paths within the canvas and attaching events to them, but I haven't worked with them much, so I thought I would ask here. Also - if a "wrapping" pan would be possible that would be awesome (panning to the left will eventually get to the right).

Summary: I am wondering what the best route is to accomplish "panning" is within the HTML5 Canvas. This won't be using images but actual drawn objects (if that makes any difference). I'll be glad to answer any questions if I can.

Demo:

Demo

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It depends on how you want panning with mouse movement to be implemented, but today it's often 'realtime' panning in that you can drag around. I tried to update your fiddle a little: http://jsfiddle.net/pimvdb/VWn6t/3/.

var isDown = false; // whether mouse is pressed
var startCoords = []; // 'grab' coordinates when pressing mouse
var last = [0, 0]; // previous coordinates of mouse release

canvas.onmousedown = function(e) {
    isDown = true;

    startCoords = [
        e.offsetX - last[0], // set start coordinates
        e.offsetY - last[1]
   ];
};

canvas.onmouseup   = function(e) {
    isDown = false;

    last = [
        e.offsetX - startCoords[0], // set last coordinates
        e.offsetY - startCoords[1]
    ];
};

canvas.onmousemove = function(e)
{
    if(!isDown) return; // don't pan if mouse is not pressed

    var x = e.offsetX;
    var y = e.offsetY;

    // set the canvas' transformation matrix by setting the amount of movement:
    // 1  0  dx
    // 0  1  dy
    // 0  0  1

    ctx.setTransform(1, 0, 0, 1,
                     x - startCoords[0], y - startCoords[1]);

    render(); // render to show changes

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...