HTML5画布 - 如何在画布上绘制图像上的矩形

14

实际上,我可以使用img.onload函数来完成它。这是我从 'HTML5画布-如何在图像背景上绘制线条?'学到的方法。但我需要在不使用imgonload函数的情况下绘制图像,方法如下:

    var imagePaper = new Image();


        imagePaper.onload = function(){


            context.drawImage(imagePaper,100, 20, 500,500);
        };

      imagePaper.src = "images/main_timerand3papers.png";
}

但我希望能够简单地在画布上方附加img src并绘制矩形,就像这样:

<body>  
<img id="scream" src="my.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="500" height="500" >
Your browser does not support the HTML5 canvas tag.</canvas>

但是我无法在canvas上绘制图像之上的线条,无论是图像先绘制还是形状被遮挡。这是我的完整代码:

 <!DOCTYPE html>  
 <head>  
 <title>Playing YouTube video on HTML5 canvas</title>  
 <meta name="viewport" content="user-scalable=no, initial-scale=1.0, maximum-scale=1.0, width=device-width" />  
 <style type="text/css">  
body {
        margin: 0px;
        padding: 0px;
      } 
 </style>  
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

 </head>  
 <body>  
<img id="scream" src="my.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="500" height="500" >
Your browser does not support the HTML5 canvas tag.</canvas>
  <script>  
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10,10);  
var canvas = document.getElementById('myCanvas');
      var context = canvas.getContext('2d');

      context.beginPath();
      context.rect(188, 50, 200, 100);
      context.fillStyle = 'yellow';
      context.fill();
      context.lineWidth = 7;
      context.strokeStyle = 'black';
      context.stroke();
  </script>  
 </body>  
 </html>  

看起来你只需要在画布元素上加一个 position: absolute 样式,这样它就可以直接放在 <img> 上面,而且不需要把图片绘制到画布中 - 也就是只使用组合。 - Alnitak
其实,我只是想进行数学函数操作,所以它不需要。 - Rani dubey
2个回答

28
因为您没有等待图像先加载。在您的script中添加一个window.onload()
<script>
window.onload = function() {
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');
  var img = document.getElementById('scream');

  context.drawImage(img, 10, 10);

  context.beginPath();
  context.rect(188, 50, 200, 100);
  context.fillStyle = 'yellow';
  context.fill();
  context.lineWidth = 7;
  context.strokeStyle = 'black';
  context.stroke();
}
</script>

发生的情况是它试图在图像加载之前绘制它,使用window.onload将在整个文档加载完成后(例如图像)调用代码。否则,它可能不显示图像或将其绘制偏离线条。


3

我尝试使用 window.onload() 来解决问题,它在使用其他浏览器时都能成功,但是当我使用 Microsoft Edge 浏览器时却无法生效。对我来说有效的解决方法是将 onload 处理程序附加到图像上,例如:

image.onload = function ()
{
    context.drawImage(image, 0, 0);
}

然后它完美地运行了。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接