Convert image to base64
1
2
<img id="image" src="/image.png">
<canvas id="canvas"></canvas>
1
2
3
4
5
6
7
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const image = document.getElementById('image');
ctx.drawImage(image, 0, 0);
console.log(canvas.toDataURL()); //return base64
Convert base64 to image
1
const img = await readAsImage(signData);
1
2
3
4
5
6
7
8
9
10
11
12
13
export function readAsImage(src) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
if (src instanceof Blob) {
const url = window.URL.createObjectURL(src);
img.src = url;
} else {
img.src = src;
}
});
}