te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>Preloading images in Javascript? Without jQuery - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Preloading images in Javascript? Without jQuery - Stack Overflow

programmeradmin3浏览0评论

There are several questions about this in the forum, but I couldn't get a good answer for what I need.

I am getting into Canvas and Javascript, and I want to preload some images as soon as the game opens. I made an example of the method I wanted to build (and didn't work)

I have 3 files: "main.html" where the canvas (there is only one in this example) is declared and I try to load an image, "ImagePreloader.js" where I preload all the images and "Variables.js" where I have my variables.

Could anyone please help me with this image preloading metod, or suggest me a viable one? I think the image is not loading because I am not using an onLoad() function, which I couldn't understand in the tutorials I read so far (I know how to apply it to an image, but not to an array of images)

main.html:

<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="800" height="600"></canvas>

    <script type="text/javascript" src="Variables.js"></script>
    <script type="text/javascript" src="ImagePreloader.js"></script>
    <script>
    // Basic canvas info
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // Draw one of the images. Somehow it doesn't work :(
    context.drawImage(imageArray[3], x, y, width, height);
    </script>
  </body>
</html>

ImagePreloader.js

// This should preload the images in imageArray[i] with 0 <= i <= 5 ... right?
function preloader() 
 {
     for(var i=0; i<5; i++) 
     {
          imageArray[i].src=images[i];
     }
 } 

Variables.js

// array of sources of my images
images = new Array();
images[0]="img1.jpg"
images[1]="img2.jpg"
images[2]="img3.jpg"
images[3]="img4.jpg"
images[4]="img5.jpg"

// Stuff to draw the image
var x = 50;
var y = 50;
var width = 256;
var height = 256;

// Is this actually an array of images?
imageArray = new Image();

Thanks in advance!

There are several questions about this in the forum, but I couldn't get a good answer for what I need.

I am getting into Canvas and Javascript, and I want to preload some images as soon as the game opens. I made an example of the method I wanted to build (and didn't work)

I have 3 files: "main.html" where the canvas (there is only one in this example) is declared and I try to load an image, "ImagePreloader.js" where I preload all the images and "Variables.js" where I have my variables.

Could anyone please help me with this image preloading metod, or suggest me a viable one? I think the image is not loading because I am not using an onLoad() function, which I couldn't understand in the tutorials I read so far (I know how to apply it to an image, but not to an array of images)

main.html:

<!DOCTYPE HTML>
<html>
  <body>
    <canvas id="myCanvas" width="800" height="600"></canvas>

    <script type="text/javascript" src="Variables.js"></script>
    <script type="text/javascript" src="ImagePreloader.js"></script>
    <script>
    // Basic canvas info
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // Draw one of the images. Somehow it doesn't work :(
    context.drawImage(imageArray[3], x, y, width, height);
    </script>
  </body>
</html>

ImagePreloader.js

// This should preload the images in imageArray[i] with 0 <= i <= 5 ... right?
function preloader() 
 {
     for(var i=0; i<5; i++) 
     {
          imageArray[i].src=images[i];
     }
 } 

Variables.js

// array of sources of my images
images = new Array();
images[0]="img1.jpg"
images[1]="img2.jpg"
images[2]="img3.jpg"
images[3]="img4.jpg"
images[4]="img5.jpg"

// Stuff to draw the image
var x = 50;
var y = 50;
var width = 256;
var height = 256;

// Is this actually an array of images?
imageArray = new Image();

Thanks in advance!

Share Improve this question edited Jul 3, 2013 at 5:16 Igor 34k14 gold badges82 silver badges116 bronze badges asked Jul 3, 2013 at 5:13 CookieGuyCookieGuy 631 gold badge2 silver badges7 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

Well, you will want to use a function which loads the images at a certain point, so you might as well try to understand onLoad. It's not that hard to grasp.

"onload" is a javascript event that occurs immediately after something is loaded. In other words: onLoad is like a javascript-native function which triggers when something is loaded. That something can be a window (eg: window.onload) or a document. What you want is the document onLoad event, as it triggers when your document is loaded.

Let's provide you with a simple example...

<body onload="preloadMyImages();">

This tells the browser "when you've loaded the document, run the preloadMyImages function".

All you have to do is then use that function to load your images into the client's browser cache.

function preloadMyImages() 
{
    var imageList = [
        "image.gif",
        "example/image.jpg",
        "whatever/image.png"
    ];
    for(var i = 0; i < imageList.length; i++ ) 
    {
        var imageObject = new Image();
        imageObject.src = imageList[i];
    }
}

That practically wraps it up and provides you with a fully working example. Enjoy!

EDIT

Since - according to your ment - you are looking for some more help, I would like to point you to https://stackoverflow./a/1038381/2432317 which (as one of many examples) shows how that you can (and probably should - depending on what you're planning do draw on your canvas) use img.onload too.

Yet, as I stated in my ment: it will all depend on where you want to take it. The more you dive into Javascript coding, the more you will understand what's going on. There are several good (partly free) books out there explaining how to code Javascript, use the HTML5 canvas, create preloaders, animations, talk about scopes etc.

A quick check at the big G of search engines turns up ample examples and tutorials too which will be helpfull for you. One of many examples: "How To Draw Images Onto Your HTML5 Canvas" which shows you preloading and looping an animation in a short and crisp tutorial.

But please, don't expect us to code it all for you - it's not going to happen. This is one of the not-so-rare cases where "learning by doing" will actually make you smarter. And if you hit another problem on your way to your final goal, you can always post a new question related to that new problem.

You have to make sure these 5 images are loaded (downloaded doesnt alwaysmean its loaded and ready to use, only onload guarantees that image is ready to use) before you use it.

So add onload for the images, then count from the onload function and trigger the draw after 5 of them are loaded

function prefetchImages(sources){
        var images = [];
        var loadedImages = 0;
        var numImages = sources.length;
        for (var i=0; i < numImages; i++) {
            images[i] = new Image();
            images[i].onload = function(){
                if (++loadedImages >= numImages) {
                    //ready draw with my images now
                    drawThePainting();
                }
            };
            images[i].src = sources[i]; //bind onload before setting src bug in some chrome versions
        }
    };

prefetchImages(["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]);

function drawThePainting(){
        // Basic canvas info
    var canvas = document.getElementById('myCanvas');
    var context = canvas.getContext('2d');

    // Draw one of the images. Somehow it doesn't work :(
    context.drawImage(imageArray[3], x, y, width, height);
}

try this

put this script in head section
<script type="text/javascript">
    function preload(arrayOfImages) {
      for(i = 0 ; i < arrayOfImages.length ; i++)
         {
     var img = new Image();
             img.src = arrayOfImages[i];
         }
    }

 preload(['img1.png','img2.png']);
</script>
发布评论

评论列表(0)

  1. 暂无评论