draw image on canvas

拥有回忆 提交于 2020-02-08 06:42:31

问题


I am trying to put an image on a canvas. I read the following tutorial https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Canvas_tutorial/Using_images and tried to do something similar to it my canvas is <canvas id="canvas" width="400" height="400"></canvas> and I have created the function

  function putImage(){
         var img = new Image();
         img.src = "./path.png"; 
         var ctx = document.getElementById('canvas').getContext('2d');
         ctx.drawImage(img,8,8);            
  }

but the image is not appearing on the canvas. I have printed the image path and it is correct, so I was able to eliminate this issue. any suggestions?

thanks


回答1:


According to the tutorial, you're supposed to wrap your ctx.drawImage() inside img.load like so

function draw() {
  var ctx = document.getElementById('canvas').getContext('2d');
  var img = new Image();
  img.onload = function(){
    ctx.drawImage(img,0,0);
    ctx.beginPath();
    ctx.moveTo(30,96);
    ctx.lineTo(70,66);
    ctx.lineTo(103,76);
    ctx.lineTo(170,15);
    ctx.stroke();
  };
  img.src = '/files/4531/backdrop.png';
}

I hope this helps.



来源:https://stackoverflow.com/questions/15333256/draw-image-on-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!