czwartek, 26 listopada 2015

HTML 5 Canvas

HTML 5 introduced many new shiny features into the web design. One of those features is <canvas> element which is quite self descriptive - a canvas on which content is painted using JavaScript (which uses coordinates for the points). Canvas elements can be static or animated, it is even possible to create games with them.

Here is example: 

  Your browser does not support the HTML5 canvas tag, sorry.

 

How it is done

The graphics are drawn by script on the canvas element which is accessed in typical JavaScript way:
"var candraw1=document.getElementById('canvas1');"
Then the desired shape is drawn on the canvas from one point to the other, like connecting dots and at last filled out and stroked:
var ct1 = document.getElementById('canvas1').getContext('2d');
ct1.fillStyle = "rgba(255, 255, 255, 1)";
ct1.strokeStyle = "blue";
ct1.beginPath();
ct1.moveTo(300, 25);
ct1.lineTo(366, 25);
ct1.lineTo(416, 67);
ct1.lineTo(416, 133);
ct1.lineTo(366, 175);
ct1.lineTo(300, 175);
ct1.lineTo(250, 133);
ct1.lineTo(250, 67);
ct1.closePath();
ct1.lineWidth=10;
ct1.stroke();
ct1.fill();
NOTE: The first value is the X coordinate (horizontal one) and starts at 0 which is the very left of the canvas, the second value is the Y coordinate (vertical one) and also starts at 0 which is the very top of the canvas.

Some shapes such as circle are drawn slightly different:
var dCircle = document.getElementById('canvas1');
var c = document.getElementById("canvas1");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(125,100,75,0,2*Math.PI);
ctx.fillStyle = "rgba(255, 255, 255, 1)";
ctx.fill();
ctx.fillStyle = 'white';
NOTE:The first two values used in the arc() method are X and Y coordinates of the centre of the circle and the third values is the radius of the circle. The other values are starting and ending angles for drawing arcs, they are given in radians. So in the case of our circle, the arc starts at angle 0r and ends at 2r angle which is 360.

Brak komentarzy:

Prześlij komentarz