Let's jump right in by drawing a simple image. In this recipe, we'll learn how to load an image and draw it somewhere on the canvas.
Follow these steps to draw an image in the center of the canvas:
Define the canvas context:
Create an
image
object, set theonload
property to a function that draws the image, and then set the source of the image:var imageObj = new Image(); imageObj.onload = function(){ var destX = canvas.width / 2 - this.width / 2; var destY = canvas.height / 2 - this.height / 2; context.drawImage(this, destX, destY); }; imageObj.src = "jet_300x214.jpg"; };
Embed the canvas tag inside the body of the HTML document:
<canvas id="myCanvas" width="600" height="250" style="border:1px solid black;"> </canvas>