2012-06-12 45 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