Getting Started with a canvas in HTML5

Smart Mobile Studio (SMS) makes it easy to draw and write in an HTML5 canvas, but you can experiment with the routines with a very simple page. You can compare the Pascal version (SMS) of the code to draw a green triangle with black edges with the HTML5/JavaScript below:

<!DOCTYPE html> <html> <body> <canvas id="canv" width="200" height="200"></canvas> <script> var c=document.getElementById("canv"); var context=c.getContext("2d"); context.fillStyle='green'; context.strokeStyle='black'; context.beginPath(); context.moveTo(50, 50); context.lineTo(50, 100); context.lineTo(100, 50); context.lineTo(50, 50); context.closePath(); context.fill(); context.stroke(); </script> </body> </html>

 

Notepad++ syntax highlights the code and the menu item Run > Launch in Chrome (with a key combination shortcut such as Ctrl+Alt+Shift+R makes it convenient for testing.

If you are coming to JavaScript from SMS you must note that:

If you want to put the JavaScript in an external file, copy the lines between the script tags to a new file and save it as triangle.js. Make sure that it ends with a new line. You can then call it as follows:

<!DOCTYPE html> <html> <body> <canvas id="canv" width="200" height="200"></canvas> <script type="text/javascript" src="triangle.js"></script> </body> </html>

This handy HTML5 Canvas Cheat Sheet shows that the JavaScript Methods take float (real) numbers as parameters. Here are some methods with which to experiment (as we have done below):

 

<!DOCTYPE html> <html> <body> <canvas id="canv" width="480" height="400"></canvas> <script> var c=document.getElementById("canv"); var context = c.getContext("2d"); context.fillStyle = 'green'; context.strokeStyle = 'blue'; context.font = '14pt verdana'; context.fillText('Playing with graphics', 120, 20); context.fillRect(0, 0, 10.5, 20.3); context.strokeRect(15.3, 30.1, 25.5, 40.6); context.beginPath(); context.moveTo(50, 49.6); context.lineTo(150, 78.3); context.arc(200, 300, 100, 0, 90, true); context.moveTo(250, 49.6); context.quadraticCurveTo(200, 500, 350, 80.7); context.stroke(); </script> </body> </html>