Simple way to add Image to Canvas using Javascript

Umesh Thapa
1 min readApr 4, 2022

--

Someone is experimenting a bit with the new canvas element in HTML.

And simply want to add an image to the canvas but it doesn’t work for some reason.

Following code:

HTML

<canvas id="viewport"></canvas>

CSS

canvas#viewport { border: 1px solid white; width: 900px; }

JS

var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
context.drawImage(base_image, 100, 100);
}

The image exists and I get no JavaScript errors. The image just doesn’t display.

It must be something really simple I’ve missed…

Answer to Solve these issue

You need to wait until the image is loaded before you draw it. Try this instead:

var canvas = document.getElementById('viewport'),
context = canvas.getContext('2d');

make_base();

function make_base()
{
base_image = new Image();
base_image.src = 'img/base.png';
base_image.onload = function(){
context.drawImage(base_image, 0, 0);
}
}

i.e. draw the image in the onload callback of the image.

--

--

Umesh Thapa
Umesh Thapa

Written by Umesh Thapa

Web Design || Development || Content Creator || Editor || Writer || Ewumesh || Nepal || Australia || USA #ewumesh https://ewumesh.com/

Responses (1)