File size: 1,948 Bytes
ef987bb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | // Locate a rendered transition without prescribing an HTML class, fixed device
// coordinate or even whether it is painted in a canvas.
async function pixelChanges(page, frames) {
return page.evaluate(async encoded => {
const images = await Promise.all(encoded.map(async source => {
const image = new Image();
image.src = 'data:image/png;base64,' + source;
await image.decode();
return image;
}));
const {width, height} = images[0];
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const context = canvas.getContext('2d', {willReadFrequently: true});
const pixels = images.map(image => {
context.clearRect(0, 0, width, height);
context.drawImage(image, 0, 0);
return context.getImageData(0, 0, width, height).data;
});
const different = (a, b, i) => Math.max(
Math.abs(a[i] - b[i]), Math.abs(a[i + 1] - b[i + 1]), Math.abs(a[i + 2] - b[i + 2]),
) >= 16;
const tile = 8;
const columns = Math.ceil(width / tile);
const points = Array.from({length: columns * Math.ceil(height / tile)}, () => [0, 0, 0]);
let novel = 0;
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const i = (y * width + x) * 4;
if (!different(pixels[0], pixels[1], i)) continue;
const bucket = points[Math.floor(y / tile) * columns + Math.floor(x / tile)];
bucket[0] += 1;
bucket[1] += x;
bucket[2] += y;
if (pixels.length === 4
&& (!different(pixels[2], pixels[3], i) || different(pixels[1], pixels[3], i))) novel += 1;
}
}
return {
points: points.filter(([weight]) => weight > 0)
.sort(([a], [b]) => b - a).slice(0, 56)
.map(([weight, x, y]) => ({x: x / weight, y: y / weight})),
novel,
};
}, frames.map(frame => frame.toString('base64')));
}
module.exports = {pixelChanges};
|