Load image from external url
by Ved prakash
HTML
<input type="url" id="url">
<button id="getImageFromURL">get</button>
<div>
<figure id="output"></figure>
<p id="base64"></p>
</div>
CSS
#output {
width: 200px;
height: 200px;
background-repeat: no-repeat;
background-size: contain;
}
JavaScript
const output = document.getElementById('output');
const base64 = document.getElementById('base64');
document.getElementById('getImageFromURL').addEventListener('click', () => {
const url = document.getElementById('url').value;
const image = new Image();
image.src = url;
// CORSが許可されていない場合はエラーになる
// [Tainted canvases may not be exported.]のエラー対策
image.crossOrigin = 'anonymous';
image.onload = () => {
const canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
canvas.getContext('2d').drawImage(image, 0, 0);
const src = canvas.toDataURL('image/png');
output.style.backgroundImage = `url(${src})`;
base64.innerText = src;
};
image.onerror = e => {
console.log(e);
base64.innerText = 'hello';
};
});