console
<!DOCTYPE html>
<html>
<head>
<style>
#image-container {
}
#image {
max-width: 100%;
}
#mosaic-overlay {
position: absolute;
top: 0;
left: 0;
z-index: 9;
}
</style>
</head>
<body>
<div id="image-container">
<img src="https://www.lilnong.top/static/img/wx-linong.jpg" id="image" alt="Image" />
<canvas id="mosaic-overlay"></canvas>
</div>
<button class="btn">撤回</button>
<button class="submitBtn">确认</button>
<script>
const image = document.getElementById("image");
const mosaicOverlay = document.getElementById("mosaic-overlay");
image.onload = ()=>{
mosaicOverlay.width = image.width
mosaicOverlay.height = image.height
}
const ctx = mosaicOverlay.getContext("2d");
const mosaicSize = 20;
let isMosaicing = false;
const handleStart = () => {
isMosaicing = true;
arr.push([])
}
mosaicOverlay.addEventListener("mousedown", handleStart);
mosaicOverlay.addEventListener("touchstart", handleStart);
const handleMove = () => {
isMosaicing = false;
}
window.addEventListener("mouseup", handleMove);
window.addEventListener("touchend", handleMove);
const btn = document.querySelector('.btn')
let arr = []
const handleEnd = (e) => {
if (isMosaicing) {
const point = e?.touches?.[0] || e;
const x = point.clientX - mosaicSize / 2;
const y = point.clientY - mosaicSize / 2;
arr[arr.length-1].push({x,y})
ctx.drawImage(
image,
Math.random() * image.width,
Math.random() * image.height,
mosaicSize,
mosaicSize,
x,
y,
mosaicSize,
mosaicSize
);
}
}
mosaicOverlay.addEventListener("mousemove", handleEnd);
mosaicOverlay.addEventListener("touchmove", handleEnd);
btn.addEventListener('click',( )=>{
const list = arr.pop();
list.forEach(({x,y})=>{
ctx.clearRect(x, y,mosaicSize, mosaicSize);
})
})
const submitBtn = document.querySelector('.submitBtn')
submitBtn.addEventListener('click',()=>{
mosaicOverlay.toBlob((blob) => {
const newImg = document.createElement("img");
const url = URL.createObjectURL(blob);
newImg.onload = () => {
URL.revokeObjectURL(url);
};
newImg.src = url;
document.body.appendChild(newImg);
}
);
})
</script>
</body>
</html>