Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/397.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在用户单击之前,是否在画布上绘制图像?_Javascript_Html_Canvas - Fatal编程技术网

Javascript 在用户单击之前,是否在画布上绘制图像?

Javascript 在用户单击之前,是否在画布上绘制图像?,javascript,html,canvas,Javascript,Html,Canvas,我用一个函数绘制了几个图像,该函数执行类似于: context.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height); 我读到,我需要等待图像加载,然后才能绘制它,如下所示: img.onload = function() { context.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height); }; var images

我用一个函数绘制了几个图像,该函数执行类似于:

context.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height);
我读到,我需要等待图像加载,然后才能绘制它,如下所示:

img.onload = function() {
    context.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height);
};
var images = [{name: "img1", src: "http://...a.."}, 
              {name: "img2", src: "http://...b.."},
              ...
              {name: "imgN", src: "http://...N.."}];

function onProgressUpdate(progress){
    ...
    drawProgressBar(progress); // just an example of what you can do
    ...
}

function onComplete(){
    ...        
    // get an Image from Loader object
    var texture = Loader.getImage("img2");
    // or use this:
    var texture = Loader.images.img2; // or still Loader.images["img2"]
    ...

    // iterate over the images
    for (var img in Loader.images){
        console.log(Loader.images[img].src);
    }
    ....
}

Loader.preload(images, onComplete, onProgressUpdate);
然而,这会导致绘制图像,但之后,什么也不会绘制,因为我每隔几毫秒调用一次绘制函数,因为它是简单游戏“动画”循环的一部分

在继续运行init()函数中的代码之前,是否有一种方法可以等待onload事件

我想是这样的:

var image_loaded = false;
img.onload = function() {
    image_loaded = true;
};
if(image_loaded) {
    animate();
}
应该有用吗?除非我需要添加一个超时函数来继续调用init(),直到加载的映像为true为止?

var imagesLoaded = [],
    images = [
        'http://www.zombiegames.net/inc/screenshots/The-Last-Stand-Union-City.png', 
    'http://www.zombiegames.net/inc/screenshots/Lab-of-the-Dead.png',
    'http://www.zombiegames.net/inc/screenshots/Zombotron.png',
    'http://www.zombiegames.net/inc/screenshots/Road-of-the-Dead.png'],
    canvas = document.getElementById("canvas"),
    ctx = canvas.getContext("2d");

canvas.width = 640;
canvas.height = 480;

function init(){
    // just loops through the images.
    if(imagesLoaded.length > 0){
        ctx.drawImage(imagesLoaded[0], 0, 0, 640, 480);
        imagesLoaded.push(imagesLoaded.shift());   
    }
    setTimeout(init,500);
}

function preload(){
    for(var i = 0; i < images.length; i++){
        (function(value){
            return function(){
                var loadedImage = new Image();
                loadedImage.src = images[value];
                loadedImage.onload = function(){
                    imagesLoaded.push(loadedImage);  
                } 
            }();
        })(i);

    }
    checkLoaded();
}

function checkLoaded(){
    if(imagesLoaded.length === images.length){
        console.log(imagesLoaded.length);
        init(); 
    } else{
        setTimeout(checkLoaded,30);
    }
}

preload();
var imagesLoaded=[],
图像=[
'http://www.zombiegames.net/inc/screenshots/The-Last-Stand-Union-City.png', 
'http://www.zombiegames.net/inc/screenshots/Lab-of-the-Dead.png',
'http://www.zombiegames.net/inc/screenshots/Zombotron.png',
'http://www.zombiegames.net/inc/screenshots/Road-of-the-Dead.png'],
canvas=document.getElementById(“canvas”),
ctx=canvas.getContext(“2d”);
画布宽度=640;
canvas.height=480;
函数init(){
//只是在图像中循环。
如果(imagesLoaded.length>0){
ctx.drawImage(图像标记为[0],0,0,640,480);
imagesLoaded.push(imagesLoaded.shift());
}
setTimeout(init,500);
}
函数预加载(){
对于(var i=0;i
上面是一个如何预加载图像并等待执行其他操作的示例。基本上,您要做的是将所有图像放在一个数组中,并向每个图像添加
onload
事件。当它们加载时,我通过它们进入另一个数组,该数组保存所有加载的图像。一旦两个数组的长度匹配,所有图像都可以使用


另一种方法是在加载计数器时递增计数器,并根据数组的长度检查其值。当计数器变量等于images数组的长度时,表示它们都已加载并准备好使用。

我创建了一个简单的小型库,以方便加载图像

请参阅下面的库代码:

// Simple Image Loader Library
window.Loader = (function () {
var imageCount = 0;
var loading = false;
var total = 0;

// this object will hold all image references
var images = {};

// user defined callback, called each time an image is loaded (if it is not defined the empty function wil be called)
function onProgressUpdate() {};
// user defined callback, called when all images are loaded (if it is not defined the empty function wil be called)
function onComplete() {};

function onLoadImage(name) {        
    ++imageCount;
    console.log(name + " loaded");

    // call the user defined callback when an image is loaded
    onProgressUpdate();

    // check if all images are loaded
    if (imageCount == total) {
        loading = false;
        console.log("Load complete.");
        onComplete();
    }

};

function onImageError(e) {
    console.log("Error on loading the image: " + e.srcElement);
}

function loadImage(name, src) {
    try {
        images[name] = new Image();
        images[name].onload = function () {
            onLoadImage(name);
        };
        images[name].onerror = onImageError;
        images[name].src = src;
    } catch (e) {
        console.log(e.message);
    }
}

function getImage(/**String*/ name){
    if(images[name]){
        return (images[name]);
   }
    else{
        return undefined; 
    }
}

// pre-load all the images and call the onComplete callback when all images are loaded
// optionaly set the onProgressUpdate callback to be called each time an image is loaded (useful for loading screens) 
function preload( /**Array*/ _images, /**Callback*/ _onComplete, /**Callback <optional>*/ _onProgressUpdate) {
    if (!loading) {

        console.log("Loading...");
        loading = true;

        try {
            total = _images.length;
            onProgressUpdate = _onProgressUpdate || (function(){});
            onComplete = _onComplete || (function(){});                

            for (var i = 0; i < _images.length; ++i) {
                loadImage(_images[i].name, _images[i].src);                    
            }
        } catch (e) {
            console.log(e.message);
        }
    } else {
        throw new Error("Acess denied: Cannot call the load function while there are remaining images to load.");
    }
}

// percentage of progress
function getProgress() {
    return (imageCount / total)*100;
};

// return only the public stuff to create our Loader object
return {
    preload: preload,
    getProgress: getProgress,
    getImage: getImage,
    images: images // have access to the array of images might be useful but is not necessary
};
})();

如果您没有。在哪里以及如何声明img?我设置var img=new Image();img.src=“image.png”;在脚本的顶部(我的所有其他变量都在这里)。然后我只在animate()期间调用draw,因为我多次绘制相同的图像(在不同的位置绘制多个不同的球)。这
setTimeout(checkLoaded,30)
似乎效率不高。我相信有一种更好的方法可以在每次加载时调用回调。嗯,ok尝试了您的解决方案,但没有使用数组,但似乎无法使其正常工作。我的一个简单游戏只有一个图像,其他游戏使用2-3个图像,所以我将使用这个解决方案来解决那些[效果很好]。但是,有没有更简单的方法来命名图像,而不是调用imagesLoaded[0]?