4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

JavaScript 画像をモザイク化

Last updated at Posted at 2023-08-19

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>
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?