canvas转各种格式

/**
 * canvas转化为base64
 * @param {canvas} canvas 对象
 * @param {type} 图片类型,值为'image/png'、'image/jpeg'
 */
export const canvasToBase64 = (canvas,type) => {
  return canvas.toDataURL(type)
}

/**
 * canvas转化为图片
 * @param {canvas} canvas 对象
 * @param {type} 图片类型,值为'image/png'、'image/jpeg'
 */
export const canvasToImg = (canvas,type)  =>  {
  const image = new Image()
  image.src = canvas.toDataURL(type)
  return image
}

/**
 * base64转化为file
 * @param {urlData} base64内容
 * @param {fileName} 文件名称
 */
export const base64ToFile = (urlData, fileName) => {
  const arr = urlData.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bytes = atob(arr[1])
  let n = bytes.length
  const ia = new Uint8Array(n)
  while (n--) {
    ia[n] = bytes.charCodeAt(n)
  }
  return new File([ia], fileName, { type: mime })
}

你可能感兴趣的:(canvas,javascript,前端,canvas)