Turn audio into a shareable video. forked from nypublicradio/audiogram

index.js 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. var d3 = require("d3"),
  2. patterns = require("./patterns.js"),
  3. sample = require("./sample-wave.js"),
  4. textWrapper = require("./text-wrapper.js");
  5. module.exports = function(context) {
  6. context.patternQuality = "best";
  7. var renderer = {};
  8. renderer.context = context;
  9. renderer.update = function(options) {
  10. // TODO cleaner defaults
  11. options.backgroundColor = options.backgroundColor || "#fff";
  12. options.waveColor = options.waveColor || options.foregroundColor || "#000";
  13. options.captionColor = options.captionColor || options.foregroundColor || "#000";
  14. if (typeof options.waveTop !== "number") options.waveTop = 0;
  15. if (typeof options.waveBottom !== "number") options.waveBottom = options.height;
  16. if (typeof options.waveLeft !== "number") options.waveLeft = 0;
  17. if (typeof options.waveRight !== "number") options.waveRight = options.width;
  18. this.wrapText = textWrapper(context, options);
  19. this.options = options;
  20. this.waveform = options.waveform || [sample.slice(0, options.samplesPerFrame)];
  21. return this;
  22. };
  23. // Get the waveform data for this frame
  24. renderer.getWaveform = function(frameNumber) {
  25. return this.waveform[Math.min(this.waveform.length - 1, frameNumber)];
  26. };
  27. // Draw the frame
  28. renderer.drawFrame = function(frameNumber) {
  29. // Draw the background image and/or background color
  30. context.clearRect(0, 0, this.options.width, this.options.height);
  31. context.fillStyle = this.options.backgroundColor;
  32. context.fillRect(0, 0, this.options.width, this.options.height);
  33. if (this.backgroundImage) {
  34. context.drawImage(this.backgroundImage, 0, 0, this.options.width, this.options.height);
  35. }
  36. patterns[this.options.pattern || "wave"](context, this.getWaveform(frameNumber), this.options);
  37. // Write the caption
  38. if (this.caption) {
  39. this.wrapText(this.caption);
  40. }
  41. return this;
  42. };
  43. return renderer;
  44. }