Create a new canvas for each iteration of a Vue.JS template loop

I'm having trouble figuring out how to initialize a local "signaturePad" canvas for each loop or required signature.

Additionally, I am interested in binding "dataURL" to signaturePad.toDataURL("image/jpg"). This means displaying the dataURI for every entered signature.

If anyone can assist, it would be greatly appreciated! Here is the JSfiddle link: https://jsfiddle.net/kaihendry/kt53sa2r/1/

// var canvas = document.querySelector("canvas");
// var signaturePad = new SignaturePad(canvas);
// var wrapper = document.getElementById("signature-pad");

// How do I initialise signaturePad for every signatureNeeded?

new Vue({
  el: "#app",
  data: {
    signaturesNeeded: 2,
  },
  methods: {
    submitForm: function(x) {
      fetch('/echo/html', {
          method: 'POST',
          body: new FormData(x.target)
        })
        .then(() => {
          var button = document.getElementById("button")
          button.innerText = 'Sent!'
        })
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87f4ee...[email protected]</a>/dist/signature_pad.min.js"></script>
<div id="app">
  <label>Number of signatures required
<input type=number v-model.number="signaturesNeeded">
</label>
  <form id="myForm" v-on:submit.prevent="submitForm">
    <template v-for="item in signaturesNeeded">
    
<div class="signature-pad">
<div class="signature-pad--body">
<canvas></canvas>
</div>
<div class="signature-pad--footer">
<div class="description">Sign above</div>
</div>
    
<input required type=text size=80 placeholder="Name" name=name>
<input required type=text size=80 name=dataURL>

</template>

    <button class="button" id="button" type="submit">Sign</button>
  </form>
  <a href="https://github.com/szimek/signature_pad">Signature pad sources</a>
</div>

Answer №1

To create a personalized component (like signature-pad), you can set up SignaturePad within it. I've included a functional code snippet below that demonstrates this process. The signature data URL updates when the user stops writing (it appears beneath the canvas) and all URLs are gathered by the parent component. Take a look:

Vue.component('signature-pad', {
    template: '#signaturepad',
    data() {
        return {
            signaturePad: null,
            dataUrl: null
        }
    },
    mounted() {
        this.signaturePad = new SignaturePad(this.$refs.canv, {
           onEnd: () => { 
               this.dataUrl = this.signaturePad.toDataURL();
               // For illustration purposes, all URLs are collected in the parent component
               this.$emit('update', this.dataUrl)
           }
        });
    }
});

new Vue({
  el: "#app",
     data: {
    signaturesNeeded: 2,
    // Example of storing all signature URLs
    signatureDataUris: []
  },
      methods: {
    submitForm: function (x) {
        fetch('/echo/html', { method: 'POST',
            body: new FormData(x.target) })
        .then(() => {
            var button = document.getElementById("button")
            button.innerText = 'Sent!'
        })
    },
    
    updateSignature(index, url) {
       Vue.set(this.signatureDataUris, index, url);
       console.log(this.signatureDataUris);
    }
    }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e7d6769606f7a7b7c6b517e6f6a4e3c203d203c">[email protected]</a>/dist/signature_pad.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
  <label>Number of signatures required
<input type=number v-model.number="signaturesNeeded">
</label>
  <form id="myForm" v-on:submit.prevent="submitForm">
    <template v-for="item in signaturesNeeded">
    
<signature-pad @update="(val) => updateSignature(item-1, val)" ></signature-pad>

<input required type=text size=80 placeholder="Name" name=name>
</template>
    <button class="button" id="button" type="submit">Sign</button>
  </form>
  <a href="https://github.com/szimek/signature_pad">Signature pad sources</a>
</div>


<script type='text/x-template' id="signaturepad">
<div class="signature-pad">
    <div class="signature-pad--body">
    <canvas ref="canv"></canvas>
      <div>{{dataUrl}}</div>
    </div>
    <div class="signature-pad--footer">
    <div class="description">Sign above</div>
   </div>
</div>
</script>

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

Incorporate a new class into the slot's scope

I'm developing a custom table feature that allows users to customize <td> elements using a slot. Here's the current setup: <tbody> <tr v-for="(item, key) in items"> <slot :item=item"> <td v-for="(header, he ...

Ensure history.back() does not trigger Confirm Form Resubmission

Within my web application, every form submission is directed to an action folder. Once the process is complete, the user is redirected back to their original location. However, a problem arises when the user performs an action that requires the application ...

Best practices for utilizing the getTile() method within Google Maps

I have a question about storing markers in a database using tile IDs. The goal is to display all the markers associated with a specific tile when it is displayed on a map. Initially, I created a code that was not working correctly. It only requested one ...

The removeEventListener function is failing to properly remove the keydown event

Every time my component is rendered, I attach an event listener. mounted() { window.addEventListener("keydown", e => this.moveIndex(e)); } Interestingly, even when placed within the moveIndex method itself, the event listener persists and cannot ...

Dim the background for all elements except for one

Seeking a way to create a dimmed-background effect by adjusting the opacity of all elements on the page except for one specific element. I've experimented with using the :not() selector as well as jQuery selectors to exclude certain elements, but have ...

Tips for notifying the user about incorrect login credentials in Ionic 3

I'm attempting to implement a notification system using showAlert to inform users when they enter an incorrect email or password, but I'm having difficulty achieving this using try and catch statements Would it be feasible for me to use try and ...

Top recommendation: Utilizing Typescript to allow a customer to enhance an application using their own tailored code

Our application framework is built on Angular 9, providing customers the ability to customize applications with different fields and layouts. This functionality works smoothly. However, we now face a situation where a customer wants to incorporate special ...

React Tetris game always returns false in its function

Within my react project, I am working with a 2D array containing numbers. I have implemented a function called collisionCheck that iterates through the array to check for specific values. My goal is for this function to return true and exit when it encou ...

Unable to interpret the JSON reply from the server

I am currently developing a web application that sends data to a website, which then updates its database and returns a JSON array to replace my web app page. I am using AJAX for this query, but I am facing an issue with preventing the overwriting of my we ...

Encountering issues with Office.context.document.getFileAsync function

I am experiencing a strange issue where, on the third attempt to extract a word document as a compressed file for processing in my MS Word Task Pane MVC app, it crashes. Here is the snippet of code: Office.context.document.getFileAsync(Office.FileType.Co ...

Attempting deletion with Node.js's Mongoose Framework

Having some trouble with the following code snippet. It doesn't seem to be functioning correctly and is resulting in a 404 error. Any insights on how to troubleshoot this issue? app.delete("/tm/v1/tasks", (req,res) => { Task.findOneAndDelete ...

Angular 10 does not reflect changes in the array when they occur

My component receives an array of offers from an Observable. However, when the list is modified (a offer is deleted), the component's list does not update accordingly. I attempted to use ngOnChanges to resubscribe to the list and update it in my comp ...

Tips for accessing a web service using JavaScript (AJAX)

I have two projects: one is a web service and the other is an ASP.NET web project. I am trying to insert data using JSON (with AJAX). I tested the web service file with code behind and it works fine, but I'm encountering an error with the JavaScript ...

The footer seems to be losing its stickiness and not staying at the bottom when I

My goal is to create a sticky footer for my webpage. Once you click the add new sports button, a drawer slides out and the footer remains fixed at the bottom. However, as I scroll down the page, the footer moves up instead of staying in place. I have tried ...

Exploring the concept of JavaScript closures and the pitfalls of name clobber

Is it possible for variables defined inside an inner function with the same name as a variable in an outer function to be isolated from the outer variable? function() { var myTest = "hi there"; ( function( myLocalTest ) { myLocalTest = "go ...

The slider customization on Joomla is functioning perfectly on my local machine, but it seems to be encountering some issues on

Having recently started working on a Joomla website for the first time, I encountered some challenges when trying to add a slider module. Despite successfully implementing the slider on my local machine, I faced issues when transferring the code to the liv ...

Tips for troubleshooting a 422 (Unprocessable Entity) Error Response in a Vue/Laravel project

I'm currently struggling to connect the frontend of my simple Vue 3 and Laravel 8 contact form project with the backend. No matter what data values I pass, whether it's null or not, I keep getting a 422 (Unprocessable Entity) response without any ...

Is it possible to maintain component data in Angular while also incorporating dynamic components?

All the code you need can be found here: https://stackblitz.com/edit/angular-keep-alive-component?file=src/app/app.component.ts Is it possible to maintain the state of entered values when switching components? I am currently utilizing dynamic component r ...

Introducing the new and improved SweetAlert 2.0, the ultimate solution for

I am currently utilizing SweetAlert2.0, known as "This One" <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script> It is functioning properly; however, I would like to display a table, div, or HTML element within this swe ...

AngularJS: Component fails to load controller

I am managing a directory structure that looks like this --- js/app.js ------- components ----------- header -------------- headerComponent.html -------------- headerComponent.js -------------- headerController.js Within index.html, I have the following ...