1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
class SimpleCamera extends HTMLElement { constructor() { super(); } connectedCallback() { const shadow = this.attachShadow({ mode: 'open' });
this.videoElement = document.createElement('video'); this.canvasElement = document.createElement('canvas'); this.videoElement.setAttribute('playsinline', true); this.canvasElement.style.display = 'none';
shadow.appendChild(this.videoElement); shadow.appendChild(this.canvasElement) }
open(constraints) { return navigator.mediaDevices.getUserMedia(constraints) .then((mediaStream) => { this.videoElement.srcObject = mediaStream; this.videoElement.onloadedmetadata = (e) => { this.videoElement.play() } }) }
_drawImage() { const imageWidth = this.videoElement.videoWidth; const imageHeight = this.videoElement.videoHeight; this.canvasElement.width = imageWidth; this.canvasElement.height = imageHeight;
const context = this.canvasElement.getContext('2d'); context.drawImage(this.videoElement, 0, 0, imageWidth, imageHeight); return { imageHeight, imageWidth } }
takeBlobPhoto() { const { imageHeight, imageWidth } = this._drawImage(); return new Promise((resolve, reject) => { this.canvasElement.toBlob((blob) => { resolve({ blob, imageHeight, imageWidth }) }) }) }
takeBase64Photo({ type, quality } = { type: 'png', quality: 1 }) { const { imageHeight, imageWidth } = this._drawImage(); const base64 = this.canvasElement.toDataURL('image/' + type, quality); return { base64, imageHeight, imageWidth } }
}
customElements.define('simple-camera', SimpleCamera)
(async function() { const camera = document.querySelector('simple-camera') const btnBlobPhoto = document.querySelector('#btnBlobPhoto') const btnBase64Photo = document.querySelector('#btnBase64Photo') const base64Img = document.getElementById('base64Img');
await camera.open({ video: { facingMode: 'user' } }).catch(err => { console.log('摄像头开启失败', err) })
btnPhoto.addEventListener('click', async event => { const photo = await camera.takeBlobPhoto() console.log(photo) base64Img.src = URL.createObjectURL(photo.blob); })
btnBase64Photo.addEventListener('click', async event => { const photo = camera.takeBase64Photo({ type: 'jpeg', quality: 1 }) console.log(photo) base64Img.src = photo.base64; }) }())
|