imageFunction.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. export const imgToCanvas = async (url: string) => {
  2. const img = document.createElement('img')
  3. img.src = url
  4. img.setAttribute('crossOrigin', 'anonymous') // 防止跨域引起的 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
  5. await new Promise(resolve => (img.onload = resolve))
  6. // 创建canvas DOM元素,并设置其宽高和图片一样
  7. const canvas = document.createElement('canvas')
  8. canvas.width = img.width
  9. canvas.height = img.height
  10. // 坐标(0,0) 表示从此处开始绘制,相当于偏移。
  11. let ctx = canvas.getContext('2d') as CanvasRenderingContext2D
  12. ctx.fillStyle = 'rgb(255, 255, 255)'
  13. ctx.fillStyle = '#fff'
  14. ctx.fillRect(0, 0, img.width, img.height)
  15. ctx.drawImage(img, 0, 0)
  16. return canvas
  17. }
  18. /* canvas添加水印
  19. * @param {canvas对象} canvas
  20. * @param {水印文字} text
  21. */
  22. export const addWatermark = (canvas, text) => {
  23. const ctx = canvas.getContext('2d')
  24. // ctx.fillStyle = '#fff'
  25. const water = document.createElement('canvas')
  26. // 小水印画布大小
  27. water.width = 500
  28. water.height = 300
  29. // 第一层
  30. const waterCtx = water.getContext('2d') as CanvasRenderingContext2D
  31. waterCtx.clearRect(0, 0, water.width, water.height)
  32. // 小水印中文字偏转角度
  33. waterCtx.rotate((-25 * Math.PI) / 180)
  34. // waterCtx.translate(-30, -30)
  35. waterCtx.font = '50pt Calibri' // 水印文字添加
  36. waterCtx.fillStyle = 'rgba(149,155,170,0.2)'
  37. waterCtx.fillText('酷乐秀', -10,180)
  38. const pat = ctx.createPattern(water, 'repeat')
  39. ctx.fillStyle = pat
  40. ctx.fillRect(0, 0, canvas.width, canvas.height)
  41. return canvas
  42. }
  43. export const convasToImg = canvas => {
  44. return canvas.toDataURL('image/png')
  45. }