I have 2 imageData objects which I get from the same canvas through the same context.
But when comparing them, they are not equal when I would think they would be as they should contain the same data:
var canv = document.createElement("canvas");
canv.setAttribute('width', 300);
canv.setAttribute('height', 300);
var context = canv.getContext('2d');
context.fillStyle = "#ff0000";
context.fillRect(0, 0, 300, 300);
var imageData = context.getImageData(0, 0, 300, 300);
var imageData2 = context.getImageData(0, 0, 300, 300);
if (imageData == imageData2) {
console.log("Test1: same");
} else {
console.log("Test1: different");
}
if (imageData.data == imageData2.data) {
console.log("Test2: same");
} else {
console.log("Test2: different");
}
if (imageData == imageData) {
console.log("Test3: same");
} else {
console.log("Test3: different");
}
if (imageData.data == imageData.data) {
console.log("Test4: same");
} else {
console.log("Test4: different");
}
This code outputs:
Test1: different
Test2: different
Test3: same
Test4: same
So comparing the object to itself works as expected and when comparing the data inside the imageData object, but not against what should be an identical copy.
Is this an issue with comparing objects or is there something I am missing with the way the data is being sourced from the canvas element?
Thanks
imageData.datais aCanvasPixelArray, which is an object. For two objects A and BA == Bwill only be true if they reference the same object.Since you’re using two different
imageDataobjects bothimageData == imageData2andimageData.data == imageData2.datawill evaluate to false, even if their properties are the same.Note that the type of
imageData.datahas been changed toUint8ClampedArray, which is basically a Canvas PixelArrayBuffer.In order to check two Images you would have to do a pixel-based check:
However, there could be already a library which uses non-blocking methods.