Time for action – drawing to the canvas

Let's take a look at a quick example of drawing a non-animated shape. We don't even need jQuery for this.

  1. Add the <canvas> element to the <body> of our template file:
    <canvas id="c" width="500" height="300">
      <p>Your browser doesn't support the canvas element!</p>
    </canvas>
  2. Next we can add the JavaScript that will draw to the <canvas>. We'll draw a Union Jack flag. Function in the <script> element at the bottom of the template file and add the following code in its place:
    var canvas = document.getElementById("c"), context = canvas.getContext("2d"); context.fillStyle = "#039"; context.fillRect(50, 50, 400, 200); context.beginPath(); context.strokeStyle = "#fff"; context.lineWidth = 50; context.moveTo(250, 50); ...

Get jQuery 1.4 Animation Techniques Beginner's Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.