欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用canvas一步步实现图片打码功能的方法

程序员文章站 2022-03-29 18:51:31
这篇文章主要介绍了使用canvas一步步实现图片打码功能的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学... 19-06-17...

原文地址
https://github.com/my729/front-common-funtion/blob/master/picture-code-demo/readme.md

预览地址

准备工作

demo 基于 vue + elelment-ui

首先创建一个html文件, 并引入 vue 和 elelment-ui(注意还有样式文件)

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>document</title>
  <!-- elelment-ui样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<body>
  
</body>
<!-- 引入vue -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!-- 引入element-ui -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
</html>

接下来就可以写我们的打码功能啦

实现思路

  • 创建canvas画布,并将要打码的图片绘制上去
  • 监听鼠标在图片上的点击,移动、松开事件,在canvas画布上绘制要打码的区域
  • 处理绘制的打码区域
  • 保存打码后的图片

将要打码的图片绘制到canvas画布上

// 初始化 绘制图片
tocode (currentimg) {
  this.$nexttick(() => {
    // 获取将要绘制的canvas的父元素节点
    let parentid = document.getelementbyid('parentid')
    // 初始化图片
    let drawimg = new image()
    drawimg.setattribute('crossorigin', 'anonymous')
    drawimg.crossorigin = 'anonymous'
    drawimg.src = currentimg
    // 创建canvas元素并添加到父节点中
    let addcanvas = document.createelement('canvas')
    parentid.appendchild(addcanvas)
    let canvas = parentid.lastelementchild
    canvas.id = 'imgcanvas'
    if (canvas.getcontext) {
      let ctx = canvas.getcontext('2d')
      // 绘制图片
      drawimg.onload = function () {
        canvas.width = 720
        canvas.height = 500
        ctx.drawimage(drawimg, 0, 0, 720, 500)
      }
    }
  })
}

点击打码按钮,绘制打码区域

思路:

  • 鼠标点击,获取点击时的坐标,每次点击前可能会存在打过码的区域,先清除画布,重新绘制图片
  • 鼠标移动,开始绘制打码的矩形,通过移动的坐标和上面点击的点坐标确定绘制的矩形坐标和宽高
  • 将绘制的打码矩形,分割成一个个宽高15像素的小正方形,并给每个小正方形生产随机颜色
  • 鼠标松开,停止绘制矩形
// 打码
dialogcode (img) {
  let parentid = document.getelementbyid('parentid')
  let canvas = document.getelementbyid('imgcanvas')
  if (canvas.getcontext) {
    let ctx = canvas.getcontext('2d')
    let drawimage = new image()
    drawimage.crossorigin = 'anonymous'
    drawimage.src = img
    drawimage.onload = () => {
      ctx.drawimage(drawimage, 0, 0, 720, 500)
    }
    // 鼠标点击
    parentid.onmousedown = e => {
      ctx.clearrect(0, 0, canvas.width, canvas.height)
      ctx.drawimage(drawimage, 0, 0, 720, 500)
      this.flag = true
      this.clickx = e.offsetx // 鼠标点击时的x
      this.clicky = e.offsety // 鼠标点击时的y
    }
    // 鼠标松开
    parentid.onmouseup = () => {
      this.flag = false
    }
    // 鼠标按下
    parentid.onmousemove = e => {
      if (this.flag) {
        ctx.clearrect(0, 0, canvas.width, canvas.height)
        ctx.drawimage(drawimage, 0, 0, 720, 500)
        ctx.beginpath()
        let pixels = [] // 二维数组,每个子数组有5个值(绘制矩形左上角的x坐标、y坐标,矩形的宽、高,生成的4位随机数用于颜色值)
        for (let x = 0; x < (e.offsetx - this.clickx) / 15; x++) {
          for (let y = 0; y < (e.offsety - this.clicky) / 15; y++) {
            pixels.push([(x * 15 + this.clickx), (y * 15 + this.clicky), 15, 15, math.floor(math.random() * 9999)])
          }
          for (let y = 0; y > (e.offsety - this.clicky) / 15; y--) {
            pixels.push([(x * 15 + this.clickx), (y * 15 + this.clicky), 15, 15, math.floor(math.random() * 9999)])
          }
        }
        for (let x = 0; x > (e.offsetx - this.clickx) / 15; x--) {
          for (let y = 0; y > (e.offsety - this.clicky) / 15; y--) {
            pixels.push([(x * 15 + this.clickx), (y * 15 + this.clicky), 15, 15, math.floor(math.random() * 9999)])
          }
          for (let y = 0; y < (e.offsety - this.clicky) / 15; y++) {
            pixels.push([(x * 15 + this.clickx), (y * 15 + this.clicky), 15, 15, math.floor(math.random() * 9999)])
          }
        }
        // 遍历数组绘制小正方形块
        for (let i = 0; i < pixels.length; i++) {
          ctx.fillstyle = '#bf' + pixels[i][4]
          ctx.fillrect(pixels[i][0], pixels[i][1], pixels[i][2], pixels[i][3])
        }
        ctx.fill()
        ctx.closepath()
      }
    }
  }
}

保存

// 保存
dialogupload () {
  let canvas = document.getelementbyid('imgcanvas')
  let tempimg = canvas.todataurl('image/png')
  let imgurl = document.getelementbyid('imgurl')
  imgurl.crossorigin = 'anonymous'
  imgurl.src = tempimg
}

