我正在構建一個帆布遊戲。在這我想要在循環中滑動背景圖像。我不知道如何使用JavaScript來做到這一點。我將使用單個圖像,這個圖像會連續滑動到背景中。 在此先感謝。在html5畫布中滾動/滑動背景
5
A
回答
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);
}
相關問題
- 1. 滾動畫布中的巨大背景
- 2. html5畫布滾動
- 3. HTML5畫布上移動TiledMap類背景
- 4. HTML5旋轉/動畫背景
- 5. HTML5無盡背景動畫
- 6. 平滑的endles用畫布滾動背景?
- 7. HTML5畫布作爲背景
- 8. HTML5畫布背景圖片
- 9. jquery和滑動/動畫背景
- 10. 彈出式背景ListView滑動動畫
- 11. 背景滾動佈局
- 12. HTML5和畫布:隨着玩家的移動而移動背景
- 13. HTML5畫布 - 製作帶落金片的動畫背景
- 14. 滑出滾動佈局動畫android
- 15. 列表滾動動畫背景
- 16. CSS背景圖像滾動動畫
- 17. 滑動背景
- 18. 在html5畫布上自定義滾動
- 19. 在畫布上水平滾動。 HTML5
- 20. Android:滾動畫廊中的背景
- 21. Html5 for mobile - 滑動滾動
- 22. 動態HTML5畫布動畫
- 23. Html5畫布動畫
- 24. HTML5背景動畫onScroll,最佳實踐
- 25. 帶畫布的動畫背景
- 26. 使用畫布動畫作爲背景
- 27. 動畫GIF在HTML5畫布
- 28. 多個背景與平滑滾動
- 29. 平滑漸變背景動畫java
- 30. 滾動背景
我不知道你能不斷地滑動一個形象 - 你可以滑動兩半,其在邊緣無縫地加入。 – Widor
@Coulton theres沒有任何理由使用jQuery,它不對canvas進行任何操作。 – Loktar
@Widor您絕對可以使用一張圖片,只需將其中的部分複製到畫布上即可創建無縫效果。 – Loktar