HTML上で指定した画像の彩度を反転させます。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>画像の彩度反転</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 10px;
background-color: black;
color: white;
}
#imageContainer img {
max-width: 100%;
height: auto;
transition: 0.5s; /* なめらかな変化 */
}
</style>
</head>
<body>
<h3>画像の彩度反転</h3>
<input type="file" id="imageInput" accept="image/*">
<button onclick="toggleSaturation()">彩度反転</button>
<div id="imageContainer"></div>
<script>
let currentImage = null;
document.getElementById("imageInput").
addEventListener("change", function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
const img = document.createElement("img");
img.src = e.target.result;
img.id = "selectedImage";
img.style.filter = "saturate(100%)"; // 初期状態は通常彩度
document.getElementById("imageContainer").
innerHTML = "";
document.getElementById("imageContainer").
appendChild(img);
currentImage = img;
};
reader.readAsDataURL(file);
}
});
function toggleSaturation() {
if (currentImage) {
let currentFilter = currentImage.style.filter;
currentImage.style.filter = (currentFilter ===
"saturate(0%)") ? "saturate(100%)" : "saturate(0%)";
}
}
</script>
</body>
</html>
実行したら、処理したい画像ファイルを選択します。
ファイルを表示したら[彩度反転]をクリックすると・・・
彩度が反転されます。ここで再度[彩度反転]をクリックすると・・・
元のイメージに戻ります。