Skip to content

Create camera-capture element and an element for logging #35

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const plugins = [
'@babel/plugin-proposal-class-properties',
];

module.exports = { plugins };
269 changes: 269 additions & 0 deletions build/elements/camera-capture.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions build/elements/camera-capture.js.map

Large diffs are not rendered by default.

6 changes: 6 additions & 0 deletions build/elements/demo-logger.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions build/elements/demo-logger.js.map

Large diffs are not rendered by default.

284 changes: 284 additions & 0 deletions elements/camera-capture/camera-capture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,284 @@
import { html, css, LitElement } from '../../node_modules/lit-element';

import '../../node_modules/@material/mwc-icon';
import '../../node_modules/@material/mwc-ripple';

import './settings-pane.js';

class CameraCapture extends LitElement {
static styles = css`
:host {
display: block;
width: 100vw;
height: 100vh;
overflow: hidden;
}

.hidden {
display: none !important;
}

#mainContent {
margin: 0 auto;
}

video {
display: inline;
}

video:hover {
cursor: pointer;
}

.canvas-wrapper {
position: relative;
width: 100%;
}

.settings-wrapper {
position: absolute;
top: 0;
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: flex-end;
}

#cameraBar {
height: 100px;
background-color: transparent;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: space-around;
align-items: center;
}

#gallery {
width: 48px;
height: 48px;
}

#takePhotoButton {
height: 72px;
width: 72px;
}

#takePhotoButton mwc-icon {
--mdc-icon-size: 48px;
}

.camera-bar-icon {
height: 52px;
width: 52px;
display: flex;
justify-content: center;
outline: none;
border: 2px solid white;
border-radius: 52px;
color: white;
background-color: transparent;
}
`;

facingMode = "user";

async _onConstraintsChange(e) {
try {
await this.videoTrack.applyConstraints(e.detail.constraints);

const settings = this.shadowRoot.querySelector('settings-pane');
settings.applyFromTrack(this.videoTrack);
} catch(err) {
console.error(err);
}
}

_onSettingsBackgroundClicked(e) {
const settings = this.shadowRoot.querySelector('settings-pane');
settings.hide();
}

async _onFacingModeClicked() {
this.selectedCamera = (this.selectedCamera + 1) % this.cameras.length;
const camera = this.cameras[this.selectedCamera];
this.constraints.deviceId = { exact: camera.deviceId };
this.facingMode = this.getFacingMode(camera);
this.requestUpdate();

this.stopCamera();

const videoElement = this.shadowRoot.querySelector('video');
await this.startCamera(videoElement, this.constraints);

// Timeout needed in Chrome, see https://crbug.com/711524.
const settings = this.shadowRoot.querySelector('settings-pane');
setTimeout(async () => {
await customElements.whenDefined('settings-pane');
settings.applyFromTrack(this.videoTrack);
}, 500);
}

async takePhoto() {
try {
const blob = await this.imageCapturer.takePhoto();
const img = await createImageBitmap(blob);

const canvas = this.shadowRoot.querySelector('#gallery');
canvas.width = getComputedStyle(canvas).width.split('px')[0];
canvas.height = getComputedStyle(canvas).height.split('px')[0];
let ratio = Math.max(canvas.width / img.width, canvas.height / img.height);
let x = (canvas.width - img.width * ratio) / 2;
let y = (canvas.height - img.height * ratio) / 2;
canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height,
x, y, img.width * ratio, img.height * ratio);
} catch(err) {
console.error("takePhoto() failed: ", err)
}
}

startCamera(target, constraints) {
return new Promise(async (resolve, reject) => {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: constraints,
audio: false
});

this.video = target;
this.stream = stream;

target.srcObject = stream;
target.addEventListener('canplay', resolve, { once: true });
target.play();
} catch(err) {
reject(err);
}
});
}

stopCamera() {
if (this.video) {
this.video.pause();
this.video.srcObject = null;
}
if (this.stream) {
this.stream.getVideoTracks()[0].stop();
}
}

getFacingMode(device) {
if (device.facingMode == "environment"
|| device.label.indexOf("facing back") >= 0) {
return "environment";
}
// We assume by default that cameras are user facing
// which is mostly the case for desktop.
return "user";
}

