HTML5画布drawImage在第一次点击时无法工作

4

我有一个画布,我使用JavaScript函数来显示文本和一些图片。我遇到的问题是,点击事件会执行函数并显示文本,但不总是放置图片。如果第二次点击,图像就会出现。这种行为在所有浏览器中都是一致的。命令并不慢,只是第一次未能显示图像。谢谢。

// JavaScript Document

    function manualsTxt() {
        var theCanvas = document.getElementById('Canvas1');
        if (theCanvas && theCanvas.getContext) {
            var ctx = theCanvas.getContext("2d");

            if (ctx) {
                var img1 = new Image();
                var img2 = new Image();
                var img3 = new Image();
                img1.src = "images/InRoads2004.png";
                img2.src = "images/XMUp.png";
                img3.src = "images/XM.png";

                //clear canvas
                ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);

                // .drawImage (src, posX, posY);
                ctx.drawImage (img1, 50, 325);
                ctx.drawImage (img2, 250, 325);
                ctx.drawImage (img3, 450, 325);

                ctx.textBaseline = 'bottom';
                ctx.font         = 'bold 30px sans-serif';
                ctx.fillStyle   = '#671420';
                ctx.fillText ('InRoads Manuals', 60, 30);

                ctx.fillStyle    = '#000';
                ctx.font         = 'italic bold 16px sans-serif';
                ctx.textBaseline = 'top';
                ctx.fillText  ('MJM Consulting has published several InRoads training', 80, 60);
                ctx.fillText  ('manuals that have been used all over the world.  We have', 90, 80);
                ctx.fillText  ('utilized our training manuals in all of our on-site trainings', 100, 100);
                ctx.fillText  ('for dozens of civil engineering firms and Department of', 105, 120);
                ctx.fillText  ('Transportations.  Our manuals were one of the first to follow', 110, 140);
                ctx.fillText  ('a typical civil design project format.  Our manuals are easy', 115, 160);
                ctx.fillText  ('to follow and contain a cd with a self-installing data set.', 115, 180);
                ctx.fillText  ('While our manuals are listed on other sites such as Amazon.com,', 115, 220);
                ctx.fillText  ('ordering direct from us is the only place you will get a', 110, 240);
                ctx.fillText  ('full color version of the manual.', 105, 260);

            }
        }
    }

这似乎是一个缓存问题。在运行此函数之前,您是否尝试过预加载图像? - Ricardo Souza
1个回答

12
因为你没有等待图片加载完成。
var img = new Image();   // Create new img element
img.onload = function(){
  // execute drawImage statements here
};
img.src = 'myImage.png'; // Set source path

在尝试绘制图片之前,请确保每个图像已经触发了onload事件。如果你有多个图片且不想编写复杂的代码,那么可以使用一些库来完成这项工作,例如pxloader


感谢您的评论和想法。我已经创建了一个单独的 .js 文件,定义了包括源代码在内的图像。这个文件首先被加载,当用户点击需要图片的链接时,它们已经被加载了。非常感谢您!!!这让我抓狂了@@@ - Prostang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接