在画布中绘制矩形

时间:2014-11-14 06:56:18

标签: javascript html5 canvas html5-canvas

我能够在画布上绘制矩形而不是视频。但是它隐藏在视频背后但我能够通过侧面看到它。请建议我应该怎样做才能将它绘制在视频上,就像我可以在图像上绘制一样。代码我我正在使用:

   <p>Video to use:</p>
<video id="video1" controls width="270" autoplay>
  <source src="http://www.craftymind.com/factory/html5video/BigBuckBunny_640x360.ogv" type="video/ogg"/> 
</video>

<p>Canvas (the code draws the current frame of the video every 20 millisecond):</p>
<canvas id="myCanvas" width="270" height="135" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

></canvas></div>

检查我的jsfiddle:http://jsfiddle.net/mummydaddy/LjqbuLne/

2 个答案:

答案 0 :(得分:1)

要在矩形下看到您的视频,您需要将矩形绘制为所有帧刷新,如下所示:

v.addEventListener("play", function() {var i = window.setInterval(function() {

  ctx.clearRect ( 0 , 0 , 300 , 300 );    // clear your canvas if you move shapes
  ctx.drawImage(v,5,5,260,125) 
  ctx.beginPath();
  ctx.rect(100, 100, 200, 200);
  ctx.fillStyle = 'yellow';
  ctx.fill();
  ctx.lineWidth = 7;
  ctx.strokeStyle = 'black';
  ctx.stroke();
},20); }, false);

你可以看到我使用ctx而不是context var。这两个变量具有相同的节点引用,因此......没有必要复制它。

答案 1 :(得分:1)

你需要这样做:

Fiddle

var v = document.getElementById("video1");
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var i;

function draw() {
    i = window.setInterval(function draw() {
        ctx.drawImage(v, 5, 5, 260, 125);
        ctx.clearRect(135, 92, 126, 34);
        ctx.beginPath();
        ctx.rect(135, 92, 126, 34);
        ctx.fillStyle = 'yellow';
        ctx.fill();
        ctx.lineWidth = 7;
        ctx.strokeStyle = 'black';
        ctx.stroke();
    }, 20);
}

draw();
v.addEventListener("play", function () {
    draw();
}, false);
v.addEventListener("pause", function () {
    clearInterval(i);
}, false);
v.addEventListener("ended", function () {
    clearInterval(i);
}, false);