Tutorial to crop a part of an html5 video (or image) into a canvas.
Desired result :
Demo : here
Code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>html5 : how to crop a video tag into a canvas tag</title>
<script type="text/javascript">
function onLoadEvent() {
function loop(){
var video = document.getElementById('video');
ctx.drawImage(video, 320, 0, 320, 180, 0, 0, 640, 360);
setTimeout(loop, 1000 / 30);
}
var canvas = document.getElementById('cropCvs');
var ctx = canvas.getContext('2d');
loop();
}
</script>
</head>
<body onload="javascript:onLoadEvent()">
<video
id="video"
height="360"
width="640"
autoplay
controls
src="http://cdn.kaltura.org/apis/html5lib/kplayer-examples/media/bbb_trailer_360p.webm?a"
style="width: 640px; height: 360px; border: 1px solid black;">
</video>
<canvas
id="cropCvs"
height="360"
width="640"
style="width: 320px; height: 180px; border: 1px solid black;">
</canvas>
</body>
</html>
Details:

- context .
drawImage
(image, dx, dy) - context .
drawImage
(image, dx, dy, dw, dh) - context .
drawImage
(image, sx, sy, sw, sh, dx, dy, dw, dh) - details src : http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html
in this example : ctx.drawImage(video, 320, 0, 320, 180, 0, 0, 640, 360);
video : video source tag
320,0 : the shift coords
320,180 : the canvas size
0,0 : no shift in the canvas
640,360 : important ! it’s the native resolution of video source
320,0 : the shift coords
320,180 : the canvas size
0,0 : no shift in the canvas
640,360 : important ! it’s the native resolution of video source
setTimeout(loop, 1000 / 30); // 30 is the fps
important ! the video and canvas width and height properties must be set to the native resolution (for video) and desired resolution (for canvas)
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.