Created
December 6, 2016 08:01
-
-
Save MeTe-30/9f853178f8beb65c42afa033e91bead3 to your computer and use it in GitHub Desktop.
Convert image to Base64, dataUrl by Canvas & BLOB | Javscript
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
function toDataUrl(url, callback) { | |
var xhr = new XMLHttpRequest(); | |
xhr.responseType = 'blob'; | |
xhr.onload = function () { | |
var reader = new FileReader(); | |
reader.onloadend = function () { | |
callback(reader.result); | |
} | |
reader.readAsDataURL(xhr.response); | |
}; | |
xhr.open('GET', url); | |
xhr.send(); | |
} | |
function toDataUrl(url, callback) { | |
var image = new Image(); | |
image.setAttribute('crossOrigin', 'anonymous'); | |
image.onload = function () { | |
var canvas = document.createElement('canvas'); | |
canvas.width = this.naturalWidth; | |
canvas.height = this.naturalHeight; | |
canvas.getContext('2d').drawImage(this, 0, 0, canvas.width, canvas.height); | |
callback(canvas.toDataURL('image/png', 1)); | |
}; | |
image.src = url; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment