Endless panning canvas

by John kuoppala

HTML

<canvas id="canvas"></canvas>

CSS

canvas {
    border: 1px solid black;
}

JavaScript

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");

c.height = 300;
c.width = 500;

var offSetX = 0;
var offSetY = 0;
var movingLeft = false;
var movingRight = false;
var movingDown = false;
var movingUp = false;   

//Mouse event to see what is going on.
c.addEventListener("mousemove",move);

function move(event) {
    event = event || window.event;
    x = event.pageX - c.offsetLeft,
    y = event.pageY - c.offsetTop;        
    movingLeft = false;
    movingRight = false;
    movingDown = false;
    movingUp = false; 
    if (x>c.width-50) {
        movingLeft = true;
    }
    if (x<50) {
        movingRight = true;   
    }
    if (y<50) {
        movingUp = true;   
    }
    if (y>c.height-50) {
        movingDown = true;   
    }
}

function updateDraw() {
    ctx.clearRect(0,0,c.width,c.height);
    ctx.beginPath();
    ctx.moveTo(c.width/2-10,0);
    ctx.lineTo(c.width/2+10,0);
    ctx.lineTo(c.width/2,10);
    ctx.closePath();
    ctx.stroke();
    ctx.textAlign="center";
    ctx.fillText(c.width/2+offSetX,c.width/2,20);

    ctx.moveTo(0,c.height/2-10);
    ctx.lineTo(0,c.height/2+10);
    ctx.lineTo(10,c.height/2);
    ctx.closePath();
    ctx.stroke();
    ctx.textAlign="center";
    ctx.fillText(c.height/2+offSetY,20,c.height/2+3);
    
    ctx.beginPath();
    ctx.arc(c.width/2+offSetX,c.height/2+offSetY,30,0,2*Math.PI);
    ctx.closePath();
    ctx.fill();
    
    
    if (movingLeft) {offSetX++;}
    if (movingRight) {offSetX--;}
    if (movingDown) {offSetY++;}
    if (movingUp) {offSetY--;}
    
    
    requestAnimationFrame(updateDraw);
}

//Starting the whole thing
updateDraw();