Skip to content

Instantly share code, notes, and snippets.

@pixelbreaker

pixelbreaker/example.js

Last active Mar 2, 2017
Embed
What would you like to do?
PouchDB image cache
import ImageCache from './image-cache.js'
var imageCache = new ImageCache();
var img = $(el).find('img');
imageCache.loadImage(img[0], img.attr('src'));
import PouchDB from 'pouchdb/lib/index-browser'; // USE BROWSER VERSION
class ImageCache {
constructor() {
this._db = new PouchDB('offline-tiles');
this._canvas = document.createElement('canvas');
}
loadImage(img, imgUrl) {
this._db.get(imgUrl, false, this.onCacheLookup(img,imgUrl));
}
onCacheLookup (img, imgUrl) {
return (err,data) => {
if (data) { // something exists in the cache
img.src = data.dataUrl; // data.dataUrl is already a base64-encoded PNG image.
} else { // load the image
img.onload = this.saveTile(imgUrl);
img.crossOrigin = 'Anonymous';
img.src = imgUrl;
}
};
}
saveTile(tileUrl) {
return function(ev) {
var img = ev.target;
this._canvas.width = img.naturalWidth || img.width;
this._canvas.height = img.naturalHeight || img.height;
var context = this._canvas.getContext('2d');
context.drawImage(img, 0, 0);
var dataUrl = this._canvas.toDataURL('image/png');
var doc = {dataUrl: dataUrl, timestamp: Date.now()};
this._db.put(doc, tileUrl, doc.timestamp);
}.bind(this);
}
}
export default ImageCache;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.