直到用户点击,图片不会在画布上绘制? [英] Image not drawn on canvas until user clicks?

查看:159
本文介绍了直到用户点击,图片不会在画布上绘制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绘制几个图像与执行类似的功能:

I draw several images with a function that performs something similar to:

context.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height);

我读过,我需要等待图片加载才能绘制,具有类似这样的:

I've read that I need to wait for the image to be loaded before I can draw it, with something like this:

img.onload = function() {
    context.drawImage(img, width / 2 * (-1), height / 2 * (-1), width, height);
};

但是这会导致图像被绘制,但是之后没有绘制,因为我调用我的绘制函数每几毫秒,因为它是一个简单的游戏的'动画'循环的一部分。

However this causes the image to be drawn but afterwards, nothing is drawn since I call up my draw function every few milliseconds as it's part of the 'animation' loop for a simple game.

有一种方式,我可以等待onload事件,我的init()函数?

Is there a way that I can wait for the onload event before I continue running code in my init() function?

我想像这样:

var image_loaded = false;
img.onload = function() {
    image_loaded = true;
};
if(image_loaded) {
    animate();
}

应该工作吗?除非我需要添加一个timeOut函数来保持调用init(),直到image_loaded为true。

Should work? Unless I need to add a timeOut function to keep calling the init() until image_loaded is true?

推荐答案

小图书馆。

检查演示

请参阅下面的库代码:

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



工作原理



图片已加载并且您的应用程序可以使用该库具有 Loader.preload 方法。

preload方法将接收一个对象数组,每个对象包含要加载的图像的名称和src属性。您可以选择设置 onComplete 回调(在加载所有图像时调用)和 onProgressUpdate 回调每次加载图像时调用)。 onProgressUpdate 回调在您为应用程序创建加载屏幕时很有用。

The preload method will receive an array of objects, each object containing the name and the src properties of an image you want to load. Optionally you can setup the onComplete callback (to be called when all images are loaded) and the onProgressUpdate callback (to be called each time an image is loaded). The onProgressUpdate callback is useful if you want to create a loading screen for your application.

使用 Loader.getProgress()以获取随时加载的图片的百分比。

Use the Loader.getProgress() to obtain the percentage of images loaded at any time.

要获取已加载图片的引用,调用 Loader.getImage(name)其中name是图像的name属性(a String)。

To obtain the reference of an image loaded, call Loader.getImage(name) where name is the name property (a String) of the image.

你由于某种原因需要迭代所有图像使用 Loader.images

If you for some reason needs iterate over all images use Loader.images. It's the object containing all references for the images in its properties.

使用像这样:

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

如果没有,请检查演示

这篇关于直到用户点击,图片不会在画布上绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