Draw on a Canvas with Code Injection In Ghost

Ghost allows you to inject arbitrary code / html into any post. You can do this by using the code injection feature, and enclosing your code in a <script> tag. We can use code injection to add interactivity to regular html elements. A particularly fun one to play with is the canvas. I added a canvas above using the following code. Try clicking on it.

<canvas id="canvas" width="700" height="300"></canvas>

To achieve the interactivity you see above, we create explosions of colour whenever a mouse click is detected using javascript. You can add this kind of interactivity by using the code injection option on the post sidebar.

Start by injecting code that gets a reference to the canvas, and fills it with a black retangle. You can paste the following into the Post Footer area:

<script>
  var canvas = document.querySelector("#canvas");
  var ctx = canvas.getContext('2d');
  ctx.fillStyle = "rgb(0,0,0)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
</script>

Once you have that working, start adding a listener for clicks on the page.

document.body.addEventListener("click", function (event) {
    var x = event.clientX,
        y = event.clientY;
    console.table(x,y)
})

This should get you started on some basic canvas development. The code you see running on this page is borrowed from this epic code pen. Check it out for some really fun particle math.