browser.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. var canPromise = require('./can-promise')
  2. var QRCode = require('./core/qrcode')
  3. var CanvasRenderer = require('./renderer/canvas')
  4. var SvgRenderer = require('./renderer/svg-tag.js')
  5. function renderCanvas (renderFunc, canvas, text, opts, cb) {
  6. var args = [].slice.call(arguments, 1)
  7. var argsNum = args.length
  8. var isLastArgCb = typeof args[argsNum - 1] === 'function'
  9. if (!isLastArgCb && !canPromise()) {
  10. throw new Error('Callback required as last argument')
  11. }
  12. if (isLastArgCb) {
  13. if (argsNum < 2) {
  14. throw new Error('Too few arguments provided')
  15. }
  16. if (argsNum === 2) {
  17. cb = text
  18. text = canvas
  19. canvas = opts = undefined
  20. } else if (argsNum === 3) {
  21. if (canvas.getContext && typeof cb === 'undefined') {
  22. cb = opts
  23. opts = undefined
  24. } else {
  25. cb = opts
  26. opts = text
  27. text = canvas
  28. canvas = undefined
  29. }
  30. }
  31. } else {
  32. if (argsNum < 1) {
  33. throw new Error('Too few arguments provided')
  34. }
  35. if (argsNum === 1) {
  36. text = canvas
  37. canvas = opts = undefined
  38. } else if (argsNum === 2 && !canvas.getContext) {
  39. opts = text
  40. text = canvas
  41. canvas = undefined
  42. }
  43. return new Promise(function (resolve, reject) {
  44. try {
  45. var data = QRCode.create(text, opts)
  46. resolve(renderFunc(data, canvas, opts))
  47. } catch (e) {
  48. reject(e)
  49. }
  50. })
  51. }
  52. try {
  53. var data = QRCode.create(text, opts)
  54. cb(null, renderFunc(data, canvas, opts))
  55. } catch (e) {
  56. cb(e)
  57. }
  58. }
  59. exports.create = QRCode.create
  60. exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)
  61. exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)
  62. // only svg for now.
  63. exports.toString = renderCanvas.bind(null, function (data, _, opts) {
  64. return SvgRenderer.render(data, opts)
  65. })