Complete code:Github.com/MXHOO/canva…

The compressed image

  1. Access to the file
  2. Draw on the canvas using cxt.drawImage
  3. Compress using Canvas.todataURL
  4. The specific implementation
function compress(file) {
  return new Promise((reslove, reject) = > {
    let afterResult = ' '
    const img = new Image()
    getBase64(file).then(data= > {
      img.src = data
    }).catch(error= > console.log(error))
    img.onload = function() {
      const canvas = document.createElement('canvas')
      const context = canvas.getContext('2d')
      canvas.width = this.width
      canvas.height = this.height
      /* drawImage(img, sx, sy, swidth, sheight, x, y, width, height): drawImage(img, sx, sy, swidth, sheight, x, y, width, height): drawImage(img, sx, sy, swidth, sheight, x, y, width, height): Swidth: width of the clipped image sheight: height of the clipped image x: X coordinate y placed on the canvas: Height: Width of the image to be used (expand/shrink) */
     context.drawImage(before, 0.0)
      /* toDataURL(type, quailty): returns aURL containing the image display parameter: type: image format, image/ PNG by default quailty: When type is image, the image quality can be selected from 0 to 1 */
      afterResult = canvas.toDataURL(file.type, 0.5)
      reslove(afterResult)
    }
    img.onerror = function(err) {
      reject(err)
    }
  }) 
}
Copy the code

Add a watermark

  1. Draw the watermark pattern according to the requirements
  2. Set the watermark as the background
  3. The specific implementation
// Create a watermark
function createImage(text){
  const canvas = document.createElement('canvas')
  const ctx= canvas.getContext('2d')
  canvas.height = 50
  canvas.width = 100
  ctx.font = '20px'
  ctx.fillStyle = "Rgba (100100100,0.1)"
  ctx.fillText(text, 20.20)
  ctx.rotate(30*Math.PI/180)
  return canvas.toDataURL('image/png')}// Add a watermark
function watermark() {
  const url = createImage('Test data')
  const watermark = document.getElementById('watermark')
  watermark.style.background = 'url(' + url + ') repeat top left'
}
Copy the code