Library/HTML/Minimal Javascript Canvas Tutorial
From Athile
< Library
Important: this tutorial assumes you are using JQuery.
Insert the HTML Canvas Element
Below is an example that inserts a canvas element with the id "canvas" (this can be changed to any string name), adds a thin border (to clearly define the bounds of the canvas), and sets to to be 300x300 pixels.
<canvas id="canvas" style="border: 1px solid black" width="300" height="300"></canvas>Get the Javascript Canvas 2d object
Here the JQuery document ready event gets the context object ("ctx"). This object is used for all the drawing operations.
$(document).ready(function () { var canvas = $('#canvas'); var ctx = canvas[0].getContext("2d"); ... })
Draw A Circle
Two steps here:
- The canvas is scaled and transformed to a normalized (-0.5, -0.5) to (0.5, 0.5) space, lower-left to upper-right. The default canvas space will be in pixel space otherwise. Any coordinate space can be used: this tutorial simply is using a Cartesian-based orientation as an example.
- The path, arc, and fill methods draw a circle
ctx.scale(300, -300); ctx.translate(0.5, -0.5); ctx.beginPath(); ctx.arc(0, 0, .5, 0, Math.PI * 2, true); ctx.closePath(); ctx.fill();
The HTML5 Canvas Specification provides reference on additional methods on the context object.