user3673449 user3673449 - 5 months ago 28
Javascript Question

Draw video on canvas HTML5

I'm trying to draw a video on a canvas. To achieve this I capture the onMouseDown and onMouseUp events in Javascript to get the x and y coordinates of each event (that I need to set the position, width and height of the video inside the canvas).

Therefore, every time I draw a video on the canvas, the previous I create should be stopped and the new one has to be played.
Two problems:

1) the video doesn't play (the function only draws the first frame), but his audio does

2) how can I get previously drawn videos to stop?

Demo: http://jsfiddle.net/e3c3kore/

<body>
<canvas id="canvas" width="800" height="600"></canvas>
</body>



var canvas, context, xStart, yStart, xEnd, yEnd;

canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.addEventListener("mousedown", mouseDown);
canvas.addEventListener("mouseup", mouseUp);

function mouseDown(e) {
xStart = e.offsetX;
yStart = e.offsetY;
}

function mouseUp(e) {
xEnd = e.offsetX;
yEnd = e.offsetY;
if (xStart != xEnd && yStart != yEnd) {
var video = document.createElement("video");
video.src = "http://techslides.com/demos/sample-videos/small.mp4";
video.addEventListener('loadeddata', function() {
video.play();
context.drawImage(video, xStart, yStart, xEnd-xStart, yEnd-yStart);
});
}
}


Demo: http://jsfiddle.net/e3c3kore/

Answer

1) The drawImage() method was only be called once. It needs to be called once per frame.

2) Call pause() method to stop video.

For example, the follow code starts a timer loop (for drawing the frames) on mouse up and stops any previous video on mouse down.

var canvas, context, video, xStart, yStart, xEnd, yEnd;

canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
canvas.addEventListener("mousedown", mouseDown);
canvas.addEventListener("mouseup", mouseUp);

function mouseDown(e) {
    if (video) {
        video.pause();
        video = null;
        context.clearRect(0, 0, canvas.width, canvas.height);
    }
    xStart = e.offsetX;
    yStart = e.offsetY;
}

function mouseUp(e) {
    xEnd = e.offsetX;
    yEnd = e.offsetY;
    if (xStart != xEnd && yStart != yEnd) {
        video = document.createElement("video");
        video.src = "http://techslides.com/demos/sample-videos/small.mp4";
        video.addEventListener('loadeddata', function() {
            console.log("loadeddata");
            video.play();
            setTimeout(videoLoop, 1000 / 30);
        });
    }
}

function videoLoop() {
    if (video && !video.paused && !video.ended) {
        context.drawImage(video, xStart, yStart, xEnd - xStart, yEnd - yStart);
        setTimeout(videoLoop, 1000 / 30);
    }
}
Comments