Richland College Multimedia Learning Center

JavaScript, jQuery, and React
Home e-Handouts and Assignments Syllabus Resources Student Sites Other Classes RLC Multimedia
Updated 6/19/2020 at 1:55pm

HTML5 Canvas


References


Introduction

One of the handiest HTML tags which was introduced in HTML5 is the <canvas> tag.

Please NOTE that the <canvas> tag is an HTML tag.

But the magic that happens in the <canvas> tag is done with JavaScript code.


Sample Code

Before you can use the JavaScript Canvas Object methods and properties, you need to add an HTML <canvas> tag to your page.

Following is a sample page with several <canvas> tags in it. This is page canvasSample2.html. Please note that there are three <canvas> tags in this page:

You can see the sample page running in a browser here.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Canvas Sample</title>
  <meta charset="UTF-8">
  <link rel="stylesheet" type="text/css" href="canvasStyles.css" media="screen">
</head>

<body>
  <div id="mainDiv">
    <header>
      <h3>A Sample Canvas</h3>
    </header>
    
    <section>
      <h4>Here is the first canvas tag:</h4>
      <canvas id='theCanvas'></canvas>
      
      <h4>Here is the second canvas tag:</h4>
      <!--<h5>(This is a fake power meter at 75%)</h5>-->
      <canvas id='theCanvas2'></canvas>
      
      <h4>Here is the third canvas tag:</h4>
      <canvas id='theCanvas3'></canvas>
    </section>
    
    <br><br>
    <footer>
      © 2019
    </footer>
  </div>
  
  <script>
    var c = document.getElementById('theCanvas');
    var ctx1 = c.getContext("2d");
    ctx1.fillStyle = "#FF0000";
    ctx1.fillRect(20, 20, 150, 100);
    ctx1.rect(40, 40, 150, 100);
    ctx1.lineWidth = 10;
    ctx1.strokeStyle = "#0000FF";
    ctx1.stroke();  
    
    var c2 = document.getElementById('theCanvas2');
    var canvasRatio = c2.height / c2.width;
    console.log("canvasRatio is " + canvasRatio);
    var cwidth = 600;
    var cheight = cwidth * canvasRatio;
    c2.width = cwidth;
    c2.height = cheight;
    var ctx2 = c2.getContext("2d");
    ctx2.beginPath();
    ctx2.moveTo(20,20);
    ctx2.lineTo(580, 280);
    ctx2.stroke();
    
    ctx2.beginPath();
    ctx2.moveTo(20, 280);
    ctx2.lineTo(580, 20);
    ctx2.lineWidth = 10;
    ctx2.strokeStyle = "#0000FF";
    ctx2.stroke();  
    
    var c3 = document.getElementById('theCanvas3');
    var ctx3 = c3.getContext("2d");
    ctx3.font = "30px Arial";
    ctx3.fillText("Hello World", 10, 50);    
    ctx3.strokeText("Big smile!", 10, 100);
  </script>

</body>
</html>

And here is the stylesheet. This is file canvasStyles.css:

body 
{
  font-family: Arial, sans-serif;
}

canvas
{
  border: 1px solid black;
}

#mainDiv
{
  width: 50%;
  margin: 0 auto;
  border: 1px solid gray;
  border-radius: 2em;
  padding: 2em;
}

Please note these points about the above page's JavaScript code: