Is there a way to take a snapshot of an HTML Canvas frame and showcase it on a Bootstrap modal?

I have a page where users must grant permission for their webcam or camera. Once granted, a webmoji will move according to the user's face position.

Below is a button that will turn blue and become active once a face is detected. When clicked, I want to capture the current frame of the WebMoji/Canvas and display it in a modal using Bootstrap 4.

Here is the code snippet related to these elements, along with the JavaScript I have implemented:

<button type="button" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#exampleModal" id="captureFrameBtn" disabled>Face not detected</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true" role="button">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="frameContainer"></div>

            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- CANVAS WITH THE USER FACE : -->
<canvas class="jeefacetransferCanvas" id="jeefacetransferCanvas"></canvas>
<!-- CANVAS WITH THE WEBOJI : -->
<canvas class="webojiCanvas" id="webojiCanvas" width="600" height="600"></canvas>

<script>
    // Accessing the emoji canvas by its ID
    var canvas = document.getElementById("webojiCanvas");
    var img = canvas.toDataURL("image/jpg");
    var captureButton = document.getElementById("captureFrameBtn");
    var frameContainer = document.getElementById("frameContainer");
    captureButton.addEventListener("click", function() {
        frameContainer.innerHTML = "<img src='" + img + "'>";
    });
</script>

Answer №1

When dealing with the contents of frameContainer, it is advisable to avoid directly manipulating its .innerHTML property. Instead, a better approach would be to create a new instance of HTMLImageElement, set its .src property to the result of the .toDataURL() function, and then append it to the target div using .appendChild().

For example:

var canvas = document.getElementById("webojiCanvas");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();


var captureButton = document.getElementById("captureFrameBtn");
var frameContainer = document.getElementById("frameContainer");

captureButton.addEventListener("click", function() {
  var img = new Image();
  img.id = "theDuplicate";
  img.src = canvas.toDataURL("image/jpg");
  if (document.getElementById(img.id)) {
    document.getElementById(img.id).src = img.src;
  } else {
    frameContainer.appendChild(img);

  }
});
<button type="button" class="btn btn-danger btn-lg" data-toggle="modal" data-target="#exampleModal" id="captureFrameBtn">
      Face not detected
</button>

<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
              <span aria-hidden="true" role="button">&times;</span>
            </button>
      </div>
      <div class="modal-body" id="frameContainer"></div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">
              Close
            </button>
      </div>
    </div>
  </div>
</div>


<canvas class="webojiCanvas" id="webojiCanvas" width="200" height="200"></canvas>

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

Unable to adjust the padding of the material UI Select component

I'm having trouble adjusting the padding of the Select component in order to align it with the size of my other text fields. Despite knowing that I need to make changes to nested components, I have yet to discover a viable solution. <div className ...

Using Javascript to trigger a setTimeout function after the user's mouse leaves

There is a div that pops up when the user's mouse exits the webpage, containing a survey pertaining to my website. I want to avoid prompting users to take the survey if they move their cursor out of the page within the first few minutes of browsing. ...

AngularJS: Triggering events in one controller to update data in another controller

I've tried several examples, but I'm not getting the expected results. In my project, I have two controllers - one for a dropdown and one for a table. When a user selects an item from the dropdown, a factory triggers a get request to update the t ...

Tips for effectively showcasing div elements

https://jsfiddle.net/qz8hL574/1/ for (var key in table) { if (table.hasOwnProperty(key)) { $('<div class="element"></div>').appendTo('#list'); document.getElementsByClassName("element")[key].innerHTML = ...

Despite being a valid <link rel="shortcut icon">, a validation error occurs

I'm encountering an error with the w3.org validator related to this line of code: <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> The error message provided is as follows: Line 1, Column 727: Invalid value shortcut icon f ...

Is it possible to modify this code to accept multiple IDs at once?

I'm attempting to create a form in JavaScript where, upon entering the necessary details and clicking submit, the user's email client opens with the information pre-filled for easy sending. However, I am facing challenges as my code involves mult ...

Unable to load CSS background image and update code

After writing the code in my CSS file, /*The code I initially wrote*/ .wrapper::before { content: ""; position: absolute; bottom: -30%; left: 0; height: 100%; width: 100%; background: url(../img/homeTrans2.svg) no-repe ...

Clicking on a span will allow you to alter the text within a paragraph located in a

I am hoping to update a paragraph of text with new content when a faux 'link' (span) at the bottom of the page is clicked. This is what I have so far <body> <p> This is the paragraph that should be changed after clicking on the sp ...

The functionality of ClickMarker is malfunctioning in the XY Amcharts

Recently, I encountered a situation where I had to incorporate custom legends in XY Amcharts. After managing to implement them successfully, I came across an issue. Despite adding event listeners to the legends, the associated function failed to trigger. ...

Creating input fields dynamically within Yii2 framework

I'm currently facing a challenge with forms in Yii2. My objective is to design a form that includes three dropdown menus, inquiring about the user's preferred time(s) during the week. The first menu will focus on selecting days of the week, while ...

What is the best way to incorporate CDN into my webpack build process?

I have developed a module with the following code: export default () => console.log('hello my_module~!') The configuration in the webpack.config.js file looks like this: module.exports = { // ... output: { // ... library: 'he ...

Arranging blocks within blocks? Placing additional text underneath a block

Looking to append some text at the end of a block called .label. Inside this block, there is a sub-element called .label_title, and below that is a picture/link enclosed in another block. Under the picture/link, I wish to include a short description while ...

Generate new variables based on the data received from an ajax call

Suppose there is a .txt file containing some integers separated by spaces, like '22 1 3 49'. I would like to use Ajax to read the file as an array or list, and then save each integer as a JavaScript variable. Currently, this code reads all cont ...

The jQuery script tag fails to recognize click events once dynamically loaded with the load event

Hey there, I recently utilized this script in a SAP WebDynpro setup to dynamically load and employ jQuery. The onload event of the script tag is functioning well as I can select the text of the focused element. However, I am facing issues with registering ...

Utilizing Visual Studio: Implementing jsmin in post-build actions

After attempting to add jsmin.exe as a post-build event in my VS 2010 project, I encountered an "error code 9009" when building the project. I tested this in the command prompt and found that it works if I navigate to the folder and run: jsmin < debug ...

Eliminating characteristics and rejuvenating the component

I have divs on my webpage that I want to keep hidden until a specific element is clicked. When trying to hide them, I encountered three options: visibilty: hidden - I didn't like this because the hidden div still took up space in the layout. displa ...

Struggling to implement Datatables row grouping using ajax is proving to be quite challenging

Is there a way to group rows in a table based on date ranges, using the data from the first column ("Due_Date"), and leveraging the rowGroup extension provided by Datatables? I've tried various solutions found online, such as using the data property ( ...

What is the best way to apply a background image to a DIV element using CSS

The main aim is to change the background image of a DIV using AJAX. $.getJSON("https://itunes.apple.com/search?term=" + searchTerm + '&limit=1' + '&callback=?', function(data) { $.each(data.results, fun ...

Stopping Form Submission with MUI TextField

I am currently creating a form using React along with MUI. I'm trying to figure out how to prevent the form from being submitted when the user hits the enter key. Usually, I would use e.preventDefault(), but for some reason it's not working in th ...

Is there a way to rotate a div without utilizing the "transform" CSS property?

I am currently utilizing a plugin from the SVG library to render graphics within a div (). However, I am encountering an issue when attempting to rotate it using the "transform" property. The rotation is purely visual and does not alter the X and Y axes of ...