Drawing fillRect through SoundCloud's waveform.js not working

368 views Asked by At

I am trying to use waveform.js found on http://www.waveformjs.org to draw waveforms of SoundCloud tracks. It hasn't been working so I've stripped down waveform.js to a bare bones form that attempts to draw a fillRect in a newly created canvas element through a Waveform object. The canvas element is successfully created but the fillRect does not appear. I've contrasted this to the direct creation of a canvas element and fillRect, which both work.

Here is the HTML:

<!DOCTYPE html>
 <html>
   <head>
       <meta charset="UTF-8">
       <title>Sample document</title>
   </head>
   <body>
        <div id="example1"></div>
        <hr>
        <div id="example2"></div>
   </body>
       <script src="waveform.js"></script>
       <script src="script.js"></script>
 </html>

Here is script.js:

var canvas, container;

// Creating canvas element and rect in example1
canvas = document.createElement("canvas");
canvas.setAttribute("id", "canvas");
container = document.getElementById("example1");
container.appendChild(canvas);
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.fillRect(20,20,50,100);
// Both created successfully

// Creating canvas element and rect in example2, through waveform object
var waveform = new Waveform({
    container: document.getElementById("example2")
});
// Canvas element created successfully, no rectangle

Here is waveform.js:

(function() {

    var Waveform;

    window.Waveform = Waveform = (function() {

        Waveform.name = 'Waveform';

        function Waveform(options) {
            this.container = options.container;
            this.canvas = this.createCanvas(this.container, this.container.clientWidth, this.container.clientHeight);
            this.context = this.canvas.getContext("2d");
            this.width = parseInt(this.context.canvas.width, 10);
            this.height = parseInt(this.context.canvas.height, 10);
            this.makeRect();
        };

        Waveform.prototype.createCanvas = function(container, width, height) {
          var canvas;
          canvas = document.createElement("canvas");
          canvas.setAttribute("id", "wfCanvas");
          container.appendChild(canvas);
          canvas.width = width;
          canvas.height = height;
          return canvas;
        };

        Waveform.prototype.makeRect = function() {
          var wfCanvas = document.getElementById("wfCanvas");
          var ctx = wfCanvas.getContext("2d");
          ctx.fillRect(20,20,50,100);
        }

        return Waveform;

    })();

}).call(this);
1

There are 1 answers

0
ShibbyOpSec1337 On

Bruh you're way over doing it.

Just be sure that the container you are applying the waveform to has PIXEL DIMENSIONS defined as either css or inline.