HTML5 Canvas Images
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.
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);
}
}
Now let’s play with dw and dh
img.onload = function () {
context.drawImage(img, 20, 20, 100, 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);
}
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 🙏.