Question

I want to use HTML to document an algorithm. This will be a local file, so there aren't any security issues.

The idea is to have a <pre> tag containing javascript code. Then, when the page is loaded, a <canvas> element will be rendered according to the the code contents, which must be evaluated.

I believe this would use some sort of eval() of the innerHtml property of the <pre> tag, but I'm not sure.

Was it helpful?

Solution

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>.

jsFiddle

enter image description here

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);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top