Utilizing Angular for Webcam Integration

After trying out this code snippet:

<video autoplay playsinline style="width: 100vw; height: 100vh;"></video>
<script>
    navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } })
        .then(stream => document.querySelector('video').srcObject = stream);
</script>

I attempted to modify it for use in a WebApp with Angular. The revised TypeScript code looks like this:

@ViewChild('myVideo') myVideo: any;

public takePicture(event?: any): void {
navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } })
.then(stream => this.myVideo.srcObject = stream);
}

This goes in the .ts file, and the following HTML markup is added:

        <button (click)="takePicture($event)"></button>
        <video #myVideo autoplay playsinline style="width: 100px; height: 100px;"></video>

Although the original example worked when opened in a browser as a standalone file, I encountered issues adapting it for Angular. Despite not receiving any error messages, I was unable to access my webcam input. It seems that the browser is prompting for camera permission, but no video feed is displayed.

Best regards from Germany!

Answer №1

//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)

}

Answer №2

If you're not seeing any output, it could be because when using viewchild, you need to access the srcObject by

this.myVideo.nativeElement.srcObject

You can either follow the method above or use traditional JavaScript document.getElementById like this:

public takePicture(event?: any): void {
const vid = document.getElementById("videoelementId")
navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } })
.then(stream => vid.srcObject = stream);
}

I have created a plugin based on this concept,

https://www.npmjs.com/package/get-my-photo

https://github.com/Faiz-exe/get-my-photo

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimizing Bootstrap popover responsiveness for elements with excessive length to ensure a smooth display experience

I am currently working on creating a popover that remains in position when hovered over, specifically for elements that are too large to fit on the screen. However, I am facing some issues with my current implementation: <template> <div class ...

Height Difference Caused by Textarea Overflow with Auto Scrollbars

Displayed below is code that generates a textarea with 3 visible rows: <textarea id="txtInput" rows="3" cols="20" style="overflow:auto"></textarea> Unexpectedly, in Firefox (version 20.0.1), the textarea displays 4 rows instead of 3. To view ...

What is the simplest method to customize or enhance Angular 5 directives with Angular-material?

In my Angular5 application, I am utilizing the angular-material library in some areas. However, I prefer to maintain a level of agnosticism in my markup when it comes to external libraries. Despite this, I attempted the following approach: import { Direc ...

Is there a way to access service data within an Angular interceptor?

I'm trying to include my authentication token in the request header within my auth.interceptor.ts. The value of the authentication token is stored in auth.service.ts. Below is the code for auth.interceptor.ts @Injectable() export class AuthIntercepto ...

Encountering a TypeError while attempting to utilize Django and Pandas for displaying data in an HTML format

import pandas as pd from django.shortcuts import render # Define the home view function def home(): # Read data from a CSV file and select only the 'name' column data = pd.read_csv("pandadjangoproject/nmdata.csv", nrows=11) only_city ...

Why does the Change Detection problem persist even when using On Push with the same object reference?

After a recent discussion on Angular Change detection, I believed I had a solid understanding. However, my confidence wavered when I encountered this issue: Why is change detection not happening here when [value] changed? To further illustrate the problem ...

The importation of TypeScript source modules is not compiled accurately in the distribution folder

Currently, I am working on a REST API in TypeScript with the following structure: ├── dist │ ├── index.js │ ├── library.js ├── src │ ├── index.ts │ ├── library.ts ├── node_modules ├── package. ...

Understanding the behavior of the enter key in Angular and Material forms

When creating forms in my MEAN application, I include the following code: <form novalidate [formGroup]="thesisForm" enctype="multipart/form-data" (keydown.enter)="$event.preventDefault()" (keydown.shift.enter)="$ev ...

Cannot locate module: Error: Unable to find the path '../containers/Layout' in '/home/yusquen/Projectss/react-shop/src/components'

https://i.stack.imgur.com/U1097.png description of image goes here Issue with module: Error: The file '../containers/Login' could not be found in the 'react-shop/src/components' directory. ...

Unable to click on hyperlink and image not adjusting in size

I am having an issue with the anchor tags inside a div. For some reason, the width and height are set to 0px, and I have tried to adjust them with no success. Each dot in my onepage scroller is meant to navigate to a different page. .dotstyle-scaleup{ f ...

Is there an alternative to RequestOptionsArgs that I can use in this function?

I am currently working on updating an existing Angular application from version 4.3 to Angular 8. One of the challenges I'm facing is replacing old component classes like ConnectionBackend, RequestOptions, and RequestOptionsArgs with their updated equ ...

The droplist functionality in jQuery does not seem to be functioning properly within an ASP.NET MVC 5

After adding an external theme to my project and writing a script for listing data in a dropdown list on a separate page, I encountered an issue where the script works on other pages but not on the Layout theme page. HomeController Note: The partial view ...

Implementing full-window mask when hovering over a div

I've been grappling with creating a mask that covers an image within a div, but I can't seem to get it to cover the entire area without leaving whitespace in the middle. I've tried various solutions to fix it, but nothing has worked so far. ...

Angular 8 combined with Mmenu light JS

Looking for guidance on integrating the Mmenu light JS plugin into an Angular 8 project. Wondering where to incorporate the 'mmenu-light.js' code. Any insights or advice would be greatly appreciated. Thank you! ...

Steps for adding a stroke to just the left and right sides of an SVG wave:

How do I apply a stroke only to the right and left sides of an SVG (specifically a wave SVG)? <svg class="defs-only" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <symbol id="wave"> <svg viewBox="0 0 100 50" ...

Adding strings in Typescript

I have the following code snippet: let whereClause = 'CurLocation =' + GS + ' and Datediff(DD,LastKYCVerified,GetDate()) >= 180 and CreditCard = ' + 'ACTIVE ' + &ap ...

When evaluating objects or arrays of objects to determine modifications

How can we detect changes in table data when users add input to cells? For example, if a user clicks on a cell and adds an input, the function should return TRUE to indicate that there are changes. If the user just clicks on the cell without making any ch ...

Clicking on text triggers image display

My journey in coding is just starting and I have a good understanding of the basics of HTML, CSS, Javascript, and jQuery. I am trying to make an image appear when I click on text but struggling with the implementation. I'm working on a restaurant web ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...

Troubleshooting Paths with Angular's NgFor Directive

Within my Angular project, I have implemented a basic ngFor loop to display logo images. Here is a snippet of the code: <div *ngFor="let item of list" class="logo-wrapper"> <div class="customer-logo"> & ...