JSFiddle - React, Tailwind, and code Playground
by Hugo Lopez
HTML
<img id="myImage" /> left is is html data uri. <br />
Next 2 are svg data uri. Stand alone <a href="http://fiddle.jshell.net/hugolpz/xGUsu/96/show/light/">html page</a>
<svg></svg>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="//d3js.org/topojson.v0.min.js"></script>
<script>
var width = 960,
height = 500,
svg = d3.select("svg")
.attr("width", width)
.attr("height", height);
svg.append("image")
.attr("xlink:href", "http://fiddle.jshell.net/img/logo.png")
.attr("width", width)
.attr("height", height)
.attr("class", "bg1")
.attr("fill", "#AAA");
svg.append("image")
.attr("xlink:href", "http://fiddle.jshell.net/img/logo.png")
.attr("width", width / 2)
.attr("height", height / 2)
.attr("class", "bg2")
.attr("background-color", "#333");
</script>
CSS
body {
background: grey;
}
#myImage {
padding: 1em;
background: #4072b4;
}
JavaScript
var converterEngine = function (input) { // fn BLOB => Binary => Base64 ?
var uInt8Array = new Uint8Array(input),
i = uInt8Array.length;
var biStr = []; //new Array(i);
while (i--) {
biStr[i] = String.fromCharCode(uInt8Array[i]);
}
var base64 = window.btoa(biStr.join(''));
console.log("2. base64 produced >>> " + base64); // print-check conversion result
return base64;
};
var getImageBase64 = function (url, callback) {
// 1. Loading file from url:
var xhr = new XMLHttpRequest(url);
xhr.open('GET', url, true); // url is the url of a PNG image.
xhr.responseType = 'arraybuffer';
xhr.callback = callback;
xhr.onload = function (e) {
if (this.status == 200) { // 2. When loaded, do:
console.log("1:Loaded response >>> " + this.response); // print-check xhr response
var imgBase64 = converterEngine(this.response); // convert BLOB to base64
this.callback(imgBase64); //execute callback function with data
}
};
xhr.send();
};
//HTML part
getImageBase64('http://fiddle.jshell.net/img/logo.png', function (data) {
$("#myImage").attr("src", "data:image/png;base64," + data); // inject data:image in DOM
// data:[<mime type>][;charset=<charset>][;base64],<encoded data>
})
//SVG part
getImageBase64('http://fiddle.jshell.net/img/logo.png', function (data) {
d3.selectAll("image")
.attr("width", width / 2) // resizing, just to see
.attr("href", "data:image/png;base64," + data); // replace link by data URI
})