Updating drawing with codemirror contents

Hi all,

Problem statement

I am struggling to understand how to pass the contents of a codemirror editor (when it’s updated manually on screen, by deleting or add new code) to a p5.js instance, on a button click.

In other words, how can I refresh and generate a new p5.js instance using only the current code from the codemirror instance on screen each time the button is pressed?

Issue detail

I’ve constructed the extremely basic code file below, it’s a simple HTML page, which has a loaded Codemirror File.

Every time ‘Update Code’ is pressed, it prints the current contents of the codemirror instance to the console. So for example, its possible to change the Ellipse size in the codemirror instance; pressing the button will then print this updated code to the console. I want that updated code to also be reflected in the p5js instance below.

Ultimate Aim

  • I would like to be able to refresh the p5.js output via the button click for any changes made to the codemirror instance

Code

Please excuse any and all formatting / indenting (please open in codepen or the like):



<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/mode/javascript/javascript.min.js"></script>

<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/theme/dracula.min.css">

<body>
  <font size="4">
    <form>
      <textarea id="jsCode">
  function setup() {
    createCanvas(400, 400);
  }

  function draw() {
  background(220);
  ellipse(200,200,20);
  }
      </textarea>
    </form>
  </font>
</body>


<script id="newx">
        editor = CodeMirror.fromTextArea(document.getElementById('jsCode'), {
            mode: 'javascript', 
            lineNumbers:true,
            theme: 'dracula',
            electricChars: true,
            scrollbarStyle: "null",
        });
</script>

          <script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.2.0/p5.js"></script>

          
          <p>Click the button to update the drawing</p>

          <button onclick="function3()">Run Code</button>

          <script>
            eval(editor.getValue());
          </script>

          <script>
            function function3(){
              console.log(editor.getValue());
            }
          </script>

Hi all - as an update what i’m effectively trying to do is literally exactly this (the run button):