dasumae / src /redact.js
NagaYu's picture
Upload 6 files
c4413a6 verified
Raw History Blame Contribute Delete
2.61 kB
// Redaction renderers. Each draws the hidden version of ONE box into a 2D
// context. Source pixels are read from `img` (the original image / bitmap) in
// ORIGINAL-image pixels, so repeated renders never feed back on themselves and
// a full-resolution download looks identical to the on-screen preview.
//
// ctx : destination 2D context
// img : source drawable (HTMLImageElement / ImageBitmap / Canvas) at natural size
// box : { x, y, w, h } in ORIGINAL-image pixels
// scale : destination-pixels per original-pixel (1 for full-res download)
//
// style is one of 'solid' | 'mosaic' | 'blur'.
function destRect(box, scale) {
return {
x: Math.round(box.x * scale),
y: Math.round(box.y * scale),
w: Math.max(1, Math.round(box.w * scale)),
h: Math.max(1, Math.round(box.h * scale)),
};
}
function solid(ctx, _img, box, scale) {
const d = destRect(box, scale);
ctx.save();
ctx.fillStyle = '#000';
ctx.fillRect(d.x, d.y, d.w, d.h);
ctx.restore();
}
// Pixelate: shrink the region to a small grid then scale it back up with image
// smoothing disabled, so each grid cell becomes a flat block.
function mosaic(ctx, img, box, scale) {
const d = destRect(box, scale);
// Block size grows with the box so redaction strength is consistent.
const block = Math.max(6, Math.round(Math.min(d.w, d.h) / 10));
const gw = Math.max(1, Math.round(d.w / block));
const gh = Math.max(1, Math.round(d.h / block));
const tmp = document.createElement('canvas');
tmp.width = gw; tmp.height = gh;
const tctx = tmp.getContext('2d');
tctx.imageSmoothingEnabled = true;
// original-pixel source -> tiny grid
tctx.drawImage(img, box.x, box.y, box.w, box.h, 0, 0, gw, gh);
ctx.save();
ctx.imageSmoothingEnabled = false;
ctx.drawImage(tmp, 0, 0, gw, gh, d.x, d.y, d.w, d.h);
ctx.restore();
}
// Blur: redraw just the box region from the source with a canvas blur filter,
// clipped to the box so the blur does not bleed outside it.
function blur(ctx, img, box, scale) {
const d = destRect(box, scale);
const radius = Math.max(4, Math.round(Math.min(d.w, d.h) / 6));
ctx.save();
ctx.beginPath();
ctx.rect(d.x, d.y, d.w, d.h);
ctx.clip();
ctx.filter = `blur(${radius}px)`;
// Draw a slightly expanded source so the blurred edges stay opaque.
ctx.drawImage(img, box.x, box.y, box.w, box.h, d.x, d.y, d.w, d.h);
ctx.restore();
}
const RENDERERS = { solid, mosaic, blur };
export function applyRedaction(ctx, img, box, scale, style) {
(RENDERERS[style] || solid)(ctx, img, box, scale);
}
export const STYLES = ['solid', 'mosaic', 'blur'];