【问题标题】:Canvas drawImage not working画布drawImage不工作
【发布时间】:2012-03-22 09:42:21
【问题描述】:

我正在尝试在 HTML 画布上绘制图像:

var mainCanvas = document.getElementById('mainCanvas');
var ctx = mainCanvas.getContext('2d');

我提出一个 ajax 请求,并解析从中获得的 xml 数据(完美运行),然后当我在画布上绘制不同的形状时,它也可以 100% 运行。 以下代码中的图像绘制不起作用:

$(data).find('Object').each(function(){
  type = $(this).attr('type');
  x = $(this).attr('X');
  y = $(this).attr('Y');
  switch(type){
    case '2':
    height = h_panel;
    width = w_panel;
    ctx.fillStyle = sColor;
    ctx.fillRect(x,y,width,height);
    break;
    case '1':
    var powerFactoryImg = new Image();
    powerFactoryImg.onload = function(){
      alert('test');
      ctx.drawImage(powerFactoryImg,x,y,90,80);
    };
    powerFactoryImg.src = 'images/power_factory.png';
    break;

   //Other cases go here - they draw rectangles - all of them work

  }
});

我使用 Chrome 开发者工具检查了图片正在加载;此外,正在调用 .onload 中的警报。该代码在 Chrome 和 FF 中均无效。 这里可能有什么问题?

谢谢

【问题讨论】:

  • 鉴于正在加载图像,问题出在其他地方而不是您提供的代码中,或者您正在画布边界之外绘制图像,因此您看不到它。或者在上面画点什么?
  • 在onload中检查x和y的值:alert('test: ' + x + ', ' + y);

标签: javascript html canvas html5-canvas


【解决方案1】:

该错误可能是由于您的作业中没有var 造成的。在循环中,您不断覆盖typexy 变量。以var 为前缀来解决您的问题。

另请参阅:What is the purpose of the var keyword and when to use it (or omit it)?

$(data).find('Object').each(function(){
  var type = $(this).attr('type');//<-- var
  var x = $(this).attr('X');      //<-- var
  var y = $(this).attr('Y');      //<-- var
  switch(type){
    case '2':
       var height = h_panel;  // <-- var
       var width = w_panel;   // <-- var
       ctx.fillStyle = sColor;
       ctx.fillRect(x,y,width,height);
    break;
    case '1':
       var powerFactoryImg = new Image();
       powerFactoryImg.onload = function(){
           alert('test: ' + [x, y]); //<-- "test" is not very useful. Add [x,y]
           ctx.drawImage(powerFactoryImg,x,y,90,80);
       };
       powerFactoryImg.src = 'images/power_factory.png';
    break;

    //Other cases go here - they draw rectangles - all of them work

   }
});

PS:出于调试目的,我建议使用console.log 而不是alert

【讨论】:

  • 效果很好,非常感谢! X 和 Y 之前是未定义的。但我仍然无法理解覆盖如何导致这种情况。如果 X 和 Y 值是全局的并被多次覆盖,为什么它们无法正确读取并在读取时最终未定义?
  • @doktor .onload 事件监听器被延迟,并在图像加载时执行。在第一个图像加载之前,.each 循环已经完成,导致最近的(全局?)xy 变量等于最新的 xy 属性。所以,只画了一条线。结果,您认为“什么都没有”发生,而实际上,同一条线被多次绘制。本地声明变量解决了这个问题,因为每个onload 处理程序将正确解析xy
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 1970-01-01
  • 2018-09-22
  • 1970-01-01
  • 2016-06-15
相关资源
最近更新 更多