CSS代码:
.mosaic {
image-rendering: pixelated;
}
HTML代码:
<h4>原始图</h4>
<img src="1.jpg">
<h4>马赛克图</h4>
<img src="1.jpg" class="mosaic">
JS代码:
const img = document.querySelector('.mosaic');
img.onload = function () {
// base64地址不处理
if (!this.src.startsWith('http')) {
return;
}
const { clientWidth, clientHeight } = this;
// 创建canvas尺寸缩小
const canvas = document.createElement('canvas');
canvas.width = clientWidth / 6;
canvas.height = clientHeight / 6;
const context = canvas.getContext('2d');
context.drawImage(this, 0, 0, canvas.width, canvas.height);
// 替换图片地址
this.src = canvas.toDataURL();
};