HTML5 Canvas Images

Anton Lytvynov
2 min readApr 23, 2021

How to add an image to your canvas?

Prepare our HTML

<html lang="en">
<head>
<title>Canvas Image</title>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet">
</head>

<body>
<canvas id="c" width="800" height="600">
This is a message for old browsers
</canvas>

<script src="script.js"></script>
</body>
</html>

Style.css

#c {
border: 1px solid;
display: block;
width: 800px;
height: 600px;
margin: 0 auto;
}

Script.js

Possible variants of image drawing

drawImage(img, dx, dy);
drawImage(img, dx, dy, dw, dh);
drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh);

You can see the explanation of sx, sy, sw, sh on the image bellow.

Additional parameters for draw image function

Let’s add our image to the canvas

window.onload = function () {
let canvas = document.getElementById('c');
let context = canvas.getContext("2d");

let img = new Image();
img.src = 'avatar.png';

img.onload = function () {
context.drawImage(img, 100, 100);
}
}
Canvas & Image

Now let’s play with dw and dh

img.onload = function () {
context.drawImage(img, 20, 20, 100, 100);
}
dw = 100, dh = 100

Now let’s try to get just a part of the image

img.onload = function () {
context.drawImage(img, 20, 20, 200, 200, 40, 40, 300, 300);
}
Used all the parameters of the drawImage

Result

You can check the code for this part here.

Thank you for your attention.

Thank you for your attention.

Do you need help with web or mobile development? Feel free to contact me here.

P.S. I really appreciate your like or share 🙏.

--

--

Anton Lytvynov
Anton Lytvynov

Written by Anton Lytvynov

CEO & Founder of Lytvynov Production, Senior web developer, architect, cryptocurrencies trader, https://lytvynov-production.com

No responses yet