0

I'm trying to build a widget in Jupyter Notebook that uses Fabric.js (http://fabricjs.com/), however I'm getting an error that is a blocker for me. The most basic solution I need is just to make the widget output a canvas with an interactive red rectangle, like what you find on the Fabric.js homepage:

enter image description here

What I've tried so far:

I started from the basic "Hello World" tutorial (https://ipywidgets.readthedocs.io/en/stable/examples/Widget%20Custom.html) which is the basis for the four cells below, and I tried to add a simple example from the fabric node webpage to create a red rectangle. Here are the cells I have in Jupyter notebook:

Cell 1:

%%HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.min.js" type="text/javascript"></script>

Cell 2:

import ipywidgets as widgets
from traitlets import Unicode, validate

class HelloWidget(widgets.DOMWidget):
    _view_name = Unicode('HelloView').tag(sync=True)
    _view_module = Unicode('hello').tag(sync=True)
    _view_module_version = Unicode('0.1.0').tag(sync=True)

Cell 3:

%%javascript
require.undef('hello');

define('hello', ["@jupyter-widgets/base"], function(widgets) {

var HelloView = widgets.DOMWidgetView.extend({

    render: function() {
        var canvas = document.createElement('canvas');
        canvas.id = 'canvas';
        canvas.width = 1000;
        canvas.height = 500;
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "blue";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        this.el.appendChild(canvas);

        var fabricCanvas = new fabric.Canvas(canvas);

        var rect = new fabric.Rect({
            top : 100,
            left : 100,
            width : 60,
            height : 70,
            fill : 'red'
        });

        fabricCanvas.add(rect);             
    },
});

return {
    HelloView : HelloView
};
});

Cell 4:

HelloWidget()

However, I unfortunately get the following error in the JS console and it doesn't make the red square:

JS console error

Please help me fix the code to make it work!

Nic Scozzaro
  • 6,651
  • 3
  • 42
  • 46

1 Answers1

0

My problem was I didn't understand how require.js works... :/

Here's how I fixed the problem:

%%javascript
require.undef('hello');
require.config({
  //Define 3rd party plugins dependencies
  paths: {
    fabric: "https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.min"
  }
});
define('hello', ["@jupyter-widgets/base", 'fabric'], function(widgets) {...
Nic Scozzaro
  • 6,651
  • 3
  • 42
  • 46