【问题标题】:Drawing rectangle in Canvas在 Canvas 中绘制矩形
【发布时间】:2015-01-11 12:34:24
【问题描述】:
我能够在画布中的视频上绘制矩形。但它隐藏在视频后面,但我能够通过侧面看到它。请建议我应该如何在视频上绘制它,就像我可以在图像上绘制一样。代码 i正在使用:
<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/
【问题讨论】:
标签:
javascript
html
canvas
html5-canvas
【解决方案1】:
你需要这样做:
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);
【讨论】:
-
@125fura - 看看这个Fiddle。我已经改变了矩形的宽度和高度。
【解决方案2】:
要在矩形下查看视频,您需要将矩形绘制到所有帧刷新中,如下所示:
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。这两个变量具有相同的节点引用,所以......没有必要复制它。