Monday, December 1, 2014

Lesson 8: HTML5 canvas

HTML is originally intended for simple text, and drawing, audio and video was originally achieved by browser plugins such as Flash and Java Applets.. until HTML5 (about 2008). Super duper slide show here: http://slides.html5rocks.com/#landing-slide. I actually only used just some of its features. Note: not all browsers support all features.

This is a great link for experimenting with it: http://www.w3schools.com/html/html5_canvas.asp.

First, define a canvas, with an apology note for old browsers.

<canvas id="myCanvas1" width="200" height="200" style="border:1px solid blue;">
Sorry, your browser does not support canvas
</canvas>

Then we need javascript to draw. You will need to get the "context". Then call the methods within the context to draw lines, text, images. This tells you all the things you can do with it: http://www.w3schools.com/tags/ref_canvas.asp

This is an example to draw line.

var c = document.getElementById("myCanvas1");
var ctx = c.getContext("2d");
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.closePath();
ctx.stroke();
from (0,0) - (200,100)

With specific width and color

var c = document.getElementById("myCanvas1");
var ctx = c.getContext("2d");

ctx.beginPath();
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.lineWidth = 10;
ctx.strokeStyle = '#ff0000';
ctx.closePath();

ctx.stroke();

with specific width and style (color)

Sorry, your browser does not support canvas

Draw a filled rectangle

var c = document.getElementById("myCanvas1");
var ctx = c.getContext("2d");

ctx.fillStyle = 'green';
ctx.fillRect(30,30,100,100);

Draw Arc (Cricle). x, y, radius, start angle, end angle (in radians). (Radian is an alternative to degree measure. There are 2π radian in 360°)

var c=document.getElementById("myCanvas1");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(100,75,50,0,2*Math.PI);
ctx.stroke();

var c=document.getElementById("myCanvas1");
var ctx=c.getContext("2d");

ctx.font="20px Georgia";
ctx.rotate(20*Math.PI/180)
ctx.fillText("Hello World!",10,50);

Now I showed you almost everything you need to do the function plotter.

No comments:

Post a Comment