async firstUpdated() {
this.constraints = {};

const devices = await navigator.mediaDevices.enumerateDevices();

this.cameras = [];
this.selectedCamera = 0;

devices.forEach(device => {
if (device.kind == 'videoinput') {
if (this.getFacingMode(device) == "user") {
this.cameras.push(device);
} else {
this.cameras.unshift(device);
}
}
});

// Android bug, doesn't work with DevTools emulation.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Link ?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not filed, but can you look at it and debug with Sasha?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

She had a similar workaround that broke devtools emulation

if (navigator.userAgent.includes("Android") &&
screen.orientation.type.includes("portrait")) {
this.constraints.width = Math.ceil(visualViewport.height);
this.constraints.height = Math.ceil(visualViewport.width);
} else {
this.constraints.width = Math.ceil(visualViewport.width);
this.constraints.height = Math.ceil(visualViewport.height);
}

// Disable facingModeButton if there is no environment or user mode.
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's elaborate a bit more on the comment, as we discussed ? Do we want to treat that icon as a camera switcher (say 2 user facing mode cameras on a laptop, the inbuilt and an external one), or a facing mode switcher like say on Android, (front/user and back/environment)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Switching camera on a mobile phone with just two cameras is the exact same behavior as switching between front and back

let facingModeButton = this.shadowRoot.getElementById('facingModeButton');
if (this.cameras.length < 2) {
facingModeButton.style.color = 'gray';
facingModeButton.style.border = '2px solid gray';
} else {
facingModeButton.disabled = false;
}

this.facingMode = this.getFacingMode(this.cameras[0]);
this.requestUpdate();
this.constraints.deviceId = { exact: this.cameras[0].deviceId};

const videoElement = this.shadowRoot.querySelector('video');

await this.startCamera(videoElement, this.constraints);

this.videoTrack = videoElement.srcObject.getVideoTracks()[0];
this.imageCapturer = new ImageCapture(this.videoTrack);

let cameraBar = this.shadowRoot.querySelector('#cameraBar');
cameraBar.style.width = `${videoElement.videoWidth}px`;

let mainContent = this.shadowRoot.getElementById('mainContent');
mainContent.style.width = `${videoElement.videoWidth}px`;
mainContent.classList.remove('hidden');

this.shadowRoot.querySelector('.canvas-wrapper').style.height =
`${videoElement.videoHeight}px`;

this.shadowRoot.getElementById('takePhotoButton').disabled = false;

// Timeout needed in Chrome, see https://crbug.com/711524.
const settings = this.shadowRoot.querySelector('settings-pane');
setTimeout(async () => {
await customElements.whenDefined('settings-pane');
settings.applyFromTrack(this.videoTrack);
}, 500);
}

render() {
return html`
<div id="mainContent" class="centered hidden">
<div class="canvas-wrapper">
<video id="videoInput"></video>

<div class="settings-wrapper">
<settings-pane
@click=${this._onSettingsBackgroundClicked}
@constraintschange=${this._onConstraintsChange}>
</settings-pane>

<div id="cameraBar">
<canvas id="gallery" class="camera-bar-icon"></canvas>
<div>
<button id="takePhotoButton" class="camera-bar-icon" disabled
@click=${this.takePhoto}>
<mwc-icon>photo_camera</mwc-icon>
</button>
<mwc-ripple unbounded></mwc-ripple>
</div>
<button id="facingModeButton" class="camera-bar-icon" disabled
@click=${this._onFacingModeClicked}>
<mwc-icon>${this.facingMode === "user" ? "camera_front" : "camera_rear"}</mwc-icon>
</button>
</div>
</div>
</div>
</div>
`;
}
}

customElements.define('camera-capture', CameraCapture);
36 changes: 36 additions & 0 deletions elements/camera-capture/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>Pro Camera</title>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Material+Icons&display=block" rel="stylesheet">
</head>

<script type="module" src="./camera-capture.js"></script>

<style>
body {
font-family: Roboto, sans-serif;
margin: 0;
}

camera-view {
width: 100vw;
height: 100vh;
}

.centered {
display: flex;
justify-content: center;
flex-wrap: wrap;
}

</style>

<body>
<camera-capture></camera-capture>
</body>
</html>
Loading