Canvas JavaScript

Draw an Image

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

DrawAnImage.html

<!DOCTYPE html>
<html>
  <head>
    <title>XoaX.net's Javascript</title>
    <script type="text/javascript" src="DrawAnImage.js"></script>
  </head>
  <body onload="Initialize()">
  	<img style="display: none;" id="idAscension" src="Benvenuto_Tisi_da_Garofalo_Ascension_of_Christ_Between1510and1520.jpg">
    <canvas id="idCanvas" width="640" height ="480" style="background-color: #F0F0F0;"></canvas>
    <div style="width:640px;">
    	<h1 style="width:fit-content;margin-left:auto;margin-right:auto;">The Ascension of Christ</h1>
    	<h3 style="width:fit-content;margin-left:auto;margin-right:auto;">Completed between AD 1510 and AD 1520</h3>
    	<h2 style="width:fit-content;margin-left:auto;margin-right:auto;">by Benvenuto Tisi da Garofalo</h2>
    </div>
  </body>
</html>

DrawAnImage.js

function Initialize() {
	var qCanvas = document.getElementById("idCanvas");
	var qContext = qCanvas.getContext("2d");
	const kqImage = document.getElementById("idAscension");
	// Draw at pixel 169 to center the image.
	// The image is 1/3 the original size
	qContext.drawImage(kqImage, 198, 57, 244, 366);
}
 

Output

 
 

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