根据Html5 canvas完成剪裁照片和马赛克作用及又拍

日期:2021-01-19 类型:科技新闻 

关键词:小程序制作流程,抽奖小程序,微信小程序怎么开店,小程序码生成,小程序模版

1.关键作用

  此组件作用包括:

    照片剪裁(剪裁框拖拽,剪裁框更改尺寸);

    照片马赛克(绘图马赛克,消除马赛克);

    照片预览、照片复原(回到原图、回到解决图);

    照片提交(获得签字、提交照片)。

2.关键逻辑性

  2.1照片剪裁

  获得剪裁框(矩形框)相对画布的部位(左上)和剪裁框的height、width。获得(getImageData)canvas相应部位的照片目标(ImageData)。清空canvas画布。在canvas画布的相应部位绘图(putImageData)获得的照片目标(ImageData)。转化成预览图。

  2.2照片马赛克

  马赛克的绘图,便是在以电脑鼠标划过相对路径(画笔宽度)为管理中心的地区,再次绘图成别的的色调。1般結果是,会取周边的相仿的色调。

  取色方式:

  1)例如现有1电脑鼠标划过的点的座标(x,y),界定1个矩形框左上角座标取(x,y),宽30px,高30px。大家把矩形框宽高都除以5(分为5份,能够自定为n份),因此如今是25个6px的小格子。每一个小格子宽高全是6px。

  2)随后,大家任意获得1个小格子,获得(getImageData)这个小格子的照片目标(ImageData);再任意获得此照片目标上某个像素点(宽1px,高1px)的色调color(rgba:ImageData.data[0],ImageData.data[1],ImageData.data[2],ImageData.data[3]);最终大家把第1个6x6px的小格子的每一个像素点的色调都设定为color。

  3)别的24个小格子的色调,遍历2流程便可。

  2.3消除马赛克

  大家必须了解1个难题,无论是绘图马赛克,還是消除马赛克,其实质全是在绘图照片。大家在某个部位绘图了马赛克,消除的情况下,便是把原图在当今部位的照片目标再画出来。就做到了消除的实际效果。因此,大家必须备份数据1个canvas,和原图1模1样,消除的情况下,必须获得备份数据画布上对应部位的图象,绘图到马赛克的部位。

  2.4照片预览

  照片预览便是获得剪裁框的地区,获得地区内的照片目标。再绘图到画布上。

  2.5照片复原至原图

  清空画布,再度绘图原图

  2.6复原至已实际操作照片

  预览是储存画布照片目标(ImageData),清空画布,绘图储存的照片目标至画布

  2.7照片提交

  获得(toDataURL)canvas照片相对路径,将获得到的base64照片转换为File目标。开展提交。

3.详细编码以下:

<template>
  <div class="canvas-clip" :loading="loading">
    <div
      v-show="isDrop"
      class="canvas-mainBox"
      ref="canvas-mainBox"
      id="canvas-mainBox"
      @mousedown.stop="startMove($event)"
    >
      <div class="canvas-minBox left-up" @mousedown.stop="startResize($event,0)"></div>
      <div class="canvas-minBox up" @mousedown.stop="startResize($event,1)"></div>
      <div class="canvas-minBox right-up" @mousedown.stop="startResize($event,2)"></div>
      <div class="canvas-minBox right" @mousedown.stop="startResize($event,3)"></div>
      <div class="canvas-minBox right-down" @mousedown.stop="startResize($event,4)"></div>
      <div class="canvas-minBox down" @mousedown.stop="startResize($event,5)"></div>
      <div class="canvas-minBox left-down" @mousedown.stop="startResize($event,6)"></div>
      <div class="canvas-minBox left" @mousedown.stop="startResize($event,7)"></div>
    </div>
    <!-- 画布 -->
    <canvas
      class="canvas-area"
      ref="canvas"
      id="canvas"
      :width="canvasWidth"
      :height="canvasHeight"
      @mousedown.stop="startMove($event)"
      :class="{hoverPaint:isMa,hoverClear:isMaClear}"
    ></canvas>
    <!-- 备份数据画布 -->
    <canvas class="canvas-copy" ref="canvasCopy" :width="canvasWidth" :height="canvasHeight"></canvas>
    <div class="canvas-btns">
      <button v-if="backBtn" @click="clipBack">回到</button>
      <button :class="{active:btnIndex==0}" @click="sourceImg">原图</button>
      <button :class="{active:btnIndex==1}" @click="paintRectReady" :disabled="isDisabled">马赛克</button>
      <button :class="{active:btnIndex==2}" @click="paintRectClearReady" :disabled="isDisabled">橡皮擦</button>
      <button :class="{active:btnIndex==3}" @click="clipReady" :disabled="isDisabled">剪裁</button>
      <button :class="{active:btnIndex==4}" @click="clipPosition">预览</button>
      <button @click="getSignature">提交</button>
      <button class="close" @click="canvasClose()">x</button>
      <!-- <div class="paint-size" v-if="isMaClear || isMa">
        <span>画笔尺寸</span>
        <input :defaultValue="maSize" v-model="maSize" max="100" min="1" type="range">
        <span class="size-num">{{maSize}}</span>
      </div> -->
    </div>
  </div>
