i am trying to load images on a canvas from my local folder, this is my js script:
function loadElement(url) {
return new Promise((resolve) => {
const element = new Image();
element.addEventListener("load", () => {
resolve(element);
});
element.src = url;
});
}
//canvas
const canvas = document.querySelector("canvas");
const context = canvas.getContext("2d");
context.fillRect(0, 0, 50, 50);
loadElement("./tilesheet.png").then((element) =>
context.drawImage(element, 0, 0)
);
and my html script:
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Surface</title>
<link rel="stylesheet" href="css/main.css" />
<script type="module" src="js/main.js"></script>
</head>
<body>
<canvas id="canvas"></canvas>
</body>
</html>
but i get this error: GET http://127.0.0.1:5500/public/tilesheet.png 404 (Not Found) and i dont understand why.
Your code loads fine with a known good image:
function loadElement(url) { return new Promise((resolve) => { const e = new Image(); e.addEventListener("load", () => { resolve(e); }); e.src = url; }); } const canvas = document.querySelector("canvas"); const context = canvas.getContext("2d"); context.fillRect(0, 0, 50, 50); loadElement("http://i.stack.imgur.com/UFBxY.png").then((e) => context.drawImage(e, 0, 0));
<canvas id="canvas"></canvas>
My guess the error is right your image is not there: 404 (Not Found)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.