Drawing an image in canvas using in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for drawing an image in canvas using JavaScript −

Example

 Live Demo

<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>
<h1>Drawing an image in canvas</h1>
<img class="flower" width="300" height="300"
   src="https://i.picsum.photos/id/976/300/300.jpg?hmac=Gwae8T0kvhjbWyNIAiYgOckWbK
BHGr2p_6EEE29uDDg" />
<canvas class="canvas1" width="300" height="300" style="border: 1px solid #d3d3d3;">
</canvas><br />
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to draw the image in canvas</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   BtnEle.addEventListener("click", () => {
      var c = document.querySelector(".canvas1");
      var ctx = c.getContext("2d");
      var img = document.querySelector(".flower");
      ctx.drawImage(img, 10, 10);
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −

raja
Published on 22-Jul-2020 07:56:39
Advertisements