notlmn / image-promise

Load one or more images, return a promise. <1KB, for the browser, no dependencies.

Home Page:https://npm.im/image-promise

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

image-promise gzipped size Travis build status npm version npm downloads

Load one or more images, return a promise. Only 0.4KB, for the browser, no dependencies.

It can be used in two ways:

  • given a URL, generate an <img> and wait for it to load:

     loadImage('img.jpg').then(/*it's loaded!*/)
  • given an <img>, wait for it to load:

     const img = document.querySelector('img.my-image');
     loadImage(img).then(/*it's loaded!*/)

Install

Pick your favorite:

<script src="dist/image-promise.min.js"></script>
npm install --save image-promise
var loadImage = require('image-promise');
import loadImage from 'image-promise';

Usage

One image

loadImage(image) will return a Promise that resolves when the image load, or fails when the image

var image = 'cat.jpg';
// var image = $('img')[0]; // it can also be an <img> element

loadImage(image)
.then(function (img) {
	ctx.drawImage(img, 0, 0, 10, 10);
})
.catch(function () {
	console.error('Image failed to load :(');
});

Multiple images

image-promise can load multiple images at a time

var images = ['cat.jpg', 'dog.jpg'];
// var images = $('img'); // it can also be a jQuery object
// var images = document.querySelectorAll('img'); // or a NodeList

loadImage(images)
.then(function (allImgs) {
	console.log(allImgs.length, 'images loaded!', allImgs);
})
.catch(function (err) {
	console.error('One or more images have failed to load :(');
	console.error(err.errored);
	console.info('But these loaded fine:');
	console.info(err.loaded);
});

Set custom attributes

loadImage(image, attributes) lets you pass as the second argument an object of attributes you want to assign to the image element before it starts loading.

This is useful for example when you need CORS enabled image, where you need to set the attribute crossorigin="anonymous" before the image starts downloading.

var image = 'http://catpics.com/cat.jpg';

loadImage(image, { crossorigin: 'anonymous' })
.then(function (img) {
	ctx.drawImage(img, 0, 0, 10, 10);

	// now you can do this
	canvas.toDataURL('image/png')
})
.catch(function () {
	console.error('Image failed to load :(');
});

Dependencies

None! But you need to polyfill window.Promise in IE11 and lower.

License

MIT © Federico Brigante

About

Load one or more images, return a promise. <1KB, for the browser, no dependencies.

https://npm.im/image-promise


Languages

Language:JavaScript 98.0%Language:HTML 2.0%