0

basically, whenever I'm trying to use drawImage(), it won't display the image on the screen. I've tried looking around for some solutions but nothing is working for me.

things i've tried

function createStar(){
    let drawstarImage = ()=> {
        ctx.drawImage(starImage, 0, 0)
    }
    starImage.onload = drawstarImage;
starImage.onload = ctx.drawImage(starImage, 0, 0)

Here's the code I have now

js:

/** @type {HTMLCanvasElement} */
const canvas = document.getElementById("canvas1");
const ctx = canvas.getContext("2d");

const starImage = new Image();
starImage.src = '../Assets Folder/starImage.png';

ctx.drawImage(starImage, 0, 0);

css:

body {
    width: 100%;
    height: 100%;
    user-select: none;
}

canvas {
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    width: 100%;
    height: 100%;
    background-color:rgb(33, 96, 33);
}

html:

<canvas id="canvas1"></canvas>

If possible can you explain why it's happening because I'm new to web development. Also thank you for helping.

  • 1
    `starImage.onload = ctx.drawImage(starImage, 0, 0)` will set the return value of that call as `onload` handler. `starImage.onload = drawstarImage;` should work, if `starImage` is correctly defined. You may also want to add an `onerror = () => console.log("failed to load");` handler in case your URL is invalid. – Kaiido Nov 22 '22 at 05:03
  • @Kaiido So I tried doing the starImage.onload = drawstarImage; and also adding the onerror message. The onerror message went off so how do I fix the url. – FlowingSouth Nov 22 '22 at 05:16
  • I don't know. You can check what full path `new URL("../Assets Folder/starImage.png", location.href).toString()` produces and change your relative URL accordingly so that it points correctly to your resource. But without knowing your folder structure we can't help you much more than that. – Kaiido Nov 22 '22 at 05:20
  • I think the url is correct though because when i make an image in the html it works. – FlowingSouth Nov 22 '22 at 05:23

0 Answers0