Javascript.RU

Создать новую тему Ответ
 
Опции темы Искать в теме
  #1 (permalink)  
Старый 05.04.2023, 09:54
Новичок на форуме
Отправить личное сообщение для zfoxx Посмотреть профиль Найти все сообщения от zfoxx
 
Регистрация: 05.04.2023
Сообщений: 5

getUserMedia() Сделать несклько фото через веб камеру с возможностью их удаления.
Всем доброго дня, помогите разобраться как сделать несколько фото с веб камеры.
После нажатия на кнопку "Сделать фото" должны появляться новые фотографии (предыдущие не должны удаляться).
У каждой новой фотографии должна быть кнопка удалить фото (по ее нажатию должна удаляться именно выбранное фото).

HTML:
<!doctype html>
<html>
<head>
	<title>WebRTC: Демонстрация фотосъемки</title>
	<meta charset='utf-8'>
	<link rel="stylesheet" href="vid.css" type="text/css" media="all">
	<script src="vid.js">
	</script>
</head>
<body>
<div class="contentarea">

  <div class="camera">
    <video id="video">Видеопоток недоступен.</video>
    <button id="startbutton">Сделать фото</button> 
  </div>
  <br>
  <canvas id="canvas">
  </canvas>
  <div class="output">
    <img id="photo" alt="The screen capture will appear in this box."> 
  </div>

</div>
</body>
</html>


JS:
(function() {

  var width = 320;    // Масштабирование по ширине
  var height = 0;

  var streaming = false;	  // |streaming| указывает, идет трансляция в настоящее время или не идет
							  // Начинаем с false. (Не идет)

  var video = null;			  // Различные элементы HTML, Переменные для функции startup()
  var canvas = null;
  var photo = null;
  var startbutton = null;

  function startup() {
    video = document.getElementById('video');
    canvas = document.getElementById('canvas');
    photo = document.getElementById('photo');
    startbutton = document.getElementById('startbutton');
	
    
	navigator.mediaDevices.getUserMedia({video: true, audio: false})
    .then(function(stream) {
      video.srcObject = stream;
      video.play();
    })
    .catch(function(err) {
      console.log("An error occurred: " + err);
    });

    video.addEventListener('canplay', function(ev){
      if (!streaming) {
        height = video.videoHeight / (video.videoWidth/width);
      
        // Firefox в настоящее время имеет ошибку, из-за которой высота не может быть прочитана
        // поэтому мы будем делать предположения, если это произойдет.
      
        if (isNaN(height)) {
          height = width / (4/3);
        }
      
        video.setAttribute('width', width);
        video.setAttribute('height', height);
        canvas.setAttribute('width', width);
        canvas.setAttribute('height', height);
        streaming = true;
      }
    }, false);


    startbutton.addEventListener('click', function(ev){
      takepicture();
      ev.preventDefault();
    }, false);
    
    clearphoto();
  }

    // Заполняем фотографию
  function clearphoto() {
    var context = canvas.getContext('2d');
    context.fillStyle = "#AAA";
    context.fillRect(0, 0, canvas.width, canvas.height);

    var data = canvas.toDataURL('image/png');
    photo.setAttribute('src', data);
  }

  function takepicture() {
    var context = canvas.getContext('2d');
    if (width && height) {
      canvas.width = width;
      canvas.height = height;
      context.drawImage(video, 0, 0, width, height);
    
      var data = canvas.toDataURL('image/png');
      photo.setAttribute('src', data);
    } else {
      clearphoto();
    }
  }

  window.addEventListener('load', startup, false);
})();


CSS:
#video {
  border: 1px solid black;
  box-shadow: 2px 2px 3px black;
  width:320px;
  height:240px;
}

#photo {
  border: 1px solid black;
  box-shadow: 2px 2px 3px black;
  width:320px;
  height:240px;
}

#canvas {
  display:none;
}

.camera {
  width: 340px;
  display:inline-block;
}

.output {
  width: 340px;
  display:inline-block;
}

#startbutton {
  display:block;
  position:relative;
  margin-left:auto;
  margin-right:auto;
  bottom:32px;
  background-color: rgba(0, 150, 0, 0.5);
  border: 1px solid rgba(255, 255, 255, 0.7);
  box-shadow: 0px 0px 1px 2px rgba(0, 0, 0, 0.2);
  font-size: 14px;
  font-family: "Lucida Grande", "Arial", sans-serif;
  color: rgba(255, 255, 255, 1.0);
}

.contentarea {
  font-size: 16px;
  font-family: "Lucida Grande", "Arial", sans-serif;
  width: 760px;
}
Ответить с цитированием
  #2 (permalink)  
