javascriptcanvashooktodataurl

Hook canvas's toDataURL


[EDIT] I should have been more specific (thanks for the response Below the Radar!). I'd like the trigger to console.log to capture the returned URI when the object calls toDataURL. In the linked jsfiddle, the object calling toDataURL is canvas. This may be a sticking point, because I may need to capture the calling object as well? I could accomplish what I want by simply encapsulating canvas.toDataURL() in a console.log statement, but I'd like this to be more dynamic than that---which led me to think of adding a hook on toDataURL

jsFiddle, update: https://jsfiddle.net/spe4q1d8/170/


I'm trying to create a hook that I could place at the top or bottom of a JavaScript file which would trigger console.log every time a specific function is called. The particular function I want to hook is toDataURL() HTMLCanvasElement.toDataURL().

I've been able to set up a hook on something like alert or console.log itself, but can't figure out how to hook toDataURL.

jsFiddle, hook on alert and hook on document.createElement()

References


Solution

  • you can extend the prototyped function for instance:

    var toDataURL = HTMLCanvasElement.prototype.toDataURL;
    HTMLCanvasElement.prototype.toDataURL = function(type, encoderOptions) {
      var uri = toDataURL.call(this, type, encoderOptions);
      console.log(uri);
      return uri;
    }
    
    var canvas = document.createElement('canvas');
    canvas.toDataURL()