当前位置: 首页 > 工具软件 > mediadevices > 使用案例 >

【js调用摄像头拍照】navigator.mediaDevices.getUserMedia、canvas

晏鸿畅
2023-12-01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 400px;
            background: #ccc;
            border: 10px solid #ddd;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <div class="box">
        <video id="video" width="400" height="300"></video>
        <button id='snap'>拍照</button>
        <canvas id='canvas' width='400' height='300'></canvas>
        <img id='img' src=''>
    </div>
    <script>
        var video = document.getElementById('video'),
            canvas = document.getElementById('canvas'),
            snap = document.getElementById('snap'),
            img = document.getElementById('img');

        var constraints = { audio: true, video: { width: 1280, height: 720 } };

        navigator.mediaDevices.getUserMedia(constraints)
            .then(function (mediaStream) {
                video.srcObject = mediaStream;//srcObject属性用于播放 实时流;src属性用于播放多媒体文件,比如MP4等
                video.onloadedmetadata = function (e) {//onloadedmetadata 事件在指定视频/音频(audio/video)的元数据加载后触发
                    video.play();
                };
            })
            .catch(function (err) {
                console.log(err.name + ": " + err.message);
            })
        snap.addEventListener('click', function () {

            //绘制canvas图形
            canvas.getContext('2d').drawImage(video, 0, 0, 400, 300);

            //把canvas图像转为img图片展示
            img.src = canvas.toDataURL("image/png");//得到一个带前缀的base64字符串

        })
    </script>
</body>
</html>
 类似资料: