繁体   English   中英

图片无法在HTML5画布中呈现

[英]Image not rendering in 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);

它行得通! 奇...

如果添加width和height参数可以解决此问题,则可能是图像没有您期望的尺寸,或者甚至没有固有尺寸(有时与SVG文件一样)。 如果不是这种情况,则可能是浏览器中的错误。 如果是这种情况,请提交错误。 您可以在此处提交针对Chrome的错误: crbug.com/newissue

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM