index.js 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import barcode from './barcode'
  2. import { getSystemInfoSync } from '../helpers/hooks/useNativeAPI'
  3. import { toDataURL, getCanvasRef } from '../helpers/hooks/useCanvasAPI'
  4. const defalutOptions = {
  5. number: true,
  6. prefix: true,
  7. color: 'black',
  8. debug: false,
  9. onValid() {},
  10. onInvalid() {},
  11. onSuccess() {},
  12. onError() {},
  13. }
  14. Component({
  15. properties: {
  16. width: {
  17. type: Number,
  18. value: 200,
  19. },
  20. height: {
  21. type: Number,
  22. value: 100,
  23. },
  24. number: {
  25. type: String,
  26. value: '',
  27. },
  28. options: {
  29. type: Object,
  30. value: { ...defalutOptions },
  31. },
  32. canvasId: {
  33. type: String,
  34. value: 'wux-barcode',
  35. },
  36. },
  37. observers: {
  38. ['canvasId, number, width, height, options'](...args) {
  39. const [
  40. canvasId,
  41. number,
  42. width,
  43. height,
  44. options,
  45. ] = args
  46. this.draw({
  47. canvasId,
  48. number,
  49. width,
  50. height,
  51. options,
  52. })
  53. },
  54. },
  55. methods: {
  56. draw(opts = {}) {
  57. const props = {
  58. ...this.data,
  59. ...opts,
  60. }
  61. const {
  62. canvasId,
  63. number: value,
  64. width,
  65. height,
  66. options: oldOptions,
  67. } = props
  68. const {
  69. number,
  70. prefix,
  71. color,
  72. debug,
  73. } = {
  74. ...defalutOptions,
  75. ...oldOptions,
  76. }
  77. const options = {
  78. number,
  79. prefix,
  80. color,
  81. debug,
  82. }
  83. getCanvasRef(canvasId, this).then((canvas) => {
  84. ['onValid', 'onInvalid', 'onSuccess', 'onError'].forEach((method) => {
  85. const oldCb = oldOptions[method]
  86. options[method] = () => {
  87. if (oldCb) {
  88. oldCb()
  89. }
  90. if (method === 'onSuccess') {
  91. toDataURL({ width, height }, canvas)
  92. .then((base64Url) => {
  93. const ctx = canvas.getContext('2d')
  94. ctx.restore()
  95. this.triggerEvent('load', { base64Url })
  96. })
  97. }
  98. this.triggerEvent(method.replace(/^on/, '').toLocaleLowerCase())
  99. }
  100. })
  101. new barcode(canvas, getSystemInfoSync(['window']).pixelRatio, value, Object.assign({ width, height }, options))
  102. })
  103. },
  104. },
  105. })