2012-06-12 43 views
5

我正在构建一个帆布游戏。在这我想要在循环中滑动背景图像。我不知道如何使用JavaScript来做到这一点。我将使用单个图像,这个图像会连续滑动到背景中。 在此先感谢。在html5画布中滚动/滑动背景

+0

我不知道你能不断地滑动一个形象 - 你可以滑动两半,其在边缘无缝地加入。 – Widor

+0

@Coulton theres没有任何理由使用jQuery,它不对canvas进行任何操作。 – Loktar

+0

@Widor您绝对可以使用一张图片,只需将其中的部分复制到画布上即可创建无缝效果。 – Loktar

回答

11

Theres通过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); 
} 
+0

嗨Loktar,谢谢你的回答。你能告诉我如何扭转方向(从右到左)。我尝试过但没有成功。 – rgolekar

+1

@ user1451031我编辑了我的答案,并将其添加到第二个方法中,//在第二个方法中执行得更好。 – Loktar

+1

@ Loktar非常感谢。你救了我一天:) – rgolekar