最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - simple HTML5 canvas image not displaying - Stack Overflow

programmeradmin1浏览0评论

I'm new to this - I just can't figure out why this isn't working. When I remove Display:none from HTML, the image works correctly so I know the path to the image is correct. But it's not drawing on the canvas. Thanks for your time.

HTML:

<canvas width="840" height="900" id="Canvas6">
     Your browser does not support this feature.
    </canvas>
<img src="image/logo.png" id="img1" width="825" height="272" style="display:none;">
<script type="text/javascript" src="js/main.js"></script>

Main.JS JAVASCRIPT:

var theCanvas = document.getElementById('Canvas6');

if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {

        //Create a variable to hold our image
        var  srcImg = document.getElementById("img1");

        //Draw an image directly onto the canvas
        ctx.drawImage(srcImg, 0,0);

        //Draw a scaled down image
        //drawImage(srcImg, dx, dy, dw, dh)


    }
}

I'm new to this - I just can't figure out why this isn't working. When I remove Display:none from HTML, the image works correctly so I know the path to the image is correct. But it's not drawing on the canvas. Thanks for your time.

HTML:

<canvas width="840" height="900" id="Canvas6">
     Your browser does not support this feature.
    </canvas>
<img src="image/logo.png" id="img1" width="825" height="272" style="display:none;">
<script type="text/javascript" src="js/main.js"></script>

Main.JS JAVASCRIPT:

var theCanvas = document.getElementById('Canvas6');

if (theCanvas && theCanvas.getContext) {
var ctx = theCanvas.getContext("2d");
if (ctx) {

        //Create a variable to hold our image
        var  srcImg = document.getElementById("img1");

        //Draw an image directly onto the canvas
        ctx.drawImage(srcImg, 0,0);

        //Draw a scaled down image
        //drawImage(srcImg, dx, dy, dw, dh)


    }
}
Share Improve this question asked Apr 6, 2014 at 3:25 SteveSteve 1212 silver badges4 bronze badges 3
  • Seems to work fine... jsfiddle/YHER3 – loxxy Commented Apr 6, 2014 at 3:46
  • Hmm, thanks for taking a look. Must be a conflict with my other JS code then. – Steve Commented Apr 6, 2014 at 3:58
  • @loxxy try it with onDomready instead of onload jsfiddle/YHER3/1 – Musa Commented Apr 6, 2014 at 3:59
Add a ment  | 

3 Answers 3

Reset to default 5

In html file, the first best thing you have done is used the 'script' tag right at the end of the html file. This ensures that the "Critical Render Time" is minimized, and the display items in HTML are shown first. (Not a huge impact on this case, because here you are using the JS to draw/display, but this approach is really good when you use your js for other purposes like calculations etc., and you don't want to stop the other HTML items from displaying because of an ongoing calculation.)

Now that the canvas is ready, its time to throw the image on the canvas.

Try using the border property (style="border: 2px dotted black") to see the container area of the canvas.

Hmmm !! But the image doesn't show in canvas. WHY ??

Images(or any other files) take atleast some time to get processed. By the time they are getting processed to be loaded on the screen, your canvas is already getting displayed. Hence you see an empty canvas.

So, the solution is to make everything else wait, till the time image gets loaded.

How do we do that ? Just use the "Event Listener".

EventListener is the property of Window object. (window.addEventListener("load", some_func_to_run , false);). We generally use this, when we want our window/page/browser to wait for something, but hey , we can use it for our images as well.

var cvs = document.getElementById("canvas"); // Getting the control of the canvas
var ctx = cvs.getContext("2d"); //Getting the control of the useful HTML object getContext . This object brings in a lot of useful methods like drawImage, fillRect etc. 


//create images

var bg = new Image(); // Creating image objects
bg.src = "images/bg.png"; //Setting the source file

//create images ends


//load images first
bg.addEventListener("load" , draw , false); //**IMPORTANT : Just remove this line and you will start facing this problem of empty canvas again 

//loading images ends

function draw() {
    ctx.drawImage(bg,0,0);   // Putting the image and its coordinates on the canvas  
}

draw();  // Calling the draw function to put the image on canvas
<html>
   <body>
           <canvas id="canvas" width="288" height="512" style="border: 2px dotted black">            </canvas>
           <script src="flappyBird.js"></script>
   </body>
</html>

So, it all about using Event Listener and asking everything to wait till the image gets loaded.

Hope this help. :)

If you try to place an image on a Canvas before it has loaded, it will not show. It is not like the img tag that will show the image whenever it loads. I surrounded your JS with an onload and it worked for me.

document.getElementById("img1").onload = function() { /* Your JS */ };

You have to wait for the image to load before you can draw it on the canvas, so set your drawing code to run on the window load event (by which time all images are loaded). Also, you don't need to include the markup for the image on the page, where you have to then prevent it from displaying with CSS. You can just create the image object and set the source attribute in the javascript. For example:

var img = document.createElement('img');
img.src = 'image/logo.png';
window.addEventListener('load', function(){ 
    var theCanvas = document.getElementById('Canvas6');
    if (theCanvas && theCanvas.getContext) {
        var ctx = theCanvas.getContext("2d");
        if (ctx) {
                ctx.drawImage(img, 0,0);
        }
    }
});
发布评论

评论列表(0)

  1. 暂无评论