javascript - Crop video on canvas -


i getting video user's camera, , displaying on 1:1 square. have button takes picture , draws 1:1 canvas, issue isn't drawn in same location on canvas. how can achieve this?

here running example:

https://jsfiddle.net/90d3ar1m/

here html:

<!doctype html> <html>  <head>     <title>camera</title>     <meta http-equiv="content-security-policy" content="default-src * data: gap: https://ssl.gstatic.com 'unsafe-inline'; style-src * 'unsafe-eval'; media-src 'self' blob:">     <meta name="viewport" content="width=device-width, initial-scale=1">     <link rel="stylesheet" href="css/camera.css"> </head>  <body>     <div class="container">         <div class="camera">             <video id="monitor" autoplay></video>         </div>         <canvas id="photo"></canvas>         <input type=button value="&#x1f4f7;" onclick="snapshot()">     </div>     <script type="text/javascript" src="js/plugins/jquery.min.js"></script>     <script type="text/javascript" src="js/dist/pages/camera.js"></script> </body>  </html> 

here css:

video {     width: 500px;     height: 500px;     object-fit: cover;     object-position: center; }  .camera {     width: 500px;     height: 500px;     overflow: hidden; } 

here typescript:

let canvas: htmlcanvaselement; let video: htmlvideoelement; $(window).on('load', async event => {     video = <htmlvideoelement>document.getelementbyid('monitor');     canvas = <htmlcanvaselement>document.getelementbyid('photo');      video.srcobject = await navigator.mediadevices.getusermedia({ video: true });     video.onloadedmetadata = () => {         canvas.width = 500;         canvas.height = 500;     }  });  function snapshot() {     canvas.getcontext('2d').drawimage(video, 0, 0); } 

your problem seems caused fact video element keeps aspect ratio of video, while canvas not. remember ctx.drawimage takes 8 positional , size arguments:

context.drawimage(img/vid,sx,sy,swidth,sheight,x,y,width,height);

i did testing, , found work pretty well, mileage may vary: .drawimage(video,80,0,480,500,0,0,500,520);

i made jsfiddle these numbers, check out see if works you.

w3schools has great documentation on how these work, suggest reading that: http://www.w3schools.com/tags/canvas_drawimage.asp

you use video's videowidth , videoheight attributes calculate numbers need in drawimage different aspect ratio source videos


Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -