Wednesday, January 6, 2016

HTML5 - Drawing 2D on Canvas

Rectangle
fillRect(x coordinate, y coordinate, width, height)

Round
arc(x coordinate, y coordinate, start angle, end angle, clockwise-or-counter-clockwise)

Linear Gradient
createLinearGradient(Start point - x coordinate, Start point - y coordinate, End point - x coordinate, End point - y coordinate)

Draw Text
fillText("The actualk text goes here", Start point - x coordinate, Start point - y coordinate)

Quadratic Bézier Curve
moveTo(Start point - x coordinate, Start point - y coordinate); //specify the start point
ctx.quadraticCurveTo(Bézier control point - x coordinate, Bézier control point - y coordinate,  End point - x coordinate, End point - y coordinate);

Example

<html>
<body>

<canvas id="myCanvas" width="400" height="500" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
//1 Capture the canvas
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

//2 Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"blue");
grd.addColorStop(1,"black");

//3 Fill gradient
ctx.fillStyle = grd;
ctx.fillRect(10,200,150,80);


//4 Draw text inside the callout
var ctx = c.getContext("2d");
ctx.font = "17px Arial";
ctx.fillText("Hello World",32,70);

//5 Arc
ctx.arc(200, 400, 50, 0, 2 * Math.PI, false);
ctx.fillStyle = '#00994c';
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = '#003300';
ctx.stroke();

//6 Quadratic Bézier Curve
ctx.moveTo(75,25);
ctx.quadraticCurveTo(25,25,25,62.5);
ctx.quadraticCurveTo(25,100,50,100);
ctx.quadraticCurveTo(50,120,30,125);
ctx.quadraticCurveTo(60,120,65,100);
ctx.quadraticCurveTo(125,100,125,62.5);
ctx.quadraticCurveTo(125,25,75,25);
ctx.stroke();

</script>
</body>
</html>

Result


No comments:

Post a Comment