JSFiddle - React, Tailwind, and code Playground
by darul75
HTML
<div>TARGET IMG (DATA URI) <img id="targetImg" /></div>
JavaScript
var targetImg = document.getElementById("targetImg");
FetchImageAsBlob('https://developer.cdn.mozilla.net/static/img/logo_sprite.7d36c4a1422b.svg', function(err, img) {
if (err) {
console.log(err);
return;
}
var canvas = document.createElement('canvas'),
ctx = canvas.getContext('2d');
// init
canvas.width = img.width;
canvas.height = img.height;
// fill with image
ctx.drawImage(img, 0, 0);
var imgDataURI = canvas.toDataURL();
targetImg.src = imgDataURI;
});
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
function FetchImageAsBlob(url, cb) {
var req = createCORSRequest('GET', url);
req.onload = function() {
var img = new Image();
img.onload = function() {
URL.revokeObjectURL(this.src);
cb(null, img);
};
img.src = URL.createObjectURL(req.response);
};
req.onerror = function(e) {
cb(e);
};
req.responseType = 'blob';
req.send();
}