简体   繁体   中英

Drawing rectangle in Canvas

i am able to draw rectangle over video in canvas.But it is hiding behind video but im able to see it through side.Pls suggest what should i do for drawing it over video same as i can draw over image.Code i'm using :

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

Check my jsfiddle at: http://jsfiddle.net/mummydaddy/LjqbuLne/

To see your video under your rectangle, you need to draw your rectangle into all frame refresh like this:

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);

You can see i use ctx and not context var. These two variable have a same node reference, so ...it's not necessary to duplicate that.

You need to do it this way:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM