1

我正在绘制在两个不同位置使用加载器方法加载的图像。但它只显示第二个。(我正在关注这个http://www.html5canvastutorials.com/tutorials/html5-canvas-image-loader/

如果我添加一个 alert() 它在 Fx 中有效,但在 Chrome 中无效。我希望它在任何地方都可以在没有 alert() 的情况下工作

如果我尝试在不使用预加载图像的情况下绘制图像,我会得到想要的结果。但我认为这是额外的负载(http://www.html5canvastutorials.com/tutorials/html5-canvas-images/)

ImageOnload("O",120,120); //此图不显示

alert("如果我添加警报,它只在 Fx 中有效,在 Chrome 中无效")

ImageOnload("O",120,20);//只有这个显示???

<html>
    <head>
    </head>
    <script type="text/javascript" >
        var ctx;
        var ImageVariable={};

        window.onload= function()
        {
            var canvas = document.getElementById("gameLoop");   
            ctx = canvas.getContext("2d");

            ImageBuilder(ImageSourceDB);
            ImageOnload("O",120,120); //This image is not displaying
                    //alert("If i add alert it works only in FFox but not in chrome")
            ImageOnload("O",120,20);  
        }

        var ImageSourceDB=
        {
            X:"./Images/X.gif",
            O:"./Images/O.gif"
        }
        function ImageBuilder(ImageSrcDB)
        {
            for (iSrc in ImageSrcDB)
            {
                ImageVariable[iSrc]= new Image();   
                    ImageVariable[iSrc].src = ImageSrcDB[iSrc];
            }
        }

        function ImageOnload(ImageSrc,x,y)
        {
            ImageVariable[ImageSrc].onload= function ()
            {
                ctx.drawImage(ImageVariable[ImageSrc],x,y);
            };          
                    ImageVariable[ImageSrc].src = ImageSourceDB[ImageSrc];
        }
    </script>
    <body>
        <canvas class ="pattern" id="gameLoop" height="300"  width="300" />
    </body>
</html>

项目清单

4

1 回答 1

0
ImageOnload("O",120,120); //This image not displaying
ImageOnload("O",120,20);//only this is displaying ???

您忘记更改对象的 id:

ImageOnload("O",120,120);
ImageOnload("X",120,20); // Use "X", not "O"!!!

如果你还想显示两次“O”,那么你应该画两次,但只有一个onload功能。请参见下面的示例:

<script type="text/javascript" >
    var ctx;
    var ImageVariable={};
    var ImageSourceDB = {
        X:"./Images/X.gif",
        O:"./Images/O.gif"
    }

    window.onload = function() {
        var canvas = document.getElementById("gameLoop");   
        ctx = canvas.getContext("2d");

        ImageBuilder(ImageSourceDB);

        ImageVariable["O"].onload = function() {
            // this will be executed when the image "O" is loaded
            // this is a pointer to ImageVariable["O"]
            ctx.drawImage(this, 120, 120);
            ctx.drawImage(this, 120, 20);
        }
        ImageVariable["X"].onload = function() {
            // this will be executed when the image "X" is loaded
            ctx.drawImage(this, 30,  30);
        }
    }        
    function ImageBuilder(ImageSrcDB) {
        for (iSrc in ImageSrcDB) {
            ImageVariable[iSrc]= new Image();   
            ImageVariable[iSrc].src = ImageSrcDB[iSrc];
        }
    }
</script>
于 2012-06-10T16:19:46.580 回答