返回

图片编辑实现滤镜自定义<#title>

前端

前言

图片滤镜是图像编辑中常用的工具,它可以改变图片的外观和感觉。在本文中,我们将介绍如何使用JavaScript、Canvas和HTML5构建自定义图像滤镜。我们将通过三个控件控制图片的间距、模糊度和底色。此外,还集成了上传图片功能和多种filter实现的其他效果。

HTML结构

<!DOCTYPE html>
<html>
<head>
  
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <h1>图片滤镜</h1>
  <input type="file" id="file-input">
  <canvas id="canvas"></canvas>
  <div id="controls">
    <label for="spacing">间距:</label>
    <input type="range" min="0" max="100" value="0" step="1" id="spacing">
    <br>
    <label for="blur">模糊度:</label>
    <input type="range" min="0" max="100" value="0" step="1" id="blur">
    <br>
    <label for="background-color">底色:</label>
    <input type="color" id="background-color">
  </div>
  <script src="script.js"></script>
</body>
</html>

JavaScript代码

const canvas = document.getElementById('canvas');
const context = canvas.getContext('2d');
const fileInput = document.getElementById('file-input');
const spacingInput = document.getElementById('spacing');
const blurInput = document.getElementById('blur');
const backgroundColorInput = document.getElementById('background-color');

fileInput.addEventListener('change', () => {
  const file = fileInput.files[0];
  const reader = new FileReader();

  reader.onload = () => {
    const image = new Image();

    image.onload = () => {
      canvas.width = image.width;
      canvas.height = image.height;
      context.drawImage(image, 0, 0);
      applyFilter();
    };

    image.src = reader.result;
  };

  reader.readAsDataURL(file);
});

spacingInput.addEventListener('input', () => {
  applyFilter();
});

blurInput.addEventListener('input', () => {
  applyFilter();
});

backgroundColorInput.addEventListener('input', () => {
  applyFilter();
});

function applyFilter() {
  const spacing = parseInt(spacingInput.value);
  const blur = parseInt(blurInput.value);
  const backgroundColor = backgroundColorInput.value;

  context.filter = `sepia(${spacing}%) blur(${blur}px)`;
  context.fillStyle = backgroundColor;
  context.fillRect(0, 0, canvas.width, canvas.height);
}

CSS样式

body {
  font-family: Arial, sans-serif;
}

h1 {
  margin-bottom: 20px;
}

#file-input {
  margin-bottom: 20px;
}

canvas {
  border: 1px solid black;
}

#controls {
  margin-top: 20px;
}

label {
  margin-right: 10px;
}

input[type="range"] {
  width: 200px;
}

input[type="color"] {
  width: 100px;
}

运行效果

将上述代码保存为HTML、CSS和JavaScript文件,然后在浏览器中打开HTML文件。您将看到一个简单的图片编辑器,其中包含三个控件用于控制图片的间距、模糊度和底色。您可以通过点击“选择图片”按钮来上传图片,也可以通过拖放图片到编辑器中来加载图片。图片加载后,您可以使用三个控件来调整图片的外观。

结语

本文介绍了如何使用JavaScript、Canvas和HTML5构建自定义图像滤镜。我们通过三个控件控制图片的间距、模糊度和底色。此外,还集成了上传图片功能和多种filter实现的其他效果。希望本文对您有所帮助。