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

时间:2012-03-20 22:58:05

标签: html5 canvas drawimage

我有一个画布,我正在使用javascript函数来显示文本和一些图像。我遇到的问题是点击确实执行该功能并显示文本,但并不总是放置图像。如果再次单击,则会显示图像。此行为在所有浏览器中都是一致的。命令不慢,只是第一次无法显示图像。 TIA

// 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);

            }
        }
    }

1 个答案:

答案 0 :(得分:8)

因为您没有等待图像完成加载。

var img = new Image();   // Create new img element
img.onload = function(){
  // execute drawImage statements here
};
img.src = 'myImage.png'; // Set source path

确保在尝试绘制之前为每个图像触发onload事件。如果您有多个图像并且不想复杂化,那么有些库可以为您执行此操作,例如pxloader