在html5画布中滚动/滑动背景

时间:2012-06-12 11:04:09

标签: html5 canvas background

我正在构建一个画布游戏。在这里我想在循环中滑动背景图像。我不知道如何使用javascript做到这一点。我将使用单个图像,它将连续滑入背景。 提前谢谢。

1 个答案:

答案 0 :(得分:11)

有几种方法可以实现这一点,第一种方法会使用putImageData获得性能提升,第二种方法只使用drawImage。另请注意,第二种方法的代码是从左到右,或从右到左。

http://www.somethinghitme.com/projects/bgscroll/

var ctx = document.getElementById("canvas").getContext("2d"),
    canvasTemp = document.createElement("canvas"),
    scrollImg = new Image(),
    tempContext = canvasTemp.getContext("2d"),
    imgWidth = 0,
    imgHeight =0,
    imageData = {},
    canvasWidth = 600,
    canvasHeight = 240,
    scrollVal = 0,
    speed =2;

    scrollImg.src = "citybg.png";
    scrollImg.onload = loadImage;

    function loadImage(){
        imgWidth = scrollImg.width,
        imgHeight = scrollImg.height;
        canvasTemp.width = imgWidth;
        canvasTemp.height =  imgHeight;    
        tempContext.drawImage(scrollImg, 0,0, imgWidth, imgHeight); 
        imageData = tempContext.getImageData(0,0,imgWidth,imgHeight);
        render();                
    }

    function render(){
        ctx.clearRect(0,0,canvasWidth,canvasHeight);

        if(scrollVal >= canvasWidth-speed){
            scrollVal = 0;
        }

        scrollVal+=speed;

        // This is the bread and butter, you have to make sure the imagedata isnt larger than the canvas your putting image data to.
        imageData = tempContext.getImageData(canvasWidth-scrollVal,0,scrollVal,canvasHeight);
        ctx.putImageData(imageData, 0,0,0,0,scrollVal, imgHeight);
        imageData = tempContext.getImageData(0,0,canvasWidth-scrollVal,canvasHeight);
        ctx.putImageData(imageData, scrollVal,0,0,0,canvasWidth-scrollVal, imgHeight);

        setTimeout(function(){render();},10);
    }

第二种方法使用与上面相同的代码,只需将这两个功能更改为以下内容即可。

http://www.somethinghitme.com/projects/bgscroll/scrolldrawimage.html

function loadImage(){
    imgWidth = scrollImg.width,
    imgHeight = scrollImg.height;
    canvasTemp.width = imgWidth;
    canvasTemp.height =  imgHeight;    
    render();                
}

function render(){
    ctx.clearRect(0,0,canvasWidth,canvasHeight);

    if(scrollVal >= canvasWidth){
        scrollVal = 0;
    }

    scrollVal+=speed;                   
    ctx.drawImage(scrollImg,canvasWidth-scrollVal,0,scrollVal,imgHeight, 0, 0, scrollVal,imgHeight);
    ctx.drawImage(scrollImg,scrollVal,0,imgWidth, imgHeight);

     // To go the other way instead
     ctx.drawImage(scrollImg,-scrollVal,0,imgWidth, imgHeight);
     ctx.drawImage(scrollImg,canvasWidth-scrollVal,0,imgWidth, imgHeight);

    setTimeout(function(){render();},10);
}