Reputation: 29
Im using Angular 8 to access the webcam over the browser.
startCamera() {
if (!!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
navigator.mediaDevices.getUserMedia(this.constraints).then(this.attachVideo.bind(this)).catch(this.handleError);
} else {
alert('Sorry, camera not available.');
}
}
handleError(error) {
console.log('Error: ', error);
}
attachVideo(stream) {
this.renderer.setProperty(this.videoElement.nativeElement, 'srcObject', stream);
this.renderer.listen(this.videoElement.nativeElement, 'play', (event) => {
this.videoHeight = this.videoElement.nativeElement.videoHeight;
this.videoWidth = this.videoElement.nativeElement.videoWidth;
});
}
capture() {
this.renderer.setProperty(this.canvas.nativeElement, 'width', this.videoWidth);
this.renderer.setProperty(this.canvas.nativeElement, 'height', this.videoHeight);
this.canvas.nativeElement.getContext('2d').drawImage(this.videoElement.nativeElement, 0, 0);
var data_uri = this.canvas.nativeElement.toDataURL("image/png")
this.visitor.photoFileName = data_uri
}
when I start my app on localhost it works but over Http it doesn't. is there a way or a library to make this work?
Upvotes: 2
Views: 6772
Reputation: 275
//selfie
WIDTH = 1136;
HEIGHT = 840;
@ViewChild("video") video: ElementRef;
@ViewChild("canvas") canvas: ElementRef;
isCaptured: boolean;
error: any;
setupDevices() {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
console.log('ghiles')
console.log(navigator.mediaDevices)
console.log('ghiles')
navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => {
this.video.nativeElement.srcObject = stream;
this.video.nativeElement.play();
console.log(stream)
})
.catch( err => {
console.log(err)
// alert('Autorisation camera refusée');
console.log('Autorisation camera refusée');
const dialogReference: MatDialogRef<any, any> = this.MatDialog.open(AutorisationComponent, {
width: '1728px'
});
})
}
}
capture() {
this.canvas.nativeElement.getContext("2d").drawImage(this.video.nativeElement, 0, 0, this.WIDTH, this.HEIGHT);
console.log(this.canvas.nativeElement.getContext("2d"))
this.isCaptured = true;
var dataurl = this.canvas.nativeElement.toDataURL();
this.selfieImg = {
filename: 'selfie',
is_link: false,
mimetype: 'image/png',
source: dataurl.split(',')[1]
}
console.log(this.selfieImg)
}
Upvotes: 0
Reputation: 135
The HTTP doesn't require the UserMedia from the MediaDevices, so it doesn't require camera permission. For accessing the camera, you'll need to use HTTPS, in order to ask for the camera permission.
One solution is run: ng s --host 0.0.0.0 --ssl true
. The --host 0.0.0.0
will expose your client to external access, and the --ssl true
will use HTTPS instead of HTTP.
It works for both <video></video>
or the ngx-webcam
Upvotes: 0
Reputation: 346
You can use ngx-webcam. This allows the user to access the webcam through browser.
Sample code to use ngx-webcam:
app.component.html
<div style="text-align:center">
<h1>
Ngx-Webcam Demo
</h1>
<div>
<webcam [height]="500" [width]="500" [trigger]="triggerObservable" (imageCapture)="handleImage($event)" *ngIf="showWebcam"
[allowCameraSwitch]="allowCameraSwitch" [switchCamera]="nextWebcamObservable"
[videoOptions]="videoOptions"
[imageQuality]="1"
(cameraSwitched)="cameraWasSwitched($event)"
(initError)="handleInitError($event)"
></webcam>
<br/>
<button class="actionBtn" (click)="triggerSnapshot();">Take A Snapshot</button>
<button class="actionBtn" (click)="toggleWebcam();">Toggle Webcam</button>
<br/>
<button class="actionBtn" (click)="showNextWebcam(true);" [disabled]="!multipleWebcamsAvailable">Next Webcam</button>
<input id="cameraSwitchCheckbox" type="checkbox" [(ngModel)]="allowCameraSwitch"><label for="cameraSwitchCheckbox">Allow Camera Switch</label>
<br/>
DeviceId: <input id="deviceId" type="text" [(ngModel)]="deviceId" style="width: 500px">
<button (click)="showNextWebcam(deviceId);">Activate</button>
</div>
</div>
<div class="snapshot" *ngIf="webcamImage">
<h2>Nice one!</h2>
<img [src]="webcamImage.imageAsDataUrl"/>
</div>
<h4 *ngIf="errors.length > 0">Messages:</h4>
<ul *ngFor="let error of errors">
<li>{{error | json}}</li>
</ul>
<h2>Like this project on GitHub:</h2>
<ul class="links">
<li>
<h2><a target="_blank" rel="noopener" href="https://github.com/basst314/ngx-webcam">Ngx-Webcam / GitHub</a></h2>
</li>
</ul>
app.component.ts
import {Component, OnInit} from '@angular/core';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
import {WebcamImage, WebcamInitError, WebcamUtil} from 'ngx-webcam';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
// toggle webcam on/off
public showWebcam = true;
public allowCameraSwitch = true;
public multipleWebcamsAvailable = false;
public deviceId: string;
public videoOptions: MediaTrackConstraints = {
// width: {ideal: 1024},
// height: {ideal: 576}
};
public errors: WebcamInitError[] = [];
// latest snapshot
public webcamImage: WebcamImage = null;
// webcam snapshot trigger
private trigger: Subject<void> = new Subject<void>();
// switch to next / previous / specific webcam; true/false: forward/backwards, string: deviceId
private nextWebcam: Subject<boolean|string> = new Subject<boolean|string>();
public ngOnInit(): void {
WebcamUtil.getAvailableVideoInputs()
.then((mediaDevices: MediaDeviceInfo[]) => {
this.multipleWebcamsAvailable = mediaDevices && mediaDevices.length > 1;
});
}
public triggerSnapshot(): void {
this.trigger.next();
}
public toggleWebcam(): void {
this.showWebcam = !this.showWebcam;
}
public handleInitError(error: WebcamInitError): void {
this.errors.push(error);
}
public showNextWebcam(directionOrDeviceId: boolean|string): void {
// true => move forward through devices
// false => move backwards through devices
// string => move to device with given deviceId
this.nextWebcam.next(directionOrDeviceId);
}
public handleImage(webcamImage: WebcamImage): void {
console.info('received webcam image', webcamImage);
this.webcamImage = webcamImage;
}
public cameraWasSwitched(deviceId: string): void {
console.log('active device: ' + deviceId);
this.deviceId = deviceId;
}
public get triggerObservable(): Observable<void> {
return this.trigger.asObservable();
}
public get nextWebcamObservable(): Observable<boolean|string> {
return this.nextWebcam.asObservable();
}
}
Upvotes: 1