简体   繁体   中英

Canvas Image not rendering in Chrome (works in FF4 & IE9)

I'm stumped. For the life of me, i have no idea why this is not working in Chrome. You can see the code here:

http://jsfiddle.net/corydorning/NgXSH/

When i pull this code up in FF or IE9 it works great. You'll notice that the fiddle WILL work in Chrome with the rendered element, but it DOES NOT work outside of fiddle.

Any help is greatly appreciated. This is my first attempt with canvas.

The problem appears to be that you're not waiting for the original image element to get loaded. If you change it around a little, it works fine:

  $(function() {
    var canvas = document.createElement('canvas'),
    canvasExists = !!(canvas.getContext && canvas.getContext('2d')),
    oImage = $('img')[0];

    if (canvasExists) {
      var context = canvas.getContext('2d'), img = new Image();

      img.onload = function() {
        canvas.height = img.height;
        canvas.width = img.width;

        $(oImage).replaceWith(canvas);

        context.drawImage(oImage, 0, 0);
      }

      img.src = oImage.src; 
    } else {
      // apply MS filters
    }

It could be hard to use img.onload if you have plenty of them. An easy way in chrome to wait for image loading is to use:

$(window).load(function () {

instead of

$(document).ready(function () { 

as $(window).load is actually waiting for all image to be loaded.

It's work perfecly for using the image in the canvas. (work also in firefow and IE)

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