Sunday 27 November 2016

HTML5 : Text and Colour in Canvas

In this post, I will try to explain how to put text to the canvas using HTML, CSS, and JavaScript.


HTML5 has brought some exciting new advantages to the HTML coding world. A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content. Canvas allows you to render graphics powered by Javascript. So throw away that flash code and dive into Canvas.


Fact : HTML5 is a mix of HTML, CSS and JavaScript.

What's the syntax of this topic ?

How is the result of the syntax ?


Explanation :
  1. In the body of HTML, we type <canvas> tag. Canvas have 3 attributes, which is (id, width, height, and style).
  2. ID means what's the name of the canvas.
  3. Width & Height means the size of the canvas .
  4. Style means the style of the frame or border we want to use, referring to CSS. If you want to look more about the style, you can visit this link 
  5. To use JavaScript in HTML, you have to add <script> tag to the HTML so JS will work in your HTML.
  6. In the <script> tag, we add the variable of canvas and ctx.
  7. We will call  the canvas (var canvas), using document.getElementById("myCanvas") based on the variable's ID. 
  8. What's does ctx mean ? Actually, it is a shorthand for the word "context". That's it. Of course, you can use whatever name you like - there is no real naming convention in this instance.
  9. The Canvas.getContext() method returns a drawing context on the canvas, or null if the context identifier is not supported.
  10. Font, Fillsytle, TextAllign, and FillText which used in the syntax, are part of the script so the canvas will have "value". For more, you can visit this link.
  11. ctx.font -> in this part, we put the size of the text and the font we like to use.
  12. ctx.fillstyle -> in this part, we put the color of the text.
  13. ctx.textAllign -> in this part, we put the Alignment position of the text.
  14. ctx.fillText -> in this part, first, we put the text with an apostrophe, second, we write the position of the text. In the syntax above, the position means that the position will be at the center of width size and height size.
  15. For more color, you can visit this link.
Syntax :
<html>
<head>
<title>Text and Color</title>
</head>
<body>

<canvas id="myCanvas" width="300" height="300"style="border:1px solid #FFFF00;">

<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
ctx.font = "30px Comic Sans MS";
ctx.fillStyle = "red";
ctx.textAlign = "center";
ctx.fillText("Text and Color", canvas.width/2, canvas.height/2);

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

That's all I can share thank you ;)

No comments:

Post a Comment