简体   繁体   中英

image does not appear on github pages

I wrote a simple HTML file to put an image to a canvas. It runs on localhost but not in github pages.

The image starry-night.jpg is on the same folder.

<!DOCTYPE html>
<meta charset="utf-8">
<body>

<canvas id="vincent"></canvas>

<script>

        var width  = 960;
        var height = 500;
        var canvas = document.getElementById('vincent');
        var ctx = canvas.getContext("2d");
        canvas.width  = width;
        canvas.height = height;

        var image = new Image();
        image.src= "starry-night.jpg";
        ctx.drawImage(image, 0, 0);

        console.log("done");

</script>

</body>

Here is a link to it not working: http://monsieurcactus.github.io/LearnElm/canvas-example.html

Here is a snippet also not working:

  var width = 960; var height = 500; var canvas = document.getElementById('vincent'); var ctx = canvas.getContext("2d"); canvas.width = width; canvas.height = height; var image = new Image(); image.src= "http://monsieurcactus.github.io/LearnElm/starry-night.jpg"; ctx.drawImage(image, 0, 0); console.log("done"); 
 <canvas id="vincent"></canvas> 

Setting the image's source with the src attribute makes the browser to trigger an HTTP request for getting the image , and you need to wait for the image to be loaded before drawing it. Like this:

 <!DOCTYPE html> <meta charset="utf-8"> <body> <canvas id="vincent"></canvas> <script> var width = 960; var height = 500; var canvas = document.getElementById('vincent'); var ctx = canvas.getContext("2d"); canvas.width = width; canvas.height = height; var image = new Image(); image.src= "http://monsieurcactus.github.io/LearnElm/starry-night.jpg"; image.onload = function() { ctx.drawImage(image, 0, 0); console.log("done"); } </script> </body> 

Note: Here we need an absolute url because this example is being served outside of monsieurcactus.github.io/LearnElm/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM