Desired result: I want that the images (image and image2) should load one-by-one. Following is my code:
'use strict';
window.addEventListener('DOMContentLoaded', () => {
const cvs = document.querySelector('#cvs');
cvs.width = window.innerWidth;
cvs.height = window.innerHeight;
const c = cvs.getContext('2d');
let image = new Image(); // first image
image.src = 'https://images5.alphacoders.com/559/559956.jpg';
let image2 = new Image(); // second image
image2.src = 'https://www.highreshdwallpapers.com/wp-content/uploads/2013/03/Avengers-A.jpg';
let y = 0;
let loader = img => new Promise(resolve => img.onload = resolve(img, 0, y, 100, 60));
let logger = img => new Promise(resolve => img.onload = resolve(img.src + ' loaded!'));
async function loadImages() {
await logger(image).then(console.log); // this works
await logger(image2).then(console.log); // this works
await loader(image).then(c.drawImage);
y += 60;
await loader(image2).then(c.drawImage);
};
loadImages();
});
body {
margin: 0;
}
#cvs {
position: fixed;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="./style.css">
</head>
<body>
<canvas id='cvs'>Canvas not supported</canvas>
<script type="text/javascript" src='./script.js'></script>
</body>
</html>
Here's my concept:
new Promise
which resolves
when the image loads
and then draws it on the canvas context:
let loader = img => new Promise(resolve => img.onload = resolve(img, 0, height, 100, 60));
asynchronous
function that calls the loader
for every image and draws it on canvas:
async function loadImages() {
// ...
await loader(image).then(c.drawImage);
y += 60;
await loader(image2).then(c.drawImage);
};
But, for some reasons, the code isn't working. And, I get the following error: Uncaught (in promise) TypeError: Illegal invocation
.
I've tried replacing c.drawImage
with:
c.drawImage.bind(c)
, as recommended in this post and,
c.drawImage.call
, in this case, I've changed my resolve
as resolve(c, img, 0, height, 100, 60)
But, neither of them worked out!
What I am doing wrong?