Use JS to achieve a set of picture animation effect or use HTML5 canvas to render a series of pictures and other cases, the picture needs to be fully loaded to run the animation effect. More than one picture preloaded code is involved in this program. When a succession of cases involves picture preloading, it is necessary to consider encapsulating this functionality as a common method.
(1) The following is the JS implementation picture Preloading method Loadimages ():
JS Code
- //Implementation of a series of images preloaded
- //Parameter sources: Image information associative array
- //Parameter callback: callback function--executes this function immediately after the picture preload is complete.
- function loadimages (sources, callback) {
- var count = 0,
- Images ={},
- Imgnum = 0;
- for (src in sources) {
- imgnum++;
- }
- for (src in sources) {
- IMAGES[SRC] = new Image ();
- Images[src].onload = function() {
- if (++count >= Imgnum) {
- callback (images);
- }
- }
- IMAGES[SRC].SRC = Sources[src];
- }
- }
(2) Call the pre-load function in JS:
JS Code
- //Store associative array of image link information
- var sources = {
- Ietohell: "Img/ietohell.jpg",
- Fuckie: "Img/fuckie.jpg"
- };
- //Call picture pre-load function, implement callback function
- Loadimages (sources, function(images) {
- //to-do Something
- Ctx.drawimage (Images.ietohell, 20,20,100,100);
- Ctx.drawimage (Images.fuckie, 140,20,100,100);
- });
Precautions:
(1) Bind the Image.onload event first, then load the picture
JS Code
- IMAGES[SRC] = new Image ();
- Images[src].onload = function() {
- if (++count >= Imgnum) {
- callback (images);
- }
- }
- IMAGES[SRC].SRC = Sources[src];
Cause: If the picture is loaded from the cache, it is so fast that it does not load when it is time to bind the event, and naturally does not trigger the binding event.
(2) The difference between the for...in loop and the For loop
For loop for iterated algebraic groups (array)
For...in loop for iterating over objects (object, {}) or associative arrays (hash array)
JavaScript implementation picture preload "callback function, multiple pictures"