canvas.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. var Utils = require('./utils')
  2. function clearCanvas (ctx, canvas, size) {
  3. ctx.clearRect(0, 0, canvas.width, canvas.height)
  4. if (!canvas.style) canvas.style = {}
  5. canvas.height = size
  6. canvas.width = size
  7. canvas.style.height = size + 'px'
  8. canvas.style.width = size + 'px'
  9. }
  10. function getCanvasElement () {
  11. try {
  12. return document.createElement('canvas')
  13. } catch (e) {
  14. throw new Error('You need to specify a canvas element')
  15. }
  16. }
  17. exports.render = function render (qrData, canvas, options) {
  18. var opts = options
  19. var canvasEl = canvas
  20. if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
  21. opts = canvas
  22. canvas = undefined
  23. }
  24. if (!canvas) {
  25. canvasEl = getCanvasElement()
  26. }
  27. opts = Utils.getOptions(opts)
  28. var size = Utils.getImageWidth(qrData.modules.size, opts)
  29. var ctx = canvasEl.getContext('2d')
  30. var image = ctx.createImageData(size, size)
  31. Utils.qrToImageData(image.data, qrData, opts)
  32. clearCanvas(ctx, canvasEl, size)
  33. ctx.putImageData(image, 0, 0)
  34. return canvasEl
  35. }
  36. exports.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
  37. var opts = options
  38. if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
  39. opts = canvas
  40. canvas = undefined
  41. }
  42. if (!opts) opts = {}
  43. var canvasEl = exports.render(qrData, canvas, opts)
  44. var type = opts.type || 'image/png'
  45. var rendererOpts = opts.rendererOpts || {}
  46. return canvasEl.toDataURL(type, rendererOpts.quality)
  47. }