Testing a P5 Javascript magic in a Python kernel:

In [100]:
%%p5

  var x = 100; 
  var y = 100;

  function setup () {
    createCanvas(700, 410);
  };

  function draw () {
    background(0);
    fill(255);
    rect(x,y,50,50);
  };
Out[100]:
In [101]:
%%p5

  var x = 100; 
  var y = 100;

  function setup () {
    createCanvas(600, 400);
  };

  function draw () {
    background(0);
    fill(255);
    rect(x,y,150,150);
  };
Out[101]:
In [102]:
%%p5 

var capture;

function setup() {
  createCanvas(390, 240);
  capture = createCapture(VIDEO);
  capture.size(320, 240);
  //capture.hide();
}

function draw() {
  background(255);
  image(capture, 0, 0, 320, 240);
  filter('INVERT');
}
Out[102]:

The magic:

In [99]:
from IPython.core.magic import register_cell_magic
from IPython.display import IFrame

TEMPLATE = """
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/addons/p5.dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.6/addons/p5.sound.js"></script>

</head>
<body>
<h3>Script: %(name)s</h3>
<script>
%(script)s
</script>
</body>
</html>
"""

COUNT = 0

@register_cell_magic
def p5(line, cell):
    global COUNT
    filename = "p5-%s.html" % COUNT
    COUNT += 1
    with open(filename, "w") as fp:
        fp.write(TEMPLATE % {"script": cell, "name": filename})
    return IFrame(filename, width="100%", height="400")

del p5