【问题标题】:Image Preloading Canvas in ChromeChrome 中的图像预加载画布
【发布时间】:2013-02-27 12:47:22
【问题描述】:

据我所知,我已成功预加载了所有图像。在 FireFox 中,一切都呈现得很好,但它拒绝出现在 Chrome 中。我已经在使用 webkit 浏览器时遇到过其他随机的怪癖,我认为这只是其中之一。这是适用的代码(我为篇幅道歉,只是冗长。我向你保证,其中大部分都很简单)。

initResources() 从 $(document).ready() 函数中调用,其中画布也已正确初始化。

具体问题似乎是游戏板。 X 和 O(它是 tictactoe ...)看起来不错,但游戏板拒绝单独出现在 Chrome 的画布上。适用于所有其他浏览器。 Chrome 的开发者工具坚称它们是通过网络选项卡加载的,控制台显示了它应该显示的所有内容。谢谢。

[编辑:刚刚在 Firefox 中也失败了。可能是缓存问题,此时我更加困惑]

var canvas, context, playerPiece, aiPiece;
var x = new Image();
var o = new Image();
var gameBoard = new Image();
var numResources = 3;   // Total number of resources to wait for loading
var curResources = 0;

function initResources() {
    // Get all our resources ready to go
    x.height = 130;
    x.width = 130;
    x.onload = isLoaded();
    x.src = "images/gamepieceX.png";

    o.height = 130;
    o.width = 130;
    o.onload = isLoaded();// = curResources++;
    o.src = "images/gamepieceO.png";

    gameBoard.height = 500;
    gameBoard.width = 500;
    gameBoard.onload = isLoaded(); //= curResources++;
    gameBoard.src = "images/gameBoard.png";
}

function isLoaded() {
    curResources++;
    console.log("Loaded resource! Total: " + curResources);
    if(curResources == numResources) {
        console.log("All loaded up! Moving on!");
        gameSetup();
    }
}

function gameSetup() {
    // Draw our board and assign a piece
    console.log("Setting up game!");
    playerPiece = x;
    aiPiece = o;

    // Draw gameboard
    context.drawImage(gameBoard, 0, 0);
    console.log(gameBoard);

    canvas.addEventListener ("mousedown", mouseClicked, false);
}

【问题讨论】:

  • 我听说使用img.onload 的唯一可靠方法是通过<img onload=""/> 对其进行初始化,这样var img = new Image(); 不会始终触发onload
  • 您正在内联运行 isLoaded 函数,而不是在实际加载图像时。我认为你想要.onload = isLoaded(没有括号)不确定这是否相关,只是指出来。
  • 是的,Xymotech,我相信这就是问题所在!在回到这里并看到这些 cmets 之前,我刚刚发现了同样的事情。谢谢!
  • @DanielGast 没问题。总是小事让你着迷。 :)

标签: javascript html google-chrome canvas preload


【解决方案1】:

我是在调用内联函数而不是为每个图像上的 .onload 回调。这是在加载图像之前启动游戏初始化。感谢那些发表评论的人,但我在这里发帖后才看到这个:)

【讨论】:

    【解决方案2】:

    这是一个可能与此有关的 chrome 错误的链接。

    https://code.google.com/p/chromium/issues/detail?id=245296

    而不是使用

    new Image()
    

    以老式方式创建图像元素

    document.createElement("img")
    

    【讨论】:

      猜你喜欢
      • 2011-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-05
      • 1970-01-01
      • 2012-07-16
      • 2015-08-31
      相关资源
      最近更新 更多