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

javascript - Canvas Image not rendering in Chrome (works in FF4 & IE9) - Stack Overflow

programmeradmin1浏览0评论

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:

/

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.

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/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.

Share Improve this question asked Apr 27, 2011 at 16:03 CoryDorningCoryDorning 1,9144 gold badges25 silver badges38 bronze badges 2
  • it seems to be working in chrome fore me? am i supposed be seeing the google logo? – Naftali Commented Apr 27, 2011 at 16:33
  • it works intermittently b/c of the image loading. you were lucky. :) – CoryDorning Commented Apr 27, 2011 at 16:49
Add a ment  | 

2 Answers 2

Reset to default 4

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)

发布评论

评论列表(0)

  1. 暂无评论