<!doctype html>
AI Background Blur — Vanilla HTML/CSS/JS
12
<!doctype html>
let net = null; let originalImageData = null; const MAX_SIDE = 1600;
blurRange.addEventListener('input', ()=> blurVal.textContent = blurRange.value);
async function loadModel(){ if (net) return net; status.textContent = 'Loading model...'; net = await bodyPix.load({ architecture: 'MobileNetV1', outputStride: 16, multiplier: 0.75, quantBytes: 2 }); status.textContent = 'Model ready.'; return net; }
fileInput.addEventListener('change', async (ev)=>{ const f = ev.target.files[0]; if(!f) return; status.textContent = 'Loading image...';
const url = URL.createObjectURL(f); const img = new Image(); img.onload = () => { let w = img.naturalWidth, h = img.naturalHeight; if (Math.max(w,h) > MAX_SIDE){ const s = MAX_SIDE / Math.max(w,h); w = w*s; h = h*s; } canvas.width = w; canvas.height = h; ctx.drawImage(img,0,0,w,h); originalImageData = ctx.getImageData(0,0,w,h); URL.revokeObjectURL(url); status.textContent = 'Image loaded. Apply blur.'; } img.src = url; });
async function applyBlur(){ if(!originalImageData) return alert("Load image first."); await loadModel();
const w = canvas.width, h = canvas.height;
const off = document.createElement('canvas'); off.width=w; off.height=h; off.getContext('2d').putImageData(originalImageData,0,0);
status.textContent = 'Segmenting...'; const segmentation = await net.segmentPerson(off);
const mask = bodyPix.toMask(segmentation);
const blurCan = document.createElement('canvas'); blurCan.width=w; blurCan.height=h; const bctx = blurCan.getContext('2d'); bctx.filter = `blur(${blurRange.value}px)`; bctx.drawImage(off,0,0);
const orig = off.getContext('2d').getImageData(0,0,w,h).data; const blur = bctx.getImageData(0,0,w,h).data; const maskData = mask.data;
const out = ctx.createImageData(w,h); const outBuf = out.data;
for(let i=0;i
ctx.putImageData(out,0,0); status.textContent = "Background blurred."; }
function removeBlur(){ if(!originalImageData) return; ctx.putImageData(originalImageData,0,0); status.textContent = 'Original restored.'; }
function clearImage(){ canvas.width = 0; canvas.height = 0; originalImageData = null; status.textContent = "Image removed. Load new image."; }
downloadBtn.addEventListener('click', ()=>{ if(!originalImageData) return; const a=document.createElement('a'); a.download='blurred.png'; a.href=canvas.toDataURL(); a.click(); });
applyBtn.addEventListener('click', applyBlur); removeBtn.addEventListener('click', removeBlur); clearBtn.addEventListener('click', clearImage);
})();