context.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. export const uniContext = (ctx) => {
  2. const ALIAS_ATTRS_MAP = [
  3. 'lineCap',
  4. 'strokeStyle',
  5. 'lineWidth',
  6. 'fillStyle',
  7. ]
  8. ALIAS_ATTRS_MAP.forEach(style => {
  9. Object.defineProperty(ctx, style, {
  10. set: value => {
  11. if(value)
  12. ctx[`set${style.charAt(0).toUpperCase()}${style.slice(1)}`](value)
  13. }
  14. })
  15. })
  16. ctx.uniDrawImage = ctx.drawImage
  17. ctx.drawImage = (image,...agrs) => {
  18. ctx.uniDrawImage(image.src, ...agrs)
  19. }
  20. return ctx
  21. }
  22. class Image {
  23. constructor() {
  24. this.currentSrc = null
  25. this.naturalHeight = 0
  26. this.naturalWidth = 0
  27. this.width = 0
  28. this.height = 0
  29. this.tagName = 'IMG'
  30. }
  31. set src(src) {
  32. this.currentSrc = src
  33. uni.getImageInfo({
  34. src,
  35. success: (res) => {
  36. this.naturalWidth = this.width = res.width
  37. this.naturalHeight = this.height = res.height
  38. this.onload()
  39. },
  40. fail: () => {
  41. this.onerror()
  42. }
  43. })
  44. }
  45. get src() {
  46. return this.currentSrc
  47. }
  48. }
  49. export const createImage = () => {
  50. return new Image()
  51. }
  52. export const toDataURL = (canvasId, com) => {
  53. return new Promise((resolve, reject) => {
  54. uni.canvasToTempFilePath({
  55. canvasId,
  56. success: (res) => {
  57. resolve(res.tempFilePath)
  58. },
  59. fail: reject
  60. }, com)
  61. })
  62. }