Merge pull request #103 from patrickkeenan/master

cross-domain and url
This commit is contained in:
Lokesh Dhakar
2016-11-06 15:35:24 -08:00
committed by GitHub
2 changed files with 86 additions and 0 deletions

42
async.html Executable file
View File

@@ -0,0 +1,42 @@
<!doctype html>
<html class="no-js" lang="en">
<head>
<script src="examples/js/jquery.js"></script>
<script src="src/color-thief.js"></script>
</head>
<body>
<header>
<div class="container">
<div id="samedomain">
<img src="examples/img/photo1.jpg" width="400" height="200">
<h1>Same domain, image by url</h1>
</div>
<script type="text/javascript">
var colorThief = new ColorThief();
colorSync = colorThief.getColorFromUrl("examples/img/photo1.jpg", function(color){
$('#samedomain').css('background-color','rgb('+color[0]+','+color[1]+','+color[2]+')')
console.log('url',color)
});
</script>
<div id="crossdomain">
<img width="400" height="200">
<h1>Cross-domain, image by url</h1>
</div>
<script type="text/javascript">
colorThief.getColorAsync("http://lorempixel.com/400/200/",function(color, element){
$('#crossdomain').css('background-color','rgb('+color[0]+','+color[1]+','+color[2]+')')
$('#crossdomain img').attr('src',element.src)
console.log('async', color, element.src)
});
</script>
</div>
</body>
</html>

View File

@@ -138,6 +138,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;
});
};