HTML5 Canvas - 如何在画布上绘制矩形

时间:2014-11-13 05:39:44

标签: javascript jquery html html5 canvas

实际上,我可以使用img.onload函数来完成它。我从“HTML5 Canvas - How to Draw a line over an image background?”得到的东西。但我需要在不使用img函数onload的情况下绘制图像,如下所示:

    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>

但我无法在画布上绘制img线条,无论是img是绘图还是形状都隐藏在后面。这是我的完整代码:

 <!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>  

2 个答案:

答案 0 :(得分:14)

因为您没有等待首先加载图像。在script添加window.onload()

<script>
window.onload = function() {
  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>

正在发生的是它正在尝试在加载之前绘制图像,window.onload会在加载整个文档后调用代码(例如图像)。否则它可能不会显示任何图像或将其绘制出来。

答案 1 :(得分:0)

我尝试了使用 window.onload() 的相同方法,直到我使用 Microsoft Edge 浏览器尝试了此方法。一种对我有用的解决方案是在图像上附加 onload 处理程序,例如:

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

然后完美运行。