crus4

crus4

HTML Canvas Images


HI guys, in this post we are going to draw an image on Canvas.

To draw an image on canvas we are going to use drawImage(image, x,y) method. Here we need an image’s destination point and an image object.

Here x,y are the coordinates of canvas.

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name=" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <img src = "your_img_url" width ="200" height="237" id = "cup " alt=" coffee cup ">
    <canvas id="myCanvas" width="240" height="297" style="border:1px solid #d3d3d3;"> </canvas>
    <script>
      window.onload = function() {
        var canvas=document.getElementById("myCanvas");
        var ctx=canvas.getContext("2d");
        var img = document.getElementById("cup");
        ctx.drawImage(img, 10, 10);

      }
    </script>

</body>
</html>

Output

How to Embed Multiple Images in Canvas

With the help of JavaScript you can embed multiple images in canvas.

Below is a code to embed multiple images using JavaScript:

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
</style>
</head>
<body>
<h3>Combining multiple images into a single one</h3>
<img class="image" src="url_ist"/>
<img class="image" src="url_2nd" />
<canvas class="result"></canvas>
<br />
<button class="Btn">CLICK HERE</button>
<h4>Click on the above button to combine the two images above together</h4>
<script>
   let imgEle1 = document.querySelectorAll(".image")[0];
   let imgEle2 = document.querySelectorAll(".image")[1];
   let resEle = document.querySelector(".result");
   var context = resEle.getContext("2d");
   let BtnEle = document.querySelector(".Btn");
   BtnEle.addEventListener("click", () => {
   resEle.width = imgEle1.width;
      resEle.height = imgEle1.height;
      context.globalAlpha = 1.0;
      context.drawImage(imgEle1, 0, 0);
      context.globalAlpha = 0.5;
      context.drawImage(imgEle2, 0, 0);
   });
</script>
</body>
</html>

Output

Once you click on the CLICK HERE button, these two images will be embedded:

So, this is how you can combine two images in canvas using JavaScript.


Related Posts

HTML Canvas

Other HTML Canvas Graphics

HTML id Attribute

HTML Canvas Images – crus4

3 thoughts on “HTML Canvas Images – crus4

Leave a Reply

Your email address will not be published.