Старый 05.04.2023, 10:42
Аватар для рони
Профессор
Отправить личное сообщение для рони Посмотреть профиль Найти все сообщения от рони
 
Регистрация: 27.05.2010
Сообщений: 33,071

фото через веб камеру с возможностью их удаления
zfoxx,
<!DOCTYPE html>
<html>
<head>
    <title>WebRTC: Демонстрация фотосъемки</title>
    <meta charset='utf-8'>
    <style type="text/css">
        #video {
            border: 1px solid black;
            box-shadow: 2px 2px 3px black;
            width: 320px;
            height: 240px;
        }
        #photo {
            border: 1px solid black;
            box-shadow: 2px 2px 3px black;
            width: 320px;
            height: 240px;
        }
        #canvas {
            display: none;
        }
        .camera {
            width: 340px;
            display: inline-block;
        }
        .output {
            width: 340px;
            display: inline-block;
        }
        #startbutton {
            display: block;
            position: relative;
            margin-left: auto;
            margin-right: auto;
            bottom: 32px;
            background-color: rgba(0, 150, 0, 0.5);
            border: 1px solid rgba(255, 255, 255, 0.7);
            box-shadow: 0px 0px 1px 2px rgba(0, 0, 0, 0.2);
            font-size: 14px;
            font-family: "Lucida Grande", "Arial", sans-serif;
            color: rgba(255, 255, 255, 1.0);
            opacity: 0;
            transition: 1s;
        }
        #startbutton.streaming {
            opacity: 1;
        }
        .contentarea {
            font-size: 16px;
            font-family: "Lucida Grande", "Arial", sans-serif;
            width: 760px;
        }
    </style>
    <script>
        (function() {
            var width = 320;
            var height = 0;
            var streaming = false;
            var video = null;
            var canvas = null;
            var photo = null;
            var startbutton = null;
            function startup() {
                video = document.getElementById('video');
                canvas = document.getElementById('canvas');
                photo = document.getElementById('photo');
                startbutton = document.getElementById('startbutton');
                navigator.mediaDevices.getUserMedia({
                        video: true,
                        audio: false
                    })
                    .then(function(stream) {
                        video.srcObject = stream;
                        video.play();
                        startbutton.classList.add('streaming');
                    })
                    .catch(function(err) {
                        console.log("An error occurred: " + err);
                    });
                video.addEventListener('canplay', function(ev) {
                    if (!streaming) {
                        height = video.videoHeight / (video.videoWidth / width);
                        if (isNaN(height)) {
                            height = width / (4 / 3);
                        }
                        video.setAttribute('width', width);
                        video.setAttribute('height', height);
                        canvas.setAttribute('width', width);
                        canvas.setAttribute('height', height);
                        streaming = true;
                    }
                }, false);
                startbutton.addEventListener('click', function(ev) {
                    takepicture();
                    ev.preventDefault();
                }, false);
            }
            function takepicture() {
                var context = canvas.getContext('2d');
                if (width && height) {
                    canvas.width = width;
                    canvas.height = height;
                    context.drawImage(video, 0, 0, width, height);
                    var data = canvas.toDataURL('image/png');
                    let photo = new Image;
                    photo.src = data;
                    let botton = document.createElement('button');
                    botton.textContent = 'del';
                    botton.addEventListener('click', () => {
                        botton.remove();
                        photo.remove();
                    });
                    document.querySelector('.output').append(photo, botton);
                }
            }
            window.addEventListener('load', startup, false);
        })();
    </script>
</head>
<body>
    <div class="contentarea">
        <div class="camera">
            <video id="video">Видеопоток недоступен.</video> <button id="startbutton">Сделать фото</button>
        </div><br>
        <canvas id="canvas"></canvas>
        <div class="output"></div>
    </div>
</body>
</html>
Ответить с цитированием
  #3 (permalink)  
Старый 05.04.2023, 14:37
Новичок на форуме
Отправить личное сообщение для zfoxx Посмотреть профиль Найти все сообщения от zfoxx
 
Регистрация: 05.04.2023
Сообщений: 5

Круто, спасибо
Ответить с цитированием
  #4 (permalink)  
Старый 05.04.2023, 14:40
Аватар для Alexandroppolus
Профессор
Отправить личное сообщение для Alexandroppolus Посмотреть профиль Найти все сообщения от Alexandroppolus
 
Регистрация: 25.10.2016
Сообщений: 1,005

Сообщение от рони
canvas.toDataURL('image/png');
возможно, надо сразу toBlob, с перспективой отправки на сервер (это же будет сохранено на сервере)?
и формат лучше image/jpeg
Ответить с цитированием
Ответ



Опции темы Искать в теме
Искать в теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Мультиселект элементов через запятую с возможностью удаления IgorN jQuery 4 07.09.2011 11:12