Use StackBlur.js to make the picture background blur

Article Directory

 


Preface

The front-end of WEB has become more and more powerful. Many times, the front-end is required to perform simple processing of pictures. For example, the background of the picture I encountered is blurred and then the picture is superimposed. After some exploration, the js plug-in StackBlur.js was used to complete the demand.


Tip: The following is the content of this article, the following cases are for reference

1. Use StackBlur.js to make a blur background

StackBlur.js is mainly a js plugin for blurring images.

Second, use steps

1. Install dependencies

Github project address: https://github.com/flozz/StackBlur

npm install --save stackblur-canvas

2. Create a page

html code:

        <h1>图像背景模糊处理</h1>
        <canvas id="canvas" width="600" height="300"></canvas>
        <div>
            <label>背景模糊半径</label> <input type="range" min="0" max="50" value="0" id="slider" />
            <br><br>
            <label>叠加图层透明度</label>
            <input type="range" step="0.1" min="0" max="1" value="1" id="alpha" />
            <br><br>
            <button id="add">合并</button>
            <br><br>
            <button onclick="exportCanvasAsPNG('canvas','mohu')">保存</button>
        </div>
CSS code:
html, body {
    padding: 0;
    margin: 0;
    text-align: center;
    background: #fff;
    font-family: Arial, sans-serif;
    color: #333;
}

canvas {
    border: #fff solid 4px;
    box-shadow: 0 0 10px rgba(0, 0, 0, .3);
    vertical-align: middle;
}

div {
    margin: 20px;
}

3. Write js code

// 引入StackBlur.js
import * as StackBlur from '../src/stackblur.js';

//获取预览的convas对象
const canvas = document.querySelector('#canvas');
const cctx = canvas.getContext('2d');

//创建一个待处理的convas对象
const buff = document.createElement('canvas');
buff.width = canvas.width;
buff.height = canvas.height;
const bctx = buff.getContext('2d');

//加载图片
var img = new Image();
img.src = "imgdemo.png";
img.onload = function() {
  bctx.drawImage(img, 0, 0, 600, 300);
  console.log("img is loaded")
  cctx.drawImage(buff, 0, 0);
};
img.onerror = function() {
  console.log("error!")
};

// Slider
const slider = document.querySelector('#slider');
slider.addEventListener('change', function() {
  cctx.drawImage(buff, 0, 0);
  //调用StackBlur.js实现模糊
  StackBlur.canvasRGB(
    canvas, 0, 0, canvas.width, canvas.height, slider.value
  );
});

//add合并按钮
const button = document.querySelector('#add');
button.addEventListener('click', function() {
  var img2 = new Image();
  img2.src = "code.jpg";
  img2.onload = function() {
    //设置透明度
    cctx.globalAlpha = document.querySelector('#alpha').value
    cctx.drawImage(img2, 100, 0, 150, 150);
  };
  img2.onerror = function() {
    console.log("error!")
  };

});

Three, effect display


to sum up

This case is a simple realization of the background blur, for reference only!

Guess you like

Origin blog.csdn.net/xiao_bin_shen/article/details/109000151