Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a html canvas "scroll" indefinitely?

I have a canvas element that automatically fills the entire browser window of the client when loaded. On it you can draw with the mouse, like in the result of any "make a drawing board"-tutorial out there. What I want to do however is to make it so that if you move the mouse to any extreme of the canvas (or maybe select a certain "move"-tool, you can drag the canvas in any direction you'd like), it scrolls. In particular, I want it to be possible to in theory scroll forever, so I can't really pre-generate, I have to generate "more canvas" on the fly. Does any one have any idea on how to do this?

If it helps, this is the client-side javascript right now: (the html is just a canvas-tag)

$(document).ready(function() {
    init();
});

function init() {
    var canvas = document.getElementById('canvas')
      , ctx = canvas.getContext('2d')
      , width = window.innerWidth
      , height = window.innerHeight;

    // Sets the canvas size to be the same as the browser size
    canvas.width = width;
    canvas.height = height;

    // Binds mouse and touch events to functions
    $(canvas).bind({
        'mousedown':  startDraw,
        'mousemove':  draw,
        'mouseup':    stopDraw,
    });
};

// Triggered on mousedown, sets draw to true and updates X, Y values.
function startDraw(e) {
    this.draw = true;
    this.X = e.pageX;
    this.Y = e.pageY;
};

// Triggered on mousemove, strokes a line between this.X/Y and e.pageX/Y
function draw(e) {
    if(this.draw) {
        with(ctx) {
            beginPath();
            lineWidth = 4;
            lineCap = 'round';
            moveTo(this.X, this.Y);
            lineTo(e.pageX, e.pageY);
            stroke();
        }
        this.X = e.pageX;
        this.Y = e.pageY;
    }
};

// Triggered on mouseup, sets draw to false
function stopDraw() {
    this.draw = false;
};
like image 627
mag Avatar asked Mar 28 '11 23:03

mag


1 Answers

The canvas element uses real memory of your computer, so there is no infinite canvas which scrolls forever. But, you may simulate this behavior using a virtual canvas. Just record the xy coords captured by draw() into an array and calculate a new center of the virtual canvas if the mouse touches the border. Then filter out the xy coords which fit into center +- screen size and draw them.

However, the array recording the xy coords can not grow infinitely and the filter code will get slower over the size of the array. Are 10,000 points enough?

More optimized code will turn the mouse coords into splines and saves only points needed to redraw the (smoothed) path of the mouse.

like image 96
Torsten Becker Avatar answered Nov 11 '22 08:11

Torsten Becker