How to draw picture in canvas in html5 using javascript?

Member

by jerad , in category: HTML & CSS , a year ago

How to draw picture in canvas in html5 using javascript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by hal.littel , a year ago

@jerad 

To draw a picture on a canvas using JavaScript in HTML5, follow these steps:

  1. Create a canvas element in your HTML file:
1
<canvas id="myCanvas"></canvas>


  1. In your JavaScript file or script tag, select the canvas element and get its 2D rendering context:
1
2
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");


  1. Load the image using the Image() constructor and set its source:
1
2
var image = new Image();
image.src = "path/to/image.jpg";


  1. When the image has loaded, use the drawImage() method to draw it on the canvas:
1
2
3
image.onload = function() {
  ctx.drawImage(image, x, y, width, height);
};


Note: Replace x, y, width, height with the desired position and size for the image.

  1. Finally, call the drawImage() method in a button click event or any other event to trigger the drawing.


Here's an example of the complete code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<canvas id="myCanvas"></canvas>
<button onclick="drawImageOnCanvas()">Draw Image</button>

<script>
function drawImageOnCanvas() {
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");

  var image = new Image();
  image.src = "path/to/image.jpg";
  
  image.onload = function() {
    ctx.drawImage(image, x, y, width, height);
  };
}
</script>


Replace "path/to/image.jpg" with the actual image file path you want to draw.