利用canvas對圖片進行切割


使用input標簽選擇一張圖片, 然后利用canvas對圖片進行切割, 可以設置切割的行數和列數

這是html代碼

...
<input type="file" id="input">
...

 這是js代碼

class SplitImage {
    constructor (options) {
      this.options = {
        col: 3,
        row: 3,
        inputEle: ''
      }
      this.options = Object.assign({}, this.options, options)
      if (!this.options.inputEle) {
        throw new Error('Options.inputEle is invalid! Please check!')
      }
      this.input = null
      this.canvas = null
      this.ctx = null
      this.img = null
      this.init()
    }
    init () {
      this.input = document.querySelectorAll(this.options.inputEle)[0]
      this.input.onchange = this.fileChange.bind(this)
      this.createCanvas()
    }
    async fileChange () {
      let file = this.input.files[0]
      try {
        let base64 = await this.fileReader(file)
        try {
          await this.createImg(base64)
          this.splitImg()
        } catch (e) {
          console.log(e)
        }
      } catch (e) {
        console.log(e)
      }
    }
    fileReader (file) { // 讀取文件base64
      return new Promise((resolve, reject) => {
        const reader  = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = (e) => {
          const result = e.target.result
          resolve(result)
        }
        reader.onerror = (e) => {
          reject(e)
        }
      })
    }
    createImg (base64) { // 加載圖片
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.onload = (e) => {
          this.img = img
          resolve()
        }
        img.onerror = (e) => {
          console.log(e)
          reject(e)
        }
        img.src = base64
      })
    }
    createCanvas () { // 創建canvas
      this.canvas = document.createElement('canvas')
      this.ctx = this.canvas.getContext('2d')
    }
    drawImg (options = {}) { // 繪制圖片
      this.canvas.width = options.width
      this.canvas.height = options.height
      this.ctx.drawImage(this.img, options.x, options.y, options.width, options.height, 0, 0, options.width, options.height)
      const base64 = this.canvas.toDataURL()
      let img = document.createElement('img')
      img.src = base64
      img.style.border = '5px solid red'
      img.style.marginBottom = '-5px'
      document.body.appendChild(img)
    }
    splitImg () { // 切割圖片
      let list = []
      for (let y = 0; y < this.options.row; y++) {
        for (let x = 0; x < this.options.col; x++) {
          let simpleWidth = parseInt(this.img.width / this.options.col)
          let simpleHeight = parseInt(this.img.height / this.options.row)
          list.push({
            x: x * simpleWidth,
            y: y * simpleHeight,
            width: simpleWidth,
            height: simpleHeight
          })
        }
      }
      list.forEach(item => {
        this.drawImg(item)
      })
    }
  }
  let splitImage = new SplitImage({
    col: 2, // 切割圖片的列數
    row: 2, // 切割圖片的行數
    inputEle: '#input' // 標簽選擇器
  })

這是原圖

這是切割之后的圖片,分成了3*3的9宮格圖片,為了看得更清楚, 我給圖片都加上了5px的黑色邊框

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM