Canvas JavaScript

Draw a File Image

This JavaScript program demonstrates how to draw an image from a file onto a canvas element.

DisplayFileImage.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="DisplayFileImage.js"></script>
  </head>
  <body onload="Initialize()">
    <canvas id="idCanvas" width="640" height ="640" style="background-color: #F0F0F0;"></canvas>
  </body>
</html>

DisplayFileImage.js

function Initialize() {
	const qCanvas = document.getElementById("idCanvas");
	const qContext2D = qCanvas.getContext("2d");
	const qImageElement = new Image();

	// Set the event listener to display the image when it is loaded
	qImageElement.addEventListener("load", () => {
		qContext2D.drawImage(qImageElement, 0, 0);
	});
	
	// Load the image into the element
	qImageElement.src = "TheValeOfTears_GustaveDore.png";
}
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.