如何用Vue实现图像模糊和饱和度调整?

2024年06月16日 建站教程

安装pica插件

npm install pica

具体实现代码如下:

<template>
  <div>
    <img :src="/staticimageUrl" alt="image" />
    <button @click="blurImage">应用模糊效果</button>
    <button @click="adjustSaturation">调整饱和度</button>
  </div>
</template>
 
<script>
import pica from 'pica';
export default {
  data() {
    return {
      imageUrl: 'images/pic.jpg',
    };
  },
  methods: {
    async blurImage() {
      const img = new Image();
      img.src = this.imageUrl;
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
 
      // 调整画布尺寸与图片一致
      canvas.width = img.width;
      canvas.height = img.height;
 
      // 在画布上绘制图片
      ctx.drawImage(img, 0, 0);
 
      // 应用模糊效果
      const picaResizer = pica();
      const blurredImage = await picaResizer.resize(canvas, canvas, { blur: 5 });
 
      // 将模糊后的图片展示在<img>标签中
      this.imageUrl = blurredImage.toDataURL();
    },
    async adjustSaturation() {
      const img = new Image();
      img.src = this.imageUrl;
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
 
      // 调整画布尺寸与图片一致
      canvas.width = img.width;
      canvas.height = img.height;
 
      // 在画布上绘制图片
      ctx.drawImage(img, 0, 0);
 
      // 应用饱和度调整
      const picaResizer = pica();
      const adjustedImage = await picaResizer.resize(canvas, canvas, { saturation: 0.5 });

      // 将调整后的图片展示在<img>标签中
      this.imageUrl = adjustedImage.toDataURL();
    },
  },
};
</script>

本文链接:http://so.lmcjl.com/news/6665/

展开阅读全文
相关内容