HTML Graphics

HTML graphics are added to make the webpage more interactive and attractive. Typically, HTML5 Canvas and Scalable Vector Graphics (SVG) techniques add high-quality graphics within a browser. 

Scalable Vector Graphics (SVG) 

This type of graphic technique is used in XML. It indicates vector-based graphics within XML. It defines the dimensions and all aspects of an image or a web application.

<body>

  <!-- Basic SVG Circle -->
  <svg width="100" height="100">
    
    <circle cx="50" cy="50" r="40" 
    stroke="black" stroke-width="3" 
    fill="red" />
    
  </svg>
  
</body>

Characteristics

  • Determine image dimensions: SVG is a markup language that describes the shape of the image and its text style. 
  • Quality remains the same: The best part of this is that zooming and resizing do not affect the image’s quality. 
  • Generate with Javascript: You can use Javascript to generate SVG.
  • Highly interactive: It maintains interactivity on the webpage.

HTML Canvas Graphics

The HTML <canvas> element creates graphics and images on a web page via JavaScript. Canvas is pixel-based, renders graphics at a fixed resolution, and doesn’t scale well without quality loss when resized.

<body>
  <!-- Canvas Element -->
  <canvas id="myCanvas" width="200" height="100" 
  style="border:1px solid #000000;"></canvas>

  <script>
    // Get the canvas element and its context
    var canvas = document.getElementById("myCanvas");
    var ctx = canvas.getContext("2d");

    // Draw a blue rectangle
    ctx.fillStyle = "blue";
    ctx.fillRect(20, 20, 150, 75);
  </script>
</body>

The HTML canvas graphics are a gateway to the Javascript API, so you can access all the graphic elements and perform various operations. Using HTML canvas, you can draw images, boxes, circles, and text.

The following are examples of SVG and HTML Canvas.

<html>
<head>
  <style>
    canvas, svg {
      border: 1px solid black;
      margin: 20px;
    }
  </style>
</head>
<body>

  <!-- SVG for drawing the box -->
  <svg width="200" height="200">
    <rect x="50" y="50" width="100" height="100" 
    fill="blue" stroke="black" stroke-width="2" />
  </svg>
  
  <!-- Canvas for drawing the box -->
  <canvas id="canvasBox" width="200" height="200"></canvas>

  <script>
    // Get the canvas and context
    var canvas = document.getElementById('canvasBox');
    var ctx = canvas.getContext('2d');

    // Draw a box in the canvas
    ctx.fillStyle = 'blue';
    ctx.fillRect(50, 50, 100, 100);  // x, y, width, height
    ctx.strokeStyle = 'black';
    ctx.lineWidth = 2;
    ctx.strokeRect(50, 50, 100, 100);  // Draws border around box
  </script>

</body>
</html>

Always add an id, height, and width attribute in JavaScript to make a canvas of specific measurements. Use the style attribute to add a border to your canvas.

Scroll to Top