图像无法在HTML5画布中呈现

时间:2016-07-19 17:04:28

标签: javascript html5-canvas

我有以下JavaScript代码,调用时应将图像和副标题呈现到HTML5画布中:

var SplashScreen = function SplashScreen(imagePath, subtitle, callback) {
    var up = false;
    this.step = function (dt) {
        if (!Game.keys['fire']) up = true;
        if (up && Game.keys['fire'] && callback) callback();
    };

    this.draw = function (ctx) {
        ctx.fillStyle = "#FFFFFF";

        splashImage = new Image();
        splashImage.src = imagePath;
        splashImage.onload = function () {
            ctx.drawImage(splashImage, Game.width / 2 - 420 / 2, Game.height / 2 - 100, 420, 263);
        }

        ctx.font = "bold 20px 'SF Collegiate'";
        var measure2 = ctx.measureText(subtitle);
        ctx.fillText(subtitle, Game.width / 2 - measure2.width / 2, Game.height / 2 + 200);
    };
};

“副标题”呈现良好。但“splashImage”却没有。通过查看Chrome中的“网络”标签,我看到图片已成功加载。所以看起来图像被找到但从不渲染。

关于我的语法错误的任何想法?

更新:必须是其余代码中的内容...

如果我改变:

splashImage.onload = function () {
            ctx.drawImage(splashImage, Game.width / 2 - 420 / 2, Game.height / 2 - 100, 420, 263);
        }

ctx.drawImage(splashImage, Game.width / 2 - 420 / 2, Game.height / 2 - 100, 420, 263);

它工作正常!奇...

1 个答案:

答案 0 :(得分:0)

如果添加宽度和高度参数可以解决问题,那么可能是您的图像没有预期的大小,或者甚至可能没有固有的大小,就像SVG文件的情况一样。如果这不是正在发生的事情,那么它可能是浏览器中的错误。如果是这种情况,请提交错误。您可以在此处提交针对Chrome的错误:crbug.com/newissue