Set size of an image in the HTML5 canvas

The canvas size and image size both are different things. The canavs is the DOM element in the HMML5 that allows drawing the 2D shapes and bitmap images. To draw the image on the canvas, it should be cheked that what the dimensions of the loaded image is, and if the original image’s height and width are greater than the canvas’s height and width, the full image will not be show.

Set the canvas dimensions to the dimensions of the Image

function renderImage(src){
	var image = new Image();
	image.onload = function(){
		var canvas = document.getElementById("myCanvas");
		var ctx = canvas.getContext("2d");
		ctx.clearRect(0, 0, canvas.width, canvas.height);
		canvas.width = image.width;
		canvas.height = image.height;
		ctx.drawImage(image, 0, 0, image.width, image.height);
	};
	image.src = src;
	}

The above code does the following:

-Create a JavaScript Image object.
-Attach a handler to the onload event of that Image.
-Clear the canvas element.
-Set the canvas size to the size of the Image, and
-Draw the image to the canvas.