HI WELCOME TO KANSIRIS

Drawing with Canvas Element

HTML5 Canvas Element allows you to draw graphics, images or text. In order to make this canvas element works, we will use javascript to draw the graphics.
Before we started, see the basic syntax elements and what attributes are required for canvas element.
//sample of canvas element
<canvas id="mycanvas" width="250" height="250">
 
</canvas>
Canvas element required start and end canvas tag. The attributes for width and height are required as well. Although ID is not required but it is needed by the javascript to get the canvas object.

Example of Drawing Rectangles in HTML5

Below are the available function to draw rectangles and we include some demos for you to have a look as well.
/* canvas html5 syntax */
<canvas width="600" height="400" id="canvasdemo" class="canvasdemo" >

</canvas>

/* we include a css style to draw a black line of the canvas so we know their dimension as by default the canvas background color is transparent. */
<style type="text/css">
 .canvasdemo{border:solid 1px black;}
</style>

/* We include this javascript to draw the rectangles. */
<script type="text/javascript">
 $(function () {
  //we getting the canvas object and set as 2d context
  var canvasdemo = document.getElementById("canvasdemo");
  var cCanvasdemo = canvasdemo.getContext("2d");

  // we drawing two rectangles yellow and blue to be stacked together.
  cCanvasdemo.fillStyle = "yellow";
  cCanvasdemo.fillRect(50, 50, 100, 100);

  cCanvasdemo.fillStyle = "blue";
  cCanvasdemo.fillRect(70, 70, 100, 100);

  //we use the strokeRect function to draw stroke rectangular
  cCanvasdemo.strokeRect(370, 50, 100, 100);

  //we use clearRect function to clear/empty rectangular, you will see the yellow rectangular has been cut off/cleared by the clearRect object
  cCanvasdemo.fillStyle = "yellow";
  cCanvasdemo.fillRect(50, 250, 100, 100);
  cCanvasdemo.clearRect(70, 270, 100, 100);
 });
</script>

Quick Demo - See how easy to draw rectangles using HTML5 Canvas Element


You can as well drawing text inside the canvas. See another example below:
/* Canvas syntax */
<canvas width="600" height="120" id="canvasdemo2" class="canvasdemo">

</canvas>

/* Include a javascript to trigger the drawing */
<script type="text/javascript">
 $(function () {
  var canvasdemo2 = document.getElementById("canvasdemo2");
  var cCanvasdemo2 = canvasdemo2.getContext("2d");

  // We set the text properties. In order for the text to work properly, you have to follow this style format [Font Style] [Font Size] [Font Name], (position left), (position top).
  cCanvasdemo2.font = "italic 20px Arial";
  cCanvasdemo2.strokeText("Learn HTML 5 with bytutorial.com", 10, 50);
 });
</script>

Demo of Drawing Text in HTML5