我試圖將一堆圖像加載到畫布上,但不是它們出現。源代碼包含我想要使用的圖像的鏈接。有人有主意嗎?Javascript(帆布) - for循環和drawImage不一起工作
這是我第一次使用畫布。
<canvas id ="canvas" width = "500" height = "500"></canvas>
<script>
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
loadImages(ctx);
function loadImages()
{
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var number = 0;
var bX = 0;
var bY = 0;
var images = [];
images = getImages();
for(var i = 0;i<images.length;i++){
var t = images[i];
document.write(t.src+"<br>");
ctx.drawImage(t,0,0,100,100);
if(i%4==0)
{
bX = 0;
bY -= 110;
}
else
{
bX+=110;
}
}
}
我做了這個功能,預載的圖片,並在陣列
function getImages()
{
var imgList = [];
var sources =
[ "http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_00.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_01.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_02.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_03.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_04.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_05.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_06.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_07.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_08.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_09.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_10.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_11.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_12.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_13.png",
"http://terminus.scu.edu/~ntran/csci168-f15/hw/hw3/tile_14.png" ];
var s = 0;
var length = sources.length;
for(s; s< length;++s)
{
imgList[s] = new Image();
imgList[s].src = sources[s];
}
return imgList;
}
</script>
</body>
</html>
看來你打算使用bX和BY作爲'drawImage'的參數。第一次滿足條件時,使用'bY - = 110'會使bY爲負,這是自0%0 == 0以來的第一次迭代。 –
不要使用'document.write',[它有很多問題](https://www.youtube.com/watch?feature=player_detailpage&v=Y2Y0U-2qJMs#t=1082s),並且有更好的選擇。如果您只是將其用於調試,請改用'console.log'。「document.write」存在的一個問題是,如果在加載頁面後調用它,它將清除頁面上的所有內容並將其替換。這意味着,如果在頁面加載後調用'loadImages',則包含畫布標籤*的所有內容都將丟失,因此您的代碼將停止工作。 –