Make a bitmap wrap around the canvas for infinite scrolling

前端 未结 3 637
北恋
北恋 2020-12-12 02:56

I am looking for a way to wrap a bitmap image around the canvas, for an infinite scrolling effect. I\'m looking at EaselJS but clean javascript code will also suffice.

3条回答
  •  有刺的猬
    2020-12-12 03:13

    You can achieve this quite easily with the html5 canvas.
    Look at the drawImage specification here :
    http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#drawing-images

    drawImage comes in 3 flavors, the first being a simple copy of the image, the second allowing to scale the image, and the third is the one you seek, it allows to perform clipping in a single call.

    What you have to do :
    - have a counter that will move from zero to the width of your image, then loop to zero again.
    - each frame, draw the maximum of the image that you can on the canvas.
    - If there is still some part of the canvas not drawn, draw again the image starting from zero to fill the canvas.

    i made a fiddle, the only part that matters is in the animate function (other things are tools i often use in my fiddles).
    (Rq : I assumed in this example that two images would be enough to fill the canvas.)

    http://jsfiddle.net/gamealchemist/5VJhp/

    var startx = Math.round(startPos);
    var clippedWidth = Math.min(landscape.width - startx, canvasWidth);
    
    // fill left part of canvas with (clipped) image.
    ctx.drawImage(landscape, startx, 0, clippedWidth, landscape.height,
    0, 0, clippedWidth, landscape.height);
    
    if (clippedWidth < canvasWidth) {
        // if we do not fill the canvas
        var remaining = canvasWidth - clippedWidth;
        ctx.drawImage(landscape, 0, 0, remaining, landscape.height,
        clippedWidth, 0, remaining, landscape.height);
    }
    // have the start position move and loop
    startPos += dt * rotSpeed;
    startPos %= landscape.width;
    

提交回复
热议问题