土曜日, 11月 15, 2025

Let's start JavaScript 87 
指定画像を印象派風の画像に変換

指定画像を印象派風の画像に変換します。あくまでも「〜風」です(^o^)

<!-- index.html -->
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>印象派風フィルタ</title>
<style>
body { text-align: center; background: #f0f0f0;
    font-family: sans-serif; }
canvas { border: 1px solid #ccc; margin-top: 10px; }
</style>
</head>
<body>
<h2>画像を印象派風に変換</h2>
<input type="file" id="fileInput" accept="image/*">
<br>
<canvas id="canvas"></canvas>

<script>
const fileInput = document.getElementById('fileInput');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

fileInput.addEventListener('change', e => {
const file = e.target.files[0];
if (!file) return;
const img = new Image();
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);

// ピクセルデータ取得
const imageData =
        ctx.getImageData(0, 0, canvas.width, canvas.height);
const data = imageData.data;

// 印象派風:色のにじみ + ランダムブラシ
const radius = 2;
for (let y = 0; y < canvas.height; y += radius) {
for (let x = 0; x < canvas.width; x += radius) {
const i = (y * canvas.width + x) * 4;
const r = data[i];
const g = data[i + 1];
const b = data[i + 2];

// ランダム位置に筆触っぽく配置
const dx = x + (Math.random() - 0.5) * radius * 3;
const dy = y + (Math.random() - 0.5) * radius * 3;

ctx.fillStyle = `rgba(${r},${g},${b},0.8)`;
ctx.beginPath();
ctx.ellipse(dx, dy, radius, radius / 2,
            Math.random() * Math.PI, 0, Math.PI * 2);
ctx.fill();
}
}
};
img.src = URL.createObjectURL(file);
});
</script>
</body>
</html>
<!-- index.html -->

実行したら画像を指定するだけです。

元画像

結果はこんな感じです。やっぱり元画像を色々いじってから処理した方が良いですね。