import pixelmatch from 'pixelmatch';
import { field, input, number, raster, canvas, encode, result } from '../../src/io.js';
export default {
controls: field('差异阈值(0–1)', input('threshold', 0.1, 0, 1, 0.01)) + '<label class="check-field"><input type="checkbox" name="aa">计入抗锯齿差异</label>',
async run({ state, form, details }) {
if (state.images.length !== 2) throw new Error('请选择两张相同尺寸的图片。');
const [a, b] = state.images;
if (a.width !== b.width || a.height !== b.height) throw new Error('两张图片的尺寸必须一致。');
const width = a.width; const height = a.height;
const first = raster(a, width, height, '#ffffff').getContext('2d').getImageData(0, 0, width, height);
const second = raster(b, width, height, '#ffffff').getContext('2d').getImageData(0, 0, width, height);
const output = canvas(width, height); const ctx = output.getContext('2d'); const pixels = ctx.createImageData(width, height);
const count = pixelmatch(first.data, second.data, pixels.data, width, height, { threshold: number(form, 'threshold'), includeAA: form.elements.aa.checked });
ctx.putImageData(pixels, 0, 0);
const percent = (count * 100 / (width * height)).toFixed(3);
details.innerHTML = `<p class="metric" data-diff-count="${count}">${count.toLocaleString()} 个差异像素 · ${percent}%</p>`;
return [result(await encode(output), 'image-diff.png', `${count} 个差异像素`)];
},
};