</template>
<script>
import axios from "axios";
import md5 from "js-md5";
import req from "../../axios/config";
export default {
  props: ["imgUrl"],
  data() {
    return {
      resizeFX: "",
      movePrev: "",
      canvasWidth: 800, // 画布宽
      canvasHeight: 600, // 画布高
      loading: false,
      isDrop: false, // 剪裁
      isMa: false, // 马赛克
      maSize: 30, // 马赛克尺寸
      isMaClear: false, // 消除马赛克
      backBtn: false, // 回到按钮
      isDisabled: false,//禁用按钮
      btnIndex: 0,//当今按钮
      mouseX:'',// 电脑鼠标部位
      mouseY:'',
      clipEle: "", // 剪裁框元素
      canvasDataSession: "", // 预览前的画布信息内容
      canvas: "", // 画布
      ctx: "", // 画布左右文
      canvasCopy: "", // copy画布
      ctxCopy: "", // copy画布左右文
      uploadOption: { // 照片提交主要参数
        path: "",
        policy: "",
        signature: "",
        username: ""
      }
    };
  },
  mounted() {
    this.clipEle = this.$refs["canvas-mainBox"];
    this.canvas = this.$refs["canvas"];
    this.ctx = this.canvas.getContext("2d");
    this.canvasCopy = this.$refs["canvasCopy"];
    this.ctxCopy = this.canvasCopy.getContext("2d");
    this.draw();
  },
  methods: {
    // 建立照片
    draw() {
      var img = new Image();
      img.setAttribute('crossOrigin', 'anonymous');
      img.onload = () => {
        this.ctx.drawImage(img, 0, 0, 800, 600);
        this.ctxCopy.drawImage(img, 0, 0, 800, 600);
      };
      img.src = this.imgUrl + '?time=' + new Date().valueOf();
    },
    //预览 测算剪裁框的部位(左上座标)
    clipPosition() {
      this.isDisabled = true;
      this.backBtn = true;
      this.isMa = false;
      this.isMaClear = false;
      this.btnIndex = 4;
      //画布部位
      var canvasPx = this.canvas.offsetLeft,
        canvasPy = this.canvas.offsetTop;
      if (this.isDrop) {
        // 剪裁框部位
        var clipPx = this.clipEle.offsetLeft,
          clipPy = this.clipEle.offsetTop,
          x = clipPx - canvasPx,
          y = clipPy - canvasPy,
          w = this.clipEle.offsetWidth,
          h = this.clipEle.offsetHeight,
          // 预览图垂直居中
          positionX = 400 - this.clipEle.offsetWidth / 2,
          positionY = 300 - this.clipEle.offsetHeight / 2;
      } else {
        // 沒有剪裁框,储存详细照片
        var x = 0,
          y = 0,
          w = this.canvas.offsetWidth,
          h = this.canvas.offsetHeight,
          // 预览图垂直居中
          positionX = 0,
          positionY = 0;
      }
      var imageData = this.ctx.getImageData(x, y, w, h);
      this.canvasDataSession = this.ctx.getImageData(
        0,
        0,
        this.canvasWidth,
        this.canvasHeight
      );
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.ctx.putImageData(imageData, positionX, positionY);
      this.clipEle.style.display = "none";
      this.canvasCopy.style.display = "none";
    },
    // 回到预览前情况
    clipBack() {
      this.btnIndex = ⑴;
      this.backBtn = false;
      this.isDisabled = false;
      this.isDrop = false;
      this.ctx.putImageData(this.canvasDataSession, 0, 0);
      this.canvasCopy.style.display = "block";
    },
    // 原图
    sourceImg() {
      this.isDisabled = false;
      this.btnIndex = 0;
      this.backBtn = false;
      this.isMa = false;
      this.isDrop = false;
      this.isMaClear = false;
      var img = new Image();
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      img.setAttribute('crossOrigin', 'anonymous');
      img.onload = () => {
        this.ctx.drawImage(img, 0, 0, this.canvasWidth, this.canvasHeight);
      };
      img.src = this.imgUrl + '?time=' + new Date().valueOf();
      this.canvasCopy.style.display = "block";
    },
    // 获得签字
    getSignature() {
      // canvas照片base64 转 File 目标
      var dataURL = this.canvas.toDataURL("image/jpg"),
        arr = dataURL.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      var obj = new Blob([u8arr], { type: mime }),
        time = new Date().toGMTString(),
        formData = new FormData();
      formData.append("file", obj);
      // 获得文档后缀
      var suffix = formData.get("file").type.split("/")[1];
      req
        .get("/carsource-api/upyun/sign", { suffix: suffix })
        .then(response => {
          if (response.data.code === 0) {
            this.uploadOption.path = response.data.data.path;
            formData.append("policy", response.data.data.policy);
            formData.append("authorization", response.data.data.signature);
            this.updateImg(formData);
          }
        })
        .catch(function(error) {});
    },
    // 提交
    updateImg(formData) {
      axios({
        url: "http://v0.api.upyun.com/tmp-img",
        method: "POST",
        data: formData
      }).then(response => {
        if (response.data.code == 200) {
          this.$message.success("照片改动取得成功");
          this.canvasClose("upload", response.data.url.slice(4));
        }
      });
    },
    // 剪裁框放缩 挪动
    startResize(e, n) {
      this.resizeFX = n;
      $(document).mousemove(this.resizeDiv);
      document.addEventListener("mouseup", this.stopResize);
    },
    stopResize(e) {
      $(document).off("mousemove", this.resizeDiv);
      document.removeEventListener("mouseup", this.stopResize);
    },
    startMove(e) {
      this.movePrev = [e.pageX, e.pageY];
      $(document).mousemove(this.moveDiv);
      document.addEventListener("mouseup", this.stopMove);
    },
    stopMove(e) {
      $(document).off("mousemove", this.moveDiv);
      document.removeEventListener("mouseup", this.stopMove);
    },
    moveDiv(e) {
      // 马赛克
      if (this.isMa) {
        this.paintRect(e);
      }
      // 消除马赛克
      if (this.isMaClear) {
        this.paintRectClear(e);
      }
      // 剪裁
      if (this.isDrop) {
        var targetDiv = $("#canvas-mainBox"),
          offsetArr = targetDiv.offset();
        var chaX = e.pageX - this.movePrev[0],
          chaY = e.pageY - this.movePrev[1],
          ox = parseFloat(targetDiv.css("left")),
          oy = parseFloat(targetDiv.css("top"));
        targetDiv.css({
          left: ox + chaX + "px",
          top: oy + chaY + "px"
        });
        this.movePrev = [e.pageX, e.pageY];
      }
    },
    resizeDiv(e) {
      e.preventDefault();
      e.stopPropagation();
      // 获得必须更改规格元素到网页页面的间距
      var targetDiv = $("#canvas-mainBox"),
        offsetArr = targetDiv.offset();
      var eleSWidth = targetDiv.width(),
        eleSHeight = targetDiv.height(),
        ox = parseFloat(targetDiv.css("left")),
        oy = parseFloat(targetDiv.css("top"));
      // 获得电脑鼠标部位,和元素原始offset开展比照,
      var chaX = e.pageX - offsetArr.left,
        chaY = e.pageY - offsetArr.top;
      switch (this.resizeFX) {
        case 0:
          //假如挪动间距贴近宽度或高宽比,则不开展更改
          if (chaX >= eleSWidth - 10 || chaY >= eleSHeight - 10) {
            return;
          }
          // 得到部位差(m-e),先设定宽度和高宽比,再设定部位
          // 初始宽高+((m-e)*⑴),初始部位+(m-e)
          targetDiv.css({
            width: eleSWidth + chaX * ⑴ + "px",
            height: eleSHeight + chaY * ⑴ + "px",
            left: ox + chaX + "px",
            top: oy + chaY + "px"
          });
          break;
        case 1:
          //假如挪动间距贴近宽度或高宽比,则不开展更改
          if (chaY >= eleSHeight - 10) {
            return;
          }
          // 得到部位差(m-e),先设定宽度和高宽比,再设定部位
          // 初始宽高+((m-e)*⑴),初始部位+(m-e)
          targetDiv.css({
            height: eleSHeight + chaY * ⑴ + "px",
            top: oy + chaY + "px"
          });
          break;
        case 2:
          //假如挪动间距贴近宽度或高宽比,则不开展更改
          if (chaX <= 10 || chaY >= eleSHeight - 10) {
            return;
          }
          // 得到部位差(m-e),先设定宽度和高宽比,设定部位
          // 初始高+((m-e)*⑴),初始宽+((m-e)),初始部位+(m-e)
          targetDiv.css({
            width: chaX + "px",
            height: eleSHeight + chaY * ⑴ + "px",
            top: oy + chaY + "px"
          });
          break;
        case 3:
          //假如挪动间距贴近宽度或高宽比,则不开展更改
          if (chaX <= 10) {
            return;
          }
          // 得到部位差(m-e),先设定宽度和高宽比,再设定部位
          // 初始宽高+((m-e)*⑴),初始部位+(m-e)
          targetDiv.css({
            width: chaX + "px"
          });
          break;
        case 4:
          //假如挪动间距贴近宽度或高宽比,则不开展更改
          if (chaX <= 10 || chaY <= 10) {
            return;
          }
          // 得到部位差(m-e),先设定宽度和高宽比,再设定部位
          // 初始宽高+((m-e)*⑴),初始部位+(m-e)
          targetDiv.css({
            width: chaX + "px",
            height: chaY + "px"
          });
          break;
        case 5:
          //假如挪动间距贴近宽度或高宽比,则不开展更改
          if (chaY <= 10) {
            return;
          }
          // 得到部位差(m-e),先设定宽度和高宽比,再设定部位
          // 初始宽高+((m-e)*⑴),初始部位+(m-e)
          targetDiv.css({
            height: chaY + "px"
          });
          break;
        case 6:
          //假如挪动间距贴近宽度或高宽比,则不开展更改
          if (chaX >= eleSWidth - 10 || chaY <= 10) {
            return;
          }
          // 得到部位差(m-e),先设定宽度和高宽比,再设定部位
          // 初始宽高+((m-e)*⑴),初始部位+(m-e)
          targetDiv.css({
            width: eleSWidth + chaX * ⑴ + "px",
            height: chaY + "px",
            left: ox + chaX + "px"
          });
          break;
        case 7:
          //假如挪动间距贴近宽度或高宽比,则不开展更改
          if (chaX >= eleSWidth - 10) {
            return;
          }
          // 得到部位差(m-e),先设定宽度和高宽比,再设定部位
          // 初始宽高+((m-e)*⑴),初始部位+(m-e)
          targetDiv.css({
            width: eleSWidth + chaX * ⑴ + "px",
            left: ox + chaX + "px"
          });
          break;
        default:
          break;
      }
    },
    // 剪裁
    clipReady() {
      this.btnIndex = 3;
      this.isMa = false;
      this.isDrop = true;
      this.isMaClear = false;
    },
    // 马赛克
    paintRectReady() {
      this.btnIndex = 1;
      this.isMa = true;
      this.isDrop = false;
      this.isMaClear = false;
    },
    // 橡皮擦
    paintRectClearReady() {
      this.btnIndex = 2;
      this.isMa = false;
      this.isDrop = false;
      this.isMaClear = true;
    },
    // 绘图马赛克
    paintRect(e) {
      var offT = this.canvas.offsetTop, // 间距上边间距
        offL = this.canvas.offsetLeft, // 间距左侧间距
        x = e.clientX,
        y = e.clientY;
      if(this.mouseX - x > this.maSize/2 || x - this.mouseX > this.maSize/2 || this.mouseY - y > this.maSize/2 || y - this.mouseY > this.maSize/2){
        var oImg = this.ctx.getImageData(x - offL ,y - offT,this.maSize,this.maSize);
        var w = oImg.width;
        var h = oImg.height;
        //马赛克的水平,数据越大越模糊不清
        var num = 6;
        //等分画布
        var stepW = w/num;
        var stepH = h/num;
        //这里是循环系统画布的像素点
        for(var i=0;i<stepH;i++){
          for(var j=0;j<stepW;j++){
            //获得1个小方格的任意色调,这是小方格的任意部位获得的
            var color = this.getXY(oImg,j*num+Math.floor(Math.random()*num),i*num+Math.floor(Math.random()*num));
            //这里是循环系统小方格的像素点,
            for(var k=0;k<num;k++){
                for(var l=0;l<num;l++){
                    //设定小方格的色调
                    this.setXY(oImg,j*num+l,i*num+k,color);
                }    
            }
          }    
        }
        this.ctx.putImageData(oImg,x - offL ,y - offT);
        this.mouseX = e.clientX
        this.mouseY = e.clientY
      }
    },
    getXY(obj,x,y){
      var w = obj.width;
      var h = obj.height;
      var d = obj.data;
      var color = [];
      color[0] = d[4*(y*w+x)];
      color[1] = d[4*(y*w+x)+1];
      color[2] = d[4*(y*w+x)+2];
      color[3] = d[4*(y*w+x)+3];
      return color;
    },
    setXY(obj,x,y,color){
      var w = obj.width;
      var h = obj.height;
      var d = obj.data;
      d[4*(y*w+x)] = color[0];
      d[4*(y*w+x)+1] = color[1];
      d[4*(y*w+x)+2] = color[2];
      d[4*(y*w+x)+3] = color[3];
    },
    // 消除马赛克
    paintRectClear(e) {
      var offT = this.canvasCopy.offsetTop, // 间距上边间距
        offL = this.canvasCopy.offsetLeft, // 间距左侧间距
        x = e.clientX,
        y = e.clientY,
        // 获得原图此部位图象数据信息
        imageData = this.ctxCopy.getImageData(
          x - offL,
          y - offT,
          this.maSize,
          this.maSize
        );
      this.ctx.putImageData(imageData, x - offL, y - offT);
    },
    // 关掉画布
    canvasClose(type, url) {
      this.$emit("isShowImgChange", type, url);
    }
  }
};
</script>
<style scoped>
.canvas-clip {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 9010;
  background: #000;
}
.canvas-mainBox {
  position: absolute;
  width: 400px;
  height: 300px;
  left: 50%;
  top: 50%;
  margin-left: ⑵00px;
  margin-top: ⑴50px;
  border: 1px solid #FFF;
  cursor: move;
  z-index: 9009;
}
.canvas-minBox {
  position: absolute;
  width: 8px;
  height: 8px;
  background: #FFF;
}
.left-up {
  top: ⑷px;
  left: ⑷px;
  cursor: nw-resize;
}
.up {
  top: ⑷px;
  left: 50%;
  margin-left: ⑷px;
  cursor: n-resize;
}
.right-up {
  top: ⑷px;
  right: ⑷px;
  cursor: ne-resize;
}
.right {
  top: 50%;
  margin-top: ⑷px;
  right: ⑷px;
  cursor: e-resize;
}
.right-down {
  bottom: ⑷px;
  right: ⑷px;
  cursor: se-resize;
}
.down {
  bottom: ⑷px;
  left: 50%;
  margin-left: ⑷px;
  cursor: s-resize;
}
.left-down {
  bottom: ⑷px;
  left: ⑷px;
  cursor: sw-resize;
}
.left {
  top: 50%;
  margin-top: ⑷px;
  left: ⑷px;
  cursor: w-resize;
}
.canvas-btns {
  position: fixed;
  right: 50px;
  top: 30px;
  z-index: 9003;
}
.canvas-btns button {
  display: inline-blovk;
  background: green;
  cursor: pointer;
  border: none;
  width: 60px;
  height: 30px;
  line-height: 30px;
  color: #fff;
  font-size: 15px;
}
.canvas-btns button.active {
  background: rgb(32, 230, 32);
}
.canvas-btns button.close {
  background: rgb(230, 72, 32);
}
.canvas-copy {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: ⑶00px;
  margin-left: ⑷00px;
  z-index: 9007;
}
.canvas-mosatic {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: ⑶00px;
  margin-left: ⑷00px;
  z-index: 9009;
}
.canvas-area {
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: ⑶00px;
  margin-left: ⑷00px;
  z-index: 9008;
}
.paint-size{
  margin-top: 20px;
  font-size: 13px;
  color: #FFF;
  height: 30px;
  line-height: 30px;
  text-align: right;
}
.paint-size input{
  vertical-align: middle;
  background: green;
}
.paint-size .size-num{
  display: inline-block;
  width: 15px;
}
.hoverClear{
  cursor: url('./paint.png'),auto;
}
.hoverPaint{
  cursor: url('./paint.png'),auto;
}
</style> 

4.实际效果图以下:

总结

以上所述是网编给大伙儿详细介绍的根据Html5 canvas完成剪裁照片和马赛克作用及又拍云提交照片 作用 ,期待对大伙儿有一定的协助,假如大伙儿有任何疑惑请给我留言,网编会立即回应大伙儿的。在此也十分谢谢大伙儿对脚本制作之家网站的适用!
假如你感觉本文对你有协助,欢迎转载,烦请注明出处,感谢!