canvasOperator.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. export default class CanvasOperator {
  2. constructor(canvas) {
  3. this.canvas = canvas
  4. }
  5. /* ---------- RAF 封装 ---------- */
  6. raf(cb) {
  7. if (typeof this.canvas.requestAnimationFrame === 'function') {
  8. return this.canvas.requestAnimationFrame(cb)
  9. }
  10. if (typeof requestAnimationFrame === 'function') {
  11. return requestAnimationFrame(cb)
  12. }
  13. return setTimeout(cb, 16)
  14. }
  15. cancelRaf(id) {
  16. if (typeof this.canvas.cancelAnimationFrame === 'function') {
  17. return this.canvas.cancelAnimationFrame(id)
  18. }
  19. if (typeof cancelAnimationFrame === 'function') {
  20. return cancelAnimationFrame(id)
  21. }
  22. return clearTimeout(id)
  23. }
  24. /* ---------- 图片加载 ---------- */
  25. async loadImage(filePath) {
  26. let img
  27. if (typeof this.canvas.createImage === 'function') {
  28. img = this.canvas.createImage()
  29. }
  30. if (typeof Image !== 'undefined') {
  31. img = new Image()
  32. }
  33. // #ifndef H5
  34. img.crossOrigin = 'anonymous'
  35. // #endif
  36. return new Promise((resolve, reject) => {
  37. img.src = filePath
  38. img.onload = () => resolve(img)
  39. img.onerror = () => {
  40. console.error('[loadImage] 图片加载失败:', filePath, '请检查图片路径')
  41. reject(new Error('图片加载失败'))
  42. }
  43. })
  44. }
  45. }