I'm trying to compare two svg images for equality. To do this I first convert them to Canvas (using this post Drawing an SVG file on a HTML5 canvas as a guide). Then I extract the pixel data arrays from each Canvas and determine if each element of both arrays are equal.
This works in the general case, but the first time data is extracted from a Canvas in a particular instance of a web page, it returns an array containing only zeros.
For instance, the code below contains some inline js. When an html file containing only this code is first opened in a browser (I've tried firefox and chromium) an array containing only zeros is printed to the console. However if the page is refreshed, the desired array (one with 255 in all the blue and alpha positions) is printed to the console.
Can anyone tell me why this happens and if there's any way to get around it so that the desired array is always returned?
<script>
// create canvas
let can = document.createElement('canvas');
// get canvas context
let ctx = can.getContext('2d');
// svg markup
let xml = '<svg viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg" width="20" height="20" data-reactroot=""><rect x="0" y="0" width="20" height="20" fill="rgba(0, 0, 255, 1)"></rect></svg>';
// make it base64
let svg64 = btoa(xml);
// header
let b64Start = 'data:image/svg+xml;base64,';
// prepend header
let image64 = b64Start + svg64;
// set it as the source of a img element
let img = document.createElement('img');
img.src = image64;
// draw the image onto the canvas
ctx.drawImage(img, 0, 0);
// extract pixel data from context
let data = ctx.getImageData(0, 0, 20, 20).data;
// print pixel data somewhere we can see it
console.log(data);
</script>