源码

复制到html文件可预览

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>使用canvas一步步实现图片打码功能</title>
  <!-- elelment-ui样式 -->
  <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
  <style type="text/css">
    .rc-code__buttons {
      margin: 20px;
    }
  </style>
</head>
<body>
  <div id="app">
    <div class="rc-code__buttons">
      <h1>vue项目中使用canvas一步步实现图片打码功能</h1>
      <el-button type="primary" @click="dialogcode(data.img_url)">打码</el-button>
      <el-button type="success" @click="dialogupload()">保存</el-button>
    </div>
    <el-row>
      <el-col :span="12"><h3>点击打码按钮,在图片上绘制打码区域; 点击保存,生成打码后的图片</h3></el-col>
      <el-col :span="12"><h3>保存后的图片</h3></el-col>
      <el-col :span="12"><div id="parentid"></div></el-col>
      <el-col :span="12"><img id="imgurl"/></el-col>
    </el-row>
  </div>
</body>
<!-- 引入vue -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<!-- 引入element-ui -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
new vue({
  el: '#app',
  data () {
    return {
      data: {
        img_url: 'https://avatars0.githubusercontent.com/u/26196557?s=460&v=4'
      },
      flag: false, // 是否绘制矩形
      clickx: '', // 开始绘制矩形时,鼠标点击时的x坐标
      clicky: '' // 开始绘制矩形时,鼠标点击时的y坐标
    }
  },
  mounted() {
    this.tocode(this.data.img_url)
  },
  methods: {
    // 初始化 绘制图片
    tocode (currentimg) {
      this.$nexttick(() => {
        let parentid = document.getelementbyid('parentid')
        let drawimg = new image()
        drawimg.setattribute('crossorigin', 'anonymous')
        drawimg.crossorigin = 'anonymous'
        drawimg.src = currentimg
        let addcanvas = document.createelement('canvas')
        parentid.appendchild(addcanvas)
        let canvas = parentid.lastelementchild
        canvas.id = 'imgcanvas'
        if (canvas.getcontext) {
          let ctx = canvas.getcontext('2d')
          drawimg.onload = function () {
            canvas.width = 720
            canvas.height = 500
            ctx.drawimage(drawimg, 0, 0, 720, 500)
          }
        }
      })
    },
    // 打码
    dialogcode (img) {
      let parentid = document.getelementbyid('parentid')
      let canvas = document.getelementbyid('imgcanvas')
      if (canvas.getcontext) {
        let ctx = canvas.getcontext('2d')
        let drawimage = new image()
        drawimage.crossorigin = 'anonymous'
        drawimage.src = img
        drawimage.onload = () => {
          ctx.drawimage(drawimage, 0, 0, 720, 500)
        }
        parentid.onmousedown = e => {
          ctx.clearrect(0, 0, canvas.width, canvas.height)
          ctx.drawimage(drawimage, 0, 0, 720, 500)
          this.flag = true
          this.clickx = e.offsetx // 鼠标点击时的x
          this.clicky = e.offsety // 鼠标点击时的y
        }
        parentid.onmouseup = () => {
          this.flag = false
        }
        parentid.onmousemove = e => {
          if (this.flag) {
            ctx.clearrect(0, 0, canvas.width, canvas.height)
            ctx.drawimage(drawimage, 0, 0, 720, 500)
            ctx.beginpath()
            let pixels = [] // 二维数组,每个子数组有5个值(绘制矩形左上角的x坐标、y坐标,矩形的宽、高,生成的4位随机数用于颜色值)
            for (let x = 0; x < (e.offsetx - this.clickx) / 15; x++) {
              for (let y = 0; y < (e.offsety - this.clicky) / 15; y++) {
                pixels.push([(x * 15 + this.clickx), (y * 15 + this.clicky), 15, 15, math.floor(math.random() * 9999)])
              }
              for (let y = 0; y > (e.offsety - this.clicky) / 15; y--) {
                pixels.push([(x * 15 + this.clickx), (y * 15 + this.clicky), 15, 15, math.floor(math.random() * 9999)])
              }
            }
            for (let x = 0; x > (e.offsetx - this.clickx) / 15; x--) {
              for (let y = 0; y > (e.offsety - this.clicky) / 15; y--) {
                pixels.push([(x * 15 + this.clickx), (y * 15 + this.clicky), 15, 15, math.floor(math.random() * 9999)])
              }
              for (let y = 0; y < (e.offsety - this.clicky) / 15; y++) {
                pixels.push([(x * 15 + this.clickx), (y * 15 + this.clicky), 15, 15, math.floor(math.random() * 9999)])
              }
            }
            for (let i = 0; i < pixels.length; i++) {
              ctx.fillstyle = '#bf' + pixels[i][4]
              ctx.fillrect(pixels[i][0], pixels[i][1], pixels[i][2], pixels[i][3])
            }
            ctx.fill()
            ctx.closepath()
          }
        }
      }
    },
    // 保存
    dialogupload () {
      let canvas = document.getelementbyid('imgcanvas')
      let tempimg = canvas.todataurl('image/png')
      let imgurl = document.getelementbyid('imgurl')
      imgurl.crossorigin = 'anonymous'
      imgurl.src = tempimg
    }
  }
})
</script>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。