### JavaScript: PreloadJS Sprite Sheet Loading and EaselJS Setup Source: https://github.com/createjs/preloadjs/blob/master/examples/SpriteSheet.html Initializes EaselJS stage, defines asset manifest for images and a sprite sheet, and uses createjs.LoadQueue to load assets. Handles file loading and completion events to set up the game environment. ```javascript var assets; var stage; var w, h; var sky, grant, ground, hill, hill2; var runningRate, isInWarp, isStationary; var stationaryPosition, isPassed, spriteSheet; function init() { examples.showDistractor(); var canvas = document.getElementById("testCanvas"); stage = new createjs.Stage(canvas); runningRate = 2.5; isInWarp = false; isStationary = false; stationaryPosition = 300; isPassed = false; // grab canvas width and height for later calculations: w = canvas.width; h = canvas.height; assets = []; manifest = [ {src: "art/sky.png", id: "sky"}, {src: "art/ground.png", id: "ground"}, {src: "art/hill2.png", id: "hill2"}, {src: "art/hill1.png", id: "hill"}, {src: "static/grant.json", id:"grant", type:"spritesheet", crossOrigin:true} ]; var loader = new createjs.LoadQueue(true, "../\_assets/"); loader.on("fileload", handleFileLoad); loader.on("complete", handleComplete); loader.loadManifest(manifest); stage.autoClear = false; } function handleFileLoad(event) { assets.push(event); } function handleComplete() { for (var i = 0; i < assets.length; i++) { var event = assets[i]; var id = event.item.id; var result = event.result; switch (id) { case "sky": sky = new createjs.Shape(new createjs.Graphics().beginBitmapFill(result).drawRect(0, 0, w, h)); break; case "ground": ground = new createjs.Shape(); var g = ground.graphics; g.f("#f00"); g.beginBitmapFill(result); g.drawRect(0, 0, w + 330, 79); ground.y = h - 79; break; case "hill": // Vertically offset the pattern fill by 1 to solve a Chrome bug on BitmapFills hill = new createjs.Shape(new createjs.Graphics().f("#f00").beginBitmapFill(result).drawRect(0, 1, 282, 60)); hill.x = Math.random() * w | 0; hill.scaleX = hill.scaleY = 3; hill.y = 144; break; case "hill2": hill2 = new createjs.Shape(new createjs.Graphics().beginBitmapFill(result).drawRect(0, 1, 212, 51)); hill2.x = Math.random() * w | 0; hill2.scaleX = hill2.scaleY = 3; hill2.y = 171; break; case "grant": var spriteSheet = result; spriteSheet.getAnimation("run").next = "run"; spriteSheet.getAnimation("jump").next = "run"; grant = new createjs.Sprite(spriteSheet, "run") .set({x: -200, y:40, scaleX:0.8, scaleY:0.8}); } } examples.hideDistractor(); if (grant == null) { console.error("Can not play. Grant sprite was not loaded."); return; } stage.addChild(sky, hill, hill2, ground, grant); stage.on("mousedown", handleJumpStart); createjs.Ticker.framerate = 40; createjs.Ticker.on("tick", tick); } ``` -------------------------------- ### Initialize PreloadJS with Custom Loader and Load File (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/CustomLoader.html Initializes a PreloadJS LoadQueue, installs the custom loader plugin, and loads an image file. It also sets up an event listener for file loading completion to append the loaded content to the document body. ```javascript /** * Initialization function. */ function init() { // Hide header if this is not the top window (e.g., in an iframe) if (window.top != window) { document.getElementById("header").style.display = "none"; } var loader = new createjs.LoadQueue(); loader.installPlugin(CustomLoader); // Install the custom loader plugin loader.loadFile("../_assets/art/Autumn.png"); // Load the image file loader.on("fileload", handleFileLoad); // Set up file load event listener loader.load(); // Start the loading process } /** * Handles the 'fileload' event from the LoadQueue. * Appends the loaded result (an image element) to the document body. * @param {object} event The event object. */ function handleFileLoad(event) { console.log(event); document.body.appendChild(event.result); } // Call init() to start the process if the script is run directly // init(); ``` -------------------------------- ### Load Manifest and Media Grid Source: https://github.com/createjs/preloadjs/blob/master/examples/MediaGrid.html Loads a JSON manifest file to define the assets for the media grid. It specifies the manifest source, a callback function to handle the loaded manifest, and the base path for assets. ```javascript function loadManifest() { preload.loadManifest({src: "../_assets/static/MediaGridManifest.json", callback: "loadMediaGrid", type: "manifest"}, true, "../_assets/"); } ``` -------------------------------- ### Integrate SoundJS Plugin with PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Demonstrates how to install and use plugins, specifically SoundJS, with PreloadJS. The plugin must be installed before adding audio files to the manifest. The example shows loading audio and playing it after completion. ```javascript // Install SoundJS plugin before loading audio files var queue = new createjs.LoadQueue(); // Plugin must be installed BEFORE adding items queue.installPlugin(createjs.Sound); queue.on("fileload", handleFileLoad); queue.on("complete", handleComplete); queue.loadManifest([ {id: "music", src: "audio/background.mp3"}, {id: "sfx", src: "audio/explosion.mp3"} ]); function handleFileLoad(event) { if (event.item.type === createjs.Types.SOUND) { console.log("Sound loaded:", event.item.id); } } function handleComplete() { // Play sound using SoundJS createjs.Sound.play("music"); } ``` -------------------------------- ### Initialize PreloadJS and Register Sound Plugin Source: https://github.com/createjs/preloadjs/blob/master/examples/MediaGrid.html Initializes a new createjs.LoadQueue instance, registers the HTMLAudioPlugin for sound, and sets up event listeners for file loading and errors. It favors XHR loading but can be configured to use tag loading. ```javascript var preload; function init() { // Create a new queue. //preload = new createjs.LoadQueue(true, "assets/"); // Use this instead to favor XHR loading preload = new createjs.LoadQueue(true); createjs.Sound.registerPlugins([createjs.HTMLAudioPlugin]); // need this so it doesn't default to Web Audio preload.installPlugin(createjs.Sound); preload.on("fileload", handleFileLoaded); preload.on("error", handleError); } ``` -------------------------------- ### Load a file with PreloadJS LoadQueue Source: https://github.com/createjs/preloadjs/blob/master/README.md This example demonstrates how to initialize a LoadQueue, listen for file completion events, and load a single image file. The loaded image is then appended to the document body. ```javascript var queue = new createjs.LoadQueue(false); queue.on("fileload", handleFileComplete); queue.loadFile('http://createjs.com/assets/images/png/createjs-badge-dark.png'); function handleFileComplete(event) { document.body.appendChild(event.result); } ``` -------------------------------- ### JavaScript: Preload Images and Create Gallery with PreloadJS Source: https://github.com/createjs/preloadjs/blob/master/examples/PreloadImages.html Initializes PreloadJS to load a manifest of images, displays a loading progress bar, and adds images to a canvas stage upon completion. Handles image clicks to reorder them. ```javascript var loaderBar; var stage; var bar; var imageContainer; var currentImage; var loaderWidth; var loaderColor; var borderPadding; var preload; var oldItem; function init() { canvas = document.getElementById("myCanvas"); stage = new createjs.Stage(canvas); stage.enableMouseOver(10); borderPadding = 10; var barHeight = 20; loaderColor = createjs.Graphics.getRGB(247, 247, 247); loaderBar = new createjs.Container(); bar = new createjs.Shape(); bar.graphics.beginFill(loaderColor).drawRect(0, 0, 1, barHeight).endFill(); imageContainer = new createjs.Container(); imageContainer.x = 430; imageContainer.y = 200; loaderWidth = 300; stage.addChild(imageContainer); var bgBar = new createjs.Shape(); var padding = 3 bgBar.graphics.setStrokeStyle(1).beginStroke(loaderColor).drawRect(-padding / 2, -padding / 2, loaderWidth + padding, barHeight + padding); loaderBar.x = canvas.width - loaderWidth >> 1; loaderBar.y = canvas.height - barHeight >> 1; loaderBar.addChild(bar, bgBar); stage.addChild(loaderBar); manifest = [ {src: "image0.jpg", id: "image0"}, {src: "image1.jpg", id: "image1"}, {src: "image2.jpg", id: "image2"}, {src: "image3.jpg", id: "image3"} ]; preload = new createjs.LoadQueue(true, "test/"); // Use this instead to use tag loading //preload = new createjs.LoadQueue(false); preload.on("progress", handleProgress); preload.on("complete", handleComplete); preload.on("fileload", handleFileLoad); preload.loadManifest(manifest, true, "../\_assets/art/"); createjs.Ticker.framerate = 30; } function stop() { if (preload != null) { preload.close(); } } function handleProgress(event) { bar.scaleX = event.loaded * loaderWidth; } function handleFileLoad(event) { var image = event.result; var w = image.width; var h = image.height; var bmp = new createjs.Bitmap(image).set({ scaleX: 0.75, scaleY: 0.75, regX: w / 2, regY: h / 2, rotation: Math.random() * 16 - 8, cursor: "pointer", x: borderPadding / 2 * 0.75, y: borderPadding / 2 * 0.7 }); bmp.on("click", handleClick); var border = new createjs.Shape( new createjs.Graphics().beginFill("#FFFFFF").drawRect(0, 0, w + borderPadding, h + borderPadding).endFill() ).set({ rotation: bmp.rotation, regX: w / 2, regY: h / 2, scaleX: bmp.scaleX, scaleY: bmp.scaleY, shadow: new createjs.Shadow("#000000", 0, 0, 2.5) }); var container = new createjs.Container(); container.addChild(border, bmp); imageContainer.addChild(container); stage.update(); } function handleClick(event) { currentItem = event.target.parent; createjs.Tween.get(currentItem, {override: true}) .to({y: -300, rotation:currentItem.rotation+Math.random()*30-15}, 200, createjs.Ease.quadInOut) .call(tweenUpComplete) .to({y: 0, rotation:currentItem.rotation}, 600, createjs.Ease.quadOut) .on("change", handleTweenChange); } function handleTweenChange(tween) { stage.update(); } function tweenUpComplete(event) { imageContainer.addChildAt(currentItem, 0); } function handleComplete(event) { loaderBar.visible = false; stage.update(); } ``` -------------------------------- ### PreloadJS Queue Initialization and Event Handling (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/PreloadQueue.html Initializes a PreloadJS LoadQueue, sets up event listeners for file loading, progress, and errors, and defines functions to manage the loading process. It uses a manifest array for initial assets and allows for on-demand loading. ```javascript var map = {}; var preload; var loader; var manifest; var w = 226; // Item width var h = 170; // Item height function init() { $("#loadAnotherBtn").click(loadAnother); $("#loadAllBtn").click(loadAll); $("#reloadBtn").click(reload); reload(); } // Reset everything function reload() { // If there is an open preload queue, close it. if (preload != null) { preload.close(); } // Reset the UI $("#reloadBtn").css("display", "none"); $(".box").remove(); $("#mainProgress .progress").width(0); $("#loadAnotherBtn").attr("disabled", null); $("#loadAllBtn").attr("disabled", null); // Push each item into our manifest manifest = [ "image0.jpg", "image1.jpg", "image2.jpg", "image3.jpg", "Autumn.png", "BlueBird.png", "Nepal.jpg", "Texas.jpg" ]; // Create a preloader. There is no manifest added to it up-front, we will add items on-demand. preload = new createjs.LoadQueue(true, "../_assets/art/"); // Use this instead to use tag loading //preload = new createjs.LoadQueue(false); preload.on("fileload", handleFileLoad); preload.on("progress", handleOverallProgress); preload.on("fileprogress", handleFileProgress); preload.on("error", handleFileError); preload.setMaxConnections(5); } function stop() { if (preload != null) { preload.close(); } } function loadAll() { while (manifest.length > 0) { loadAnother(); } } function loadAnother() { // Get the next manifest item, and load it var item = manifest.shift(); preload.loadFile(item); // If we have no more items, disable the UI. if (manifest.length == 0) { $("#loadAnotherBtn").attr("disabled", "disabled"); $("#loadAllBtn").attr("disabled", "disabled"); $("#reloadBtn").css("display", "inline"); } // Create a new loader display item var div = $("#template").clone(); div.attr("id", ""); // Wipe out the ID div.addClass("box") $("#container").append(div); map[item] = div; // Store a reference to each item by its src } // File complete handler function handleFileLoad(event) { var div = map[event.item.id]; div.addClass("complete"); // Get a reference to the loaded image () var img = event.result; // Resize it to fit inside the item var r = img.width / img.height; var ir = w / h if (r > ir) { img.width = w; img.height = w / r; } else { img.height = h; img.width = h; } div.append(img); // Add it to the DOM } // File progress handler function handleFileProgress(event) { var div = map[event.item.id]; // Lookup the related item div.children("DIV").width(event.progress * div.width()); // Set the width the progress. } // Overall progress handler function handleOverallProgress(event) { $("#mainProgress > .progress").width(preload.progress * $("#mainProgress").width()); } // An error happened on a file function handleFileError(event) { var div = map[event.item.id]; div.addClass("error"); } ``` -------------------------------- ### Load Single Asset with Type Source: https://github.com/createjs/preloadjs/blob/master/examples/MediaGrid.html Loads a single asset using PreloadJS, allowing for specifying the asset type and callback for mapping. This function is used when clicking on an item in the media grid to load its corresponding asset. ```javascript function loadAsset(target) { var div = document.getElementById(target.id); div.innerHTML = ""; var type = target.attributes.getNamedItem("type"); var item = { src: target.id, id: target.id }; if (!type) { preload.loadManifest({path: "../_assets/", manifest: [item]}); } else { item.type = type.value; item.callback = "maps"; preload.loadFile(item, true); } } ``` -------------------------------- ### Custom Image Loader Plugin for PreloadJS (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/CustomLoader.html Defines a custom loader for image files in PreloadJS. It includes static methods for registering the plugin and a handler for creating loader instances. The loader itself handles the image loading process and sends a completion event. ```javascript /** * Custom loader 'class' for PreloadJS. * Allows plugins to provide custom loading logic. */ (function() { /** * Constructor for the CustomLoader. * @param {object} item The load item associated with this loader. * @param {boolean} wait Indicates if the loader should wait for other loaders. * @param {string} type The type of the loader. */ function CustomLoader(item, wait, type) { this.AbstractLoader_constructor(item, wait, type); this.img = null; // Reference to the image element } // Static Plugin Methods /** * Returns an object defining the types this plugin handles and its callback. * @returns {object} */ CustomLoader.getPreloadHandlers = function() { return { types: ["image"], callback: CustomLoader.preloadHandler }; }; /** * Callback function to create a new CustomLoader instance. * @param {object} loadItem The item to be loaded. * @returns {CustomLoader} A new instance of CustomLoader. */ CustomLoader.preloadHandler = function(loadItem) { var loader = new CustomLoader(loadItem); loader.on("complete", CustomLoader.handleComplete, CustomLoader); return loader; }; /** * Handles the completion of the custom loader. * Modifies the loaded image properties. * @param {object} event The event object. */ CustomLoader.handleComplete = function(event) { var img = event.result; img.width = img.height = 200; }; // Loader Methods var p = createjs.extend(CustomLoader, createjs.AbstractLoader); /** * Initiates the loading of the image. */ p.load = function() { this.img = new Image(); this.img.onload = createjs.proxy(this.handleLoad, this); this.img.src = this._item.src; }; /** * Handles the successful loading of the image. */ p.handleLoad = function() { this._result = this.img; this._sendComplete(); }; // Promote CustomLoader to be recognized by PreloadJS window.CustomLoader = createjs.promote(CustomLoader, "AbstractLoader"); })(); ``` -------------------------------- ### Close PreloadJS Queue Source: https://github.com/createjs/preloadjs/blob/master/examples/MediaGrid.html Closes the PreloadJS queue to release resources. This function should be called when the application is shutting down or no longer needs the queue. ```javascript function stop() { if (preload != null) { preload.close(); } } ``` -------------------------------- ### Load Fonts with PreloadJS Source: https://github.com/createjs/preloadjs/blob/master/spikes/FontLoading/testArr.html This snippet shows how to define font configurations and use createjs.FontLoader to load them. It includes event listeners for 'complete', 'progress', 'fileload', and 'error' events. The 'injectCSS' option is set to true to automatically add font styles to the document. ```javascript var fontConfig = { src: [ { src: "local('regul'), url(fonts/regul-book.woff) format('woff')", family: "regul" }, { src: "local('regul'), url(fonts/regul-bold.woff) format('woff')", family: "regul", weight: "bold" } ], type: "font", injectCSS: true }; var loader = new createjs.FontLoader(fontConfig, true); loader.on("complete", function() { result.innerHTML = "COMPLETE"; }); loader.on("progress", function(e) { console.log("progress", e.progress); }); loader.on("fileload", function(e) { console.log("fileload", e.item); }); loader.on("error", function(e) { console.log("error", e); }); loader.load(); ``` -------------------------------- ### Handle File Loaded Event for Various Media Types Source: https://github.com/createjs/preloadjs/blob/master/examples/MediaGrid.html Processes loaded files based on their type (CSS, IMAGE, JAVASCRIPT, JSON, XML, JSONP, SOUND, SVG). It appends scripts/styles to the document, displays images/SVGs, shows raw content for JSON/XML, and plays sounds. ```javascript function handleFileLoaded(event) { var item = event.item; var id = item.id; var result = event.result; var div = document.getElementById(id); if (div == null) { console.log("Could not find DIV:", id, event); return; } switch (item.type) { case createjs.Types.CSS: (document.head || document.getElementsByTagName("head")[0]).appendChild(result); div.innerHTML = ""; break; case createjs.Types.IMAGE: div.innerHTML = ""; result.width = div.clientWidth; result.height = div.clientHeight; div.appendChild(result); break; case createjs.Types.JAVASCRIPT: document.body.appendChild(result); div.innerHTML = ""; break; case createjs.Types.JSON: case createjs.Types.XML: div.innerHTML = ""; break; case createjs.Types.JSONP: div.innerHTML = ""; break; case createjs.Types.SOUND: document.body.appendChild(result); result.play(); div.innerHTML = ""; break; case createjs.Types.SVG: div.innerHTML = ""; div.appendChild(result); break; } div.style.backgroundColor = "#222222"; } ``` -------------------------------- ### JavaScript: EaselJS Animation and Game Loop Source: https://github.com/createjs/preloadjs/blob/master/examples/SpriteSheet.html Handles user input for jumping and updates the game state in a tick loop. It manages the positioning and animation of game elements like the character, ground, and hills for a continuous scrolling effect. ```javascript function handleJumpStart() { grant.gotoAndPlay("jump"); } function tick() { var outside = w + 20; var position = grant.x + runningRate; grant.x = (position >= outside) ? -200 : position; ground.x = (ground.x - 15) % 330; hill.x = (hill.x - 0.8); if (hill.x + 838 <= 0) { hill.x = outside; } hill2.x = (hill2.x - 1.2); if (hill2.x + 633 <= 0) { hill2.x = outside; } stage.update(); } ``` -------------------------------- ### Load Custom Fonts with CreateJS FontLoader Source: https://github.com/createjs/preloadjs/blob/master/spikes/FontLoading/testCSS.html This snippet shows how to define custom fonts using CSS @font-face rules and load them using createjs.FontLoader. The loader is configured with font settings and an event listener to indicate completion. ```css @font-face { font-family: 'regul'; font-style: normal; font-weight: bold; src: local('regul bold'), url('fonts/regul-bold.woff') format('woff'); } @font-face { font-family: 'regul'; font-style: normal; font-weight: normal; src: local('regul book'), url('fonts/regul-book.woff') format('woff'); } ``` ```javascript var fontConfig = { src: foo, type: "fontcss" }; var loader = new createjs.FontLoader(fontConfig, false); loader.on("complete", function() { result.innerHTML = "COMPLETE"; }); loader.load(); ``` -------------------------------- ### Handle File Load Error Source: https://github.com/createjs/preloadjs/blob/master/examples/MediaGrid.html Handles errors that occur during file loading. It identifies the item that failed to load and updates its corresponding HTML element to display an error message and apply an 'error' class to visually indicate the failure. ```javascript function handleError(event) { var item = event.data; var div = document.getElementById(item.id); if (div != null) { div.innerHTML = ""; div.className = "gridBox error"; } } ``` -------------------------------- ### Chaining Multiple PreloadJS Queues Sequentially Source: https://context7.com/createjs/preloadjs/llms.txt Demonstrates how to chain multiple createjs.LoadQueue instances to load assets in a specific sequence. By assigning one queue to the `next` property of another, you create a dependency, ensuring the second queue only starts loading after the first one completes. ```javascript var queue1 = new createjs.LoadQueue(); var queue2 = new createjs.LoadQueue(); queue1.next = queue2; queue1.loadManifest(["critical-file-1.js", "critical-file-2.js"]); queue2.loadManifest(["secondary-file-1.png", "secondary-file-2.png"]); queue1.on("complete", function() { console.log("Queue 1 complete"); }); queue2.on("complete", function() { console.log("Queue 2 complete - all assets loaded"); }); ``` -------------------------------- ### Define and Install PreloadJS Plugin for Image Loading Source: https://github.com/createjs/preloadjs/blob/master/examples/PluginSample.html This JavaScript code defines a PreloadJS plugin that intercepts 'image' type load items. It extracts an ID from the item's source, finds the corresponding HTML image element by ID, and assigns it to the item's 'tag' property. This allows PreloadJS to use the existing image element for loading and display. ```javascript var preload; function init() { // Create a new queue. preload = new createjs.LoadQueue(false, "../\_assets/art/"); // Use this instead to favor xhr loading //preload = new createjs.LoadQueue(true, "assets/"); var plugin = { getPreloadHandlers: function () { return { types: ["image"], callback: function (item) { var id = item.src.toLowerCase().split("/").pop().split(".")[0]; item.tag = document.getElementById(id); } }; } } preload.installPlugin(plugin); preload.loadManifest([ "Texas.jpg", "BlueBird.png", "Nepal.jpg", "Autumn.png" //NOTE: Will not display ]); } ``` -------------------------------- ### Retrieve Loaded Assets and Results in PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Shows how to access loaded assets and their results using the getResult() and getItem() methods. It covers retrieving by ID, getting raw results, accessing LoadItem metadata, and fetching all loaded items with their results. ```javascript var queue = new createjs.LoadQueue(); queue.loadManifest([ {id: "image", src: "photo.jpg"}, {id: "data", src: "config.json"} ]); queue.on("complete", function() { // Get result by ID var image = queue.getResult("image"); document.body.appendChild(image); // Get raw result (unprocessed) var rawJSON = queue.getResult("data", true); // Get LoadItem metadata var item = queue.getItem("image"); console.log("Image source:", item.src); // Get all loaded items var allItems = queue.getItems(true); allItems.forEach(function(entry) { console.log("Item:", entry.item.id); console.log("Result:", entry.result); }); }); ``` -------------------------------- ### Pause and Resume Asset Loading in PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Illustrates how to control the asset loading process by pausing and resuming the LoadQueue. This is useful for managing loading bursts or user interactions. It also shows how to load a file without starting immediately and initiate loading manually. ```javascript var queue = new createjs.LoadQueue(); queue.loadManifest([ "file1.png", "file2.png", "file3.png", "file4.png" ]); // Pause the queue setTimeout(function() { queue.setPaused(true); console.log("Queue paused"); }, 100); // Resume after 2 seconds setTimeout(function() { queue.setPaused(false); console.log("Queue resumed"); }, 2000); // Load without starting immediately queue.loadFile({src: "file5.png"}, false); // Start loading manually queue.load(); ``` -------------------------------- ### Handle Loading Errors with stopOnError in PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Explains the 'stopOnError' property for controlling the LoadQueue's behavior when errors occur. If true, loading halts on the first error; otherwise, it continues processing subsequent files. Includes examples of error and completion event handlers. ```javascript var queue = new createjs.LoadQueue(); // Stop queue on first error (default is false) queue.stopOnError = true; queue.on("error", handleError); queue.on("complete", handleComplete); queue.loadManifest([ "valid-file.png", "missing-file.png", // This will cause an error "another-file.png" // Won't load if stopOnError = true ]); function handleError(event) { console.error("Load error:", event.data); console.error("Failed item:", event.item); if (queue.stopOnError) { console.log("Queue paused due to error"); // Optionally resume // queue.setPaused(false); } } function handleComplete() { console.log("All files loaded successfully"); } ``` -------------------------------- ### Instantiate Preloader with Default Namespace Source: https://github.com/createjs/preloadjs/blob/master/README_CREATEJS_NAMESPACE.txt Demonstrates the default method for instantiating a PreloadJS preloader by accessing it through the 'createjs' namespace. ```javascript var bar = new createjs.LoadQueue(); ``` -------------------------------- ### Shortcut createjs Namespace with a Variable Source: https://github.com/createjs/preloadjs/blob/master/README_CREATEJS_NAMESPACE.txt Shows how to create a shortcut variable (e.g., 'c') that references the 'createjs' namespace, simplifying instantiation of CreateJS objects like Shape. ```javascript ``` -------------------------------- ### Load Multiple Files with Progress and Completion Handling (PreloadJS) Source: https://context7.com/createjs/preloadjs/llms.txt Shows how to load multiple assets from a manifest array using createjs.LoadQueue. It includes event listeners for 'progress', 'complete', and 'error' to provide feedback and handle results. Loaded items can be retrieved by their ID. ```javascript var queue = new createjs.LoadQueue(); queue.on("progress", handleProgress); queue.on("complete", handleComplete); queue.on("error", handleError); queue.loadManifest([ {id: "logo", src: "images/logo.png"}, {id: "config", src: "data/config.json"}, {id: "stylesheet", src: "css/styles.css"}, {id: "script", src: "js/app.js"} ]); function handleProgress(event) { var percentLoaded = Math.round(queue.progress * 100); console.log("Loading: " + percentLoaded + "%"); } function handleComplete(event) { console.log("All files loaded!"); var image = queue.getResult("logo"); var config = queue.getResult("config"); document.body.appendChild(image); console.log("Config data:", config); } function handleError(event) { console.error("Error loading file:", event.data); } ``` -------------------------------- ### Monitor Individual File Progress in PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Details how to track the loading progress of individual files using 'filestart', 'fileprogress', and 'fileload' events. This allows for granular feedback to the user during asset loading. ```javascript var queue = new createjs.LoadQueue(); queue.on("filestart", handleFileStart); queue.on("fileprogress", handleFileProgress); queue.on("fileload", handleFileLoad); queue.loadManifest([ "large-file-1.jpg", "large-file-2.jpg", "large-file-3.jpg" ]); function handleFileStart(event) { console.log("Started loading:", event.item.src); } function handleFileProgress(event) { var percentComplete = Math.round(event.progress * 100); console.log(event.item.src + ": " + percentComplete + "% "); } function handleFileLoad(event) { console.log("Completed:", event.item.src); } ``` -------------------------------- ### Load Font Configuration (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/FontLoader.html Defines a function to load fonts using PreloadJS. It accepts a configuration object, creates a FontLoader instance, and initiates the loading process. The 'complete' event is handled to display a success message. ```javascript function init() { if (window.top != window) { document.getElementById("header").style.display = "none"; } } function loadFonts(config) { var loader = new createjs.FontLoader(config, true); loader.on("complete", handleLoad); loader.load(); } function handleLoad() { var div = document.createElement("div"); div.className = "resultItem"; div.innerHTML = "COMPLETE"; result.appendChild(div); } ``` -------------------------------- ### Configure Base Path and Path Prefixes in PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Demonstrates how to set a base path for assets in the LoadQueue constructor or use the 'path' property within manifests. This ensures all relative URLs are correctly prefixed, simplifying asset management. Absolute URLs are not affected by path prefixes. ```javascript var queue = new createjs.LoadQueue(true, "assets/"); queue.loadManifest([ "images/logo.png", // Loads from: assets/images/logo.png "data/config.json", // Loads from: assets/data/config.json "http://cdn.com/file.js" // Absolute URLs are not prefixed ]); queue.loadManifest({ path: "game/", manifest: [ "player.png", // Loads from: assets/game/player.png "enemy.png" // Loads from: assets/game/enemy.png ] }); ``` -------------------------------- ### Specify File Types During Loading with PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Demonstrates how to explicitly define the type of files being loaded using createjs.LoadQueue, which is useful for assets without standard file extensions or for specifying data formats like BINARY, JSON, or JSONP. This ensures correct parsing and handling of the loaded data. ```javascript var queue = new createjs.LoadQueue(); queue.loadManifest([ {src: "https://cdn.example.com/asset?id=12345", type: createjs.Types.IMAGE}, {id: "binaryData", src: "data/file.bin", type: createjs.Types.BINARY}, {id: "data", src: "api/data", type: createjs.Types.JSON}, {id: "external", src: "https://api.example.com/data.js", type: createjs.Types.JSONP, callback: "myCallback"} ]); queue.on("fileload", function(event) { if (event.item.id === "binaryData") { var buffer = event.result; console.log("Binary data size:", buffer.byteLength); } }); ``` -------------------------------- ### Load Single Image File with PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Demonstrates how to load a single image file using createjs.LoadQueue. It sets up a 'fileload' event listener to append the loaded image to the document body. The LoadQueue defaults to using XHR for loading. ```javascript var queue = new createjs.LoadQueue(true); queue.on("fileload", handleFileComplete); queue.loadFile('https://example.com/images/logo.png'); function handleFileComplete(event) { var image = event.result; document.body.appendChild(image); } ``` -------------------------------- ### Remove createjs Namespace by Assigning to Window Source: https://github.com/createjs/preloadjs/blob/master/README_CREATEJS_NAMESPACE.txt Illustrates how to remove the 'createjs' namespace by assigning the 'createjs' variable to 'window' before loading the libraries, ensuring compatibility with older content. ```javascript ``` -------------------------------- ### Load Assets from a JSON Manifest File (PreloadJS) Source: https://context7.com/createjs/preloadjs/llms.txt Illustrates loading assets defined within an external JSON manifest file using createjs.LoadQueue. The 'fileload' event handler processes individual loaded items, and the 'complete' event signifies all assets have been loaded. Supports different file types based on item properties. ```javascript var queue = new createjs.LoadQueue(); queue.on("fileload", handleFileLoad); queue.on("complete", handleComplete); queue.loadManifest("manifest.json"); function handleFileLoad(event) { var item = event.item; var result = event.result; console.log("Loaded:", item.id || item.src); if (item.type === createjs.Types.IMAGE) { document.getElementById("container").appendChild(result); } } function handleComplete() { console.log("Manifest and all files loaded"); } ``` -------------------------------- ### Control Load Order and Concurrency with PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Explains how to manage asset loading order and the number of simultaneous connections using createjs.LoadQueue. It shows setting `setMaxConnections` and how `maintainScriptOrder` (true by default) affects script loading, while other assets can load in parallel. ```javascript var queue = new createjs.LoadQueue(); queue.setMaxConnections(5); queue.maintainScriptOrder = true; queue.loadManifest([ "script1.js", "script2.js", "image1.png", "image2.png", {src: "data.json", maintainOrder: true}, "script3.js" ]); queue.on("fileload", function(event) { console.log("Loaded:", event.item.src); }); ``` -------------------------------- ### Reset and Reload Assets with PreloadJS Queue Source: https://context7.com/createjs/preloadjs/llms.txt Illustrates how to reset and reload all assets in a createjs.LoadQueue. Resetting the queue clears loaded results while retaining the manifest items. Calling `.load()` again re-initiates the loading process for all items in the queue. ```javascript var queue = new createjs.LoadQueue(); queue.loadManifest([ "file1.png", "file2.png", "file3.png" ]); queue.on("complete", function() { console.log("First load complete"); queue.reset(); queue.load(); }); queue.on("complete", function() { console.log("Reload complete"); }); ``` -------------------------------- ### Registering Custom Loaders with PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Explains how to register a custom loader function with createjs.LoadQueue to handle specific file types. The custom loader must extend `createjs.AbstractLoader` and implement `canLoadItem()` to determine if it can handle the item. This allows for extended functionality beyond built-in types. ```javascript var queue = new createjs.LoadQueue(); queue.registerLoader(MyCustomLoader); function MyCustomLoader(loadItem, preferXHR) { this.AbstractLoader_constructor(loadItem, preferXHR, createjs.Types.TEXT); } MyCustomLoader.canLoadItem = function(item) { return item.type === "custom" || item.ext === "cst"; }; var p = createjs.extend(MyCustomLoader, createjs.AbstractLoader); p.load = function() { // Custom loading logic }; ``` -------------------------------- ### Retrieve Raw vs. Processed Results from PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Demonstrates how to retrieve both raw and processed results for various file types from a createjs.LoadQueue. The `getResult()` method, when called with `true` as the second argument, returns the raw data (e.g., JSON string, XML string). Otherwise, it returns the processed data (e.g., parsed JSON object, XML document). ```javascript var queue = new createjs.LoadQueue(); queue.loadManifest([ {id: "json", src: "data.json"}, {id: "xml", src: "data.xml"}, {id: "text", src: "data.txt"} ]); queue.on("complete", function() { var jsonData = queue.getResult("json"); console.log("Parsed JSON:", jsonData); var rawJSON = queue.getResult("json", true); console.log("Raw JSON string:", rawJSON); var xmlDoc = queue.getResult("xml"); var rawXML = queue.getResult("xml", true); }); ``` -------------------------------- ### Load Manual Font List (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/FontLoader.html Initiates font loading using a manually defined list of font sources and their corresponding CSS properties. This method allows for precise control over font families, weights, and local fallbacks. ```javascript function loadManualList() { loadFonts({ src: [ { src: "local('regul'), url(../_assets/fonts/regul-book.woff) format('woff')", family: "regul" }, { src: "local('regul'), url(../_assets/fonts/regul-bold.woff) format('woff')", family: "regul", weight: "bold" } ], type: "font", injectCSS: true }); return false; } ``` -------------------------------- ### Load Font Source (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/FontLoader.html Loads a single font file directly from a specified source URL. This is a straightforward approach for loading a single font asset. ```javascript function loadSrc() { loadFonts({ src: "../_assets/fonts/regul-bold.woff" }); return false; } ``` -------------------------------- ### Load Font Source List (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/FontLoader.html Loads multiple font files from a list of source URLs. PreloadJS will attempt to load each font in the provided array. ```javascript function loadSrcList() { loadFonts({ src: [ "../_assets/fonts/regul-book.woff", "../_assets/fonts/regul-bold.woff" ], type: "font" }); return false; } ``` -------------------------------- ### Loading Sprite Sheets with PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Shows how to load sprite sheets using createjs.LoadQueue with the SPRITESHEET type. This allows for easy integration of animated sprites into CreateJS applications. The `type` property is set to `createjs.Types.SPRITESHEET` for automatic processing. ```javascript var queue = new createjs.LoadQueue(); queue.on("complete", handleComplete); queue.loadFile({ id: "spritesheet", src: "sprites/player.json", type: createjs.Types.SPRITESHEET }); function handleComplete() { var spriteSheet = queue.getResult("spritesheet"); var sprite = new createjs.Sprite(spriteSheet, "walk"); stage.addChild(sprite); } ``` -------------------------------- ### Enable CORS for External Image Loading with PreloadJS Source: https://context7.com/createjs/preloadjs/llms.txt Demonstrates how to enable Cross-Origin Resource Sharing (CORS) for images loaded from external domains using createjs.LoadQueue. This is crucial for security and functionality when loading assets from different origins. The `crossOrigin` property can be set globally or per item. ```javascript var queue = new createjs.LoadQueue(true, null, "Anonymous"); queue.loadManifest([ { id: "externalImage", src: "https://external-cdn.com/image.png", crossOrigin: "Anonymous" }, { id: "localImage", src: "local-image.png" } ]); queue.on("fileload", function(event) { if (event.item.id === "externalImage") { var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); ctx.drawImage(event.result, 0, 0); } }); ``` -------------------------------- ### Remove Assets from PreloadJS Queue Source: https://context7.com/createjs/preloadjs/llms.txt Explains how to remove individual assets or multiple assets from the PreloadJS queue using their ID or source path. It also covers the method to remove all items from the queue. ```javascript var queue = new createjs.LoadQueue(); queue.loadManifest([ {id: "image1", src: "img1.png"}, {id: "image2", src: "img2.png"}, {id: "image3", src: "img3.png"} ]); // Remove single item by ID queue.remove("image2"); // Remove multiple items queue.remove(["image1", "img3.png"]); // By ID or src // Remove all items queue.removeAll(); ``` -------------------------------- ### Load Google Fonts CSS (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/FontLoader.html Loads fonts from Google Fonts by specifying the Google Fonts CSS URL. This allows easy integration of web fonts hosted by Google. ```javascript function loadGoogleFonts() { loadFonts({ src: "https://fonts.googleapis.com/css?family=Roboto:400,700,400italic,700italic", type: "fontcss" }); return false; } ``` -------------------------------- ### Load Font CSS (JavaScript) Source: https://github.com/createjs/preloadjs/blob/master/examples/FontLoader.html Loads font definitions from a CSS file. PreloadJS will parse the CSS and load the specified font resources. ```javascript function loadCSS() { loadFonts({ src: foo, type: "fontcss" }); return false; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.