├── .gitignore ├── LICENSE ├── README.md ├── index.js └── package.json /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (http://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Chang Yan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # canvas-image-cache 2 | > :sun_with_face: A Promise-based utility to cache all the loaded images in canvas. 3 | 4 | ## Installation: 5 | 6 | ``` 7 | npm install --save canvas-image-cache 8 | ``` 9 | 10 | ## Usage 11 | ```js 12 | import createImageCache from 'canvas-image-cache' 13 | 14 | let imageCache = createImageCache() 15 | 16 | const dict = { 17 | ship: './ship.png', 18 | universe: './universe.png', 19 | asteroid: './asteroid.png', 20 | fire: './fire.png' 21 | } 22 | 23 | imageCache.loadImages(dict) 24 | 25 | // provide a callback after loading 26 | imageCache.imagesOnload(() => { 27 | console.log('All images are loaded!') 28 | 29 | // the typical use scenario is to start the game loop and begin rendering the canvas 30 | gameloop() 31 | }) 32 | ``` 33 | 34 | And in your gameloop, if you want to render the image in your dict, you don't need to instantiate an `Image` instance again and wait until it's loaded. It's already stored in the `imageCache`: 35 | 36 | ```js 37 | // for instance, you want to draw ship 38 | function renderShip(context, imageCache) { 39 | const ship = imageCache.getImages().find(i => i.name === 'ship') 40 | 41 | context.drawImage(ship, dx, dy) 42 | } 43 | 44 | // or you could render them all! 45 | function renderAll(context, imageCache) { 46 | imageCache.getImages().forEach(item => { 47 | context.drawImage(item.img, dx, dy) 48 | }) 49 | } 50 | ``` 51 | 52 | ## Background 53 | 54 | Think of the typical way to render an image in canvas, you could do the followings: 55 | 56 | ```js 57 | function drawImageFromUrl(url) { 58 | let img = new Image() 59 | img.src = url 60 | 61 | img.onload = () => { 62 | // you have to wait until the image has been fully loaded 63 | context.drawImage(img, dx, dy) 64 | } 65 | } 66 | ``` 67 | 68 | This works fine in most of the cases. However, if you are in game development, say, you have a game loop function that repeatedly renders every image in 30 milliseconds. Between when you `let img = new Image()` and `img.onload`, your canvas is totally blank, which could cause a flickering/blinking issue. 69 | 70 | For more details, see https://stackoverflow.com/questions/17261080/html5-canvas-blinking-on-drawing 71 | 72 | And this utility fixes the issue mentioned above. The general idea is to load all the needed images in the game and cache them before the gameloop begins. And then you could leverage the exsisted images instances rather than creating a new one in each rendering. 73 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | function createImageCache() { 2 | let images = [] 3 | let imgPromises = [] 4 | let hasFinishedLoading = false 5 | 6 | function loadSingleImage(name, src) { 7 | imgPromises.push(new Promise((resolve, reject) => { 8 | let img = new Image() 9 | img.src = src 10 | 11 | hasFinishedLoading = false 12 | 13 | try { 14 | img.onload = () => { 15 | images.push({ name, img }) 16 | hasFinishedLoading = true 17 | 18 | resolve({ 19 | name, 20 | img 21 | }) 22 | } 23 | } catch (err) { 24 | reject(err) 25 | } 26 | })) 27 | } 28 | 29 | function loadImages(dict) { 30 | Object.keys(dict).forEach(key => { 31 | loadSingleImage(key, dict[key]) 32 | }) 33 | } 34 | 35 | function imagesOnload(callback) { 36 | // callback(arr) 37 | Promise.all(imgPromises).then(callback) 38 | } 39 | 40 | function getImages() { 41 | if (hasFinishedLoading) { 42 | return images 43 | } else { 44 | throw console.warn('Image hasn\'t finished loading. You may use getImages() in the callback of the imagesOnLoad function.') 45 | } 46 | } 47 | 48 | return { 49 | loadSingleImage, 50 | loadImages, 51 | getImages, 52 | imagesOnLoad 53 | } 54 | } 55 | 56 | module.exports = createImageCache 57 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "canvas-image-cache", 3 | "version": "0.0.1", 4 | "description": "An utility to cache all the loaded images in canvas", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "repository": { 10 | "type": "git", 11 | "url": "git+https://github.com/thomasyimgit/canvas-image-cache.git" 12 | }, 13 | "keywords": [ 14 | "cache", 15 | "image", 16 | "canvas", 17 | "html5", 18 | "game", 19 | "flicker", 20 | "blink" 21 | ], 22 | "author": "Chang Yan", 23 | "license": "MIT", 24 | "bugs": { 25 | "url": "https://github.com/thomasyimgit/canvas-image-cache/issues" 26 | }, 27 | "homepage": "https://github.com/thomasyimgit/canvas-image-cache#readme" 28 | } 29 | --------------------------------------------------------------------------------