我试图将一堆图像加载到画布上,但不是它们出现。源代码包含我想要使用的图像的链接。有人有主意吗?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',则包含画布标签*的所有内容都将丢失,因此您的代码将停止工作。 –