WEBコンテンツ上でのモザイク化処理でよく利用されるcanvas要素を本処理でも使っていますが、自前でドットを再計算などはせず、
- オリジナル画像をそれよりも小さいcanvasへ表示
- 見かけ上元のサイズで表示
という簡易処理で済ませています。
to_pixelated.js
'use strict';
const toPixelated = (imageElement, blockSize = 4) => {
const img = imageElement;
const size = {
width: img.width / blockSize,
height: img.height / blockSize,
};
const canvasElement = Object.assign(document.createElement('canvas'), size);
canvasElement.getContext('2d').drawImage(img, 0, 0, ...Object.values(size));
Object.assign(canvasElement.style, {
width: `${img.width}px`,
height: `${img.height}px`,
imageRendering: 'pixelated',
});
return canvasElement;
};
使用例 / 動作デモ
index.html
<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset='utf-8'>
<meta name='viewport' content='initial-scale=1'>
<style>
#container {
position: relative;
}
#sample01, canvas {
position: absolute;
left: 0;
top: 0;
}
#sample01 {
max-width: 100%;
}
</style>
</head>
<body>
<input type='range' id='slider' min='1' max='100' value='20' disabled>
<div id='container'>
<img src='sample.jpg' id='sample01'>
</div>
<script src='to_pixelated.js'></script>
<script>
'use strict';
const obj = {};
const slider = document.getElementById('slider');
const insertPixelated = () =>
obj.sourceImage.insertAdjacentElement('afterend', obj.pixelated = toPixelated(obj.sourceImage, slider.value));
addEventListener('load', () => {
obj.sourceImage = document.getElementById('sample01');
insertPixelated();
slider.disabled = false;
});
slider.addEventListener('input', () => {
obj.pixelated.remove();
insertPixelated();
});
</script>
</body>
</html>