Categories
HTML JavaScript Web development

HTML Canvas

If you want to start to learn JavaScript you need to know what is the HTML . The HTML <canvas> tag is used draw graphics on the website.

The HTML <canvas> tag is used to draw graphics, on the fly, via JavaScript.

The <canvas> element is only a container for graphics. You must use JavaScript to actually draw the graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.

Canvas Examples:

Example1

A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no content.

Note: Always specify an id attribute (to be referred to in a script), and a width and height attribute to define the size of the canvas.

To add a border, use the style attribute.

Here is an example of a basic, empty canvas:

<!DOCTYPE html>
<html>
<body>

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

</body>
</html>

Output:

Example2 – draw a line:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:2px solid black;"></canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>

</body>
</html>

Output:

Example3 – draw a circle:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"></canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
</script> 

</body>
</html>

Output:

Example4 – draw a text:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="250" height="100" style="border:1px solid #d3d3d3;">
</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hava a good day!",10,50);
</script>

</body>
</html>

Output:

Example5 – draw linear gradient:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3;"></canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"lightblue");
grd.addColorStop(1,"grey");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script>

</body>
</html>

Output:

Example6 – draw an image:

<body>
<p>Image to use:</p>
<img id="dance" src="dance.jpg" alt="Dancer" width="320" height="240">

<p>Canvas to fill:</p>
<canvas id="myCanvas" width="640" height="480"
style="border:1px solid #d3d3d3;"></canvas>

<p><button onclick="myCanvas()">Click here</button></p>

<script>
function myCanvas() {
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var img = document.getElementById("dance");
  ctx.drawImage(img,10,10);
}
</script>
</body>

Output:

Enjoy coding!

Leave a Reply