Last active
March 2, 2017 16:13
-
-
Save pixelbreaker/3ffb6815d73b603c8e34 to your computer and use it in GitHub Desktop.
PouchDB image cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ImageCache from './image-cache.js' | |
var imageCache = new ImageCache(); | |
var img = $(el).find('img'); | |
imageCache.loadImage(img[0], img.attr('src')); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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