You can indeed run code inside a <pre>
using innerHTML
to get the code and then eval()
. I've added the HTML5 contenteditable
attribute to our <pre>
so we can edit it like a <textarea>
.
HTML
<pre id="code" contenteditable>var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.moveTo(10,10);
context.lineTo(40,40);
context.stroke();</pre>
<button id="run">Run</button>
<canvas width="400" height="300" id="canvas"></canvas>
JavaScript
var button = document.getElementById('run');
button.onclick = function () {
var code = document.getElementById('code').innerHTML;
eval(code);
};