How to make html Canvas tag and WebGL code work inside your WordPress posts.

If you tried to add code directly into your WordPress post, using either the <script> tag to add your shader code or the WebGL dependencies, you have realized that it may not work as intended, that’s because WordPress does several formating to any text inside your post editor even if it is in html mode.

Lets review how to work with a html canvas and webgl inside your WordPress posts and content using a little html hack.


There are a couple of html tags that can make it easy for you to tell WordPress what code is meant for display (so it gets handled as just text) and what code is for meant execution.

In Example, if I were to create a simple 200x200px html canvas colored by WebGL, you would probably make a code like this inside the editor.
<canvas width = "200" height = "200" id = "wp_Canvas" > </canvas>
<script>
var canvas = document.getElementById('wp_Canvas');
gl = canvas.getContext('experimental-webgl');
//Insert vertex, shader, fragment and drawing code here
</script>

Expecting to display a canvas like this one:


Which may not be displayed depending on the editor you are working on. This is when the <pre> tag comes in handly.

Quoting directly the WordPress documentation site:
“The <pre> tag instructs the browser to use a monospaced font, but to exactly reproduce whatever is inside of the <pre> tags. Every space, line break, every bit of code is exactly reproduced.”

We make sure our code inside the html editor must include the tag we just learned about.
<pre> <canvas width = "200" height = "200" id = "my_Canvas" > </canvas>
<script>
var canvas = document.getElementById('wp_Canvas');
gl = canvas.getContext('experimental-webgl');
//Insert vertex, shader, fragment and drawing code here
</script>
</pre>

This will allow not only some html tags that get troublesome in the post, but also allows our JavaScript code to be added to our DOM (document object model) appropriately and not as part of text of the post, we can just access our canvas with webgl getting the canvas as you would in any other enviroment.

<pre>
<canvas width = "200" height = "200" id = "wp_Canvas" ></canvas>
<script>
var canvas = document.getElementById('wp_Canvas');
gl = canvas.getContext('experimental-webgl');

// Clear
gl.clearColor(0.5, 0.5, 0.5, 0.9);

// depth test
gl.enable(gl.DEPTH_TEST);

// buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);

// view port
gl.viewport(0,0,canvas.width,canvas.height);

</script>
</pre>

Allowing you in the end, to display an html canvas with graphics elements inside a wordpress post.

 

Leave a Reply

Your email address will not be published. Required fields are marked *