From be918bbaef38043845029361c33d40ca22a9c36c Mon Sep 17 00:00:00 2001 From: Patrick Keenan Date: Fri, 27 May 2016 12:32:31 -0700 Subject: [PATCH] cross-domain and url getColorFromUrl gets color from an image served from the same domain, so you don't have to create an image element to get the color. getColorAsync gets the color from another domain that has an open cross-domain policy. --- async.html | 42 ++++++++++++++++++++++++++++++++++++++++++ src/color-thief.js | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 86 insertions(+) create mode 100755 async.html diff --git a/async.html b/async.html new file mode 100755 index 0000000..e118fff --- /dev/null +++ b/async.html @@ -0,0 +1,42 @@ + + + + + + + + + + +
+
+
+ +

Same domain, image by url

+
+ +
+ +

Cross-domain, image by url

+
+ + +
+ + + + + + diff --git a/src/color-thief.js b/src/color-thief.js index 5be0250..53a5f7f 100644 --- a/src/color-thief.js +++ b/src/color-thief.js @@ -137,6 +137,50 @@ ColorThief.prototype.getPalette = function(sourceImage, colorCount, quality) { return palette; }; +ColorThief.prototype.getColorFromUrl = function(imageUrl, callback, quality) { + sourceImage = document.createElement("img"); + var thief = this; + sourceImage.addEventListener('load' , function(){ + var palette = thief.getPalette(sourceImage, 5, quality); + var dominantColor = palette[0]; + callback(dominantColor, imageUrl); + }); + sourceImage.src = imageUrl +}; + + +ColorThief.prototype.getImageData = function(imageUrl, callback) { + xhr = new XMLHttpRequest(); + xhr.open('GET', imageUrl, true); + xhr.responseType = 'arraybuffer' + xhr.onload = function(e) { + if (this.status == 200) { + uInt8Array = new Uint8Array(this.response) + i = uInt8Array.length + binaryString = new Array(i); + for (var i = 0; i < uInt8Array.length; i++){ + binaryString[i] = String.fromCharCode(uInt8Array[i]) + } + data = binaryString.join('') + base64 = window.btoa(data) + callback ("data:image/png;base64,"+base64) + } + } + xhr.send(); +}; + +ColorThief.prototype.getColorAsync = function(imageUrl, callback, quality) { + var thief = this; + this.getImageData(imageUrl, function(imageData){ + sourceImage = document.createElement("img"); + sourceImage.addEventListener('load' , function(){ + var palette = thief.getPalette(sourceImage, 5, quality); + var dominantColor = palette[0]; + callback(dominantColor, this); + }); + sourceImage.src = imageData; + }); +};