imageFunction.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. import imgList from './images/logoWatermark.png'
  2. export const imgToCanvas = async (url: string) => {
  3. console.log('imgToCanvas', url)
  4. const img = document.createElement('img')
  5. img.setAttribute('crossOrigin', 'anonymous')
  6. img.src = url + `?${new Date().getTime()}`
  7. // 防止跨域引起的 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
  8. await new Promise(resolve => (img.onload = resolve))
  9. // 创建canvas DOM元素,并设置其宽高和图片一样
  10. const canvas = document.createElement('canvas')
  11. canvas.width = img.width
  12. canvas.height = img.height
  13. // 坐标(0,0) 表示从此处开始绘制,相当于偏移。
  14. const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
  15. ctx.fillStyle = 'rgb(255, 255, 255)'
  16. ctx.fillStyle = '#fff'
  17. ctx.fillRect(0, 0, img.width, img.height)
  18. ctx.drawImage(img, 0, 0)
  19. return canvas
  20. }
  21. /* canvas添加水印
  22. * @param {canvas对象} canvas
  23. * @param {水印文字} text
  24. */
  25. export const addWatermark = async (canvas, text) => {
  26. console.log('addWatermark')
  27. try {
  28. const ctx = canvas.getContext('2d')
  29. // ctx.fillStyle = '#fff'
  30. const img = document.createElement('img')
  31. img.setAttribute('crossOrigin', 'anonymous')
  32. img.src = imgList + `?${new Date().getTime()}`
  33. // 防止跨域引起的 Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
  34. await new Promise(resolve => (img.onload = resolve))
  35. // 创建canvas DOM元素,并设置其宽高和图片一样
  36. const water = document.createElement('canvas')
  37. water.width = 600
  38. water.height = 500
  39. // 第一层
  40. const waterCtx = water.getContext('2d') as CanvasRenderingContext2D
  41. waterCtx.clearRect(0, 0, water.width, water.height)
  42. // 小水印中文字偏转角度
  43. waterCtx.rotate((-30 * Math.PI) / 180)
  44. waterCtx.drawImage(img, 0, 300)
  45. const pat = ctx.createPattern(water, 'repeat')
  46. ctx.fillStyle = pat
  47. ctx.fillRect(0, 0, canvas.width, canvas.height)
  48. return canvas
  49. } catch (e) {
  50. console.log(e)
  51. }
  52. }
  53. export const addMusicTitle = (canvas, info) => {
  54. canvas.getContext('2d')
  55. const water = document.createElement('canvas')
  56. // 小水印画布大小
  57. water.width = canvas.width
  58. water.height = canvas.height + 30
  59. const waterCtx = water.getContext('2d') as CanvasRenderingContext2D
  60. waterCtx.fillStyle = '#fff'
  61. waterCtx.fillRect(0, 0, canvas.width, canvas.height + 70)
  62. waterCtx.font = `40pt Calibri`
  63. waterCtx.fillStyle = '#000'
  64. waterCtx.textAlign = 'center'
  65. waterCtx.drawImage(canvas, 0, 70)
  66. waterCtx.fillText(info.title, canvas.width / 2, 120)
  67. return water
  68. }
  69. export const convasToImg = canvas => {
  70. return canvas.toDataURL('image/png')
  71. }