skip to Main Content

I´m trying to add an EventListener to my canvas when I lose focus in this canvas.

I have two canvases:

enter image description here

In the first canvas (at left), I draw a signature, and when change focus to the right canvas, I want the signature drawn on the first canvas to get saved in the server. I know how I can apply the logic to save in the server but I am unable to call the blur event in the canvas.

To try this, I’m doing:

var canvas = document.getElementById("pizarra_cliente");
canvas.addEventListener("blur" , function() { 
  console.log("entro");
});

But if I put a debugger in the developer tools, I see the breakpoint is not being fired inside the blue event. I tried with the onfocusout as well but got the same problem.

Anybody can help me to create an event (focusOut or blur) to my canvas?

I´m using blur because I read that this is an event that should be used in such use cases.

2

Answers


  1. Chosen as BEST ANSWER

    i get it with this logic:

    canvas.addEventListener("mouseout", function(evt) {
      let c = document.querySelector('#pizarra_cliente');
      var b64Image = c.toDataURL("image/png");
      let token = document.querySelector('meta[name="csrf-token"]').content;
      let contract = document.getElementById('n_contract').value;
      let installation = document.getElementById('installation_id').textContent;
      
      // upload image canvas to server
      fetch("/installator/saveClientSignature", {
          method: "POST",
          //mode: "no-cors",
          headers: {
            "Content-Type": "application/x-www-form-urlencoded",
            'X-CSRF-Token': token,
          },
          body: JSON.stringify({'image':b64Image, 'contract': contract, 'install': installation})
      }).then(response => response.text())
        .then(success => "")
        .catch(error => "");
    
    })
    

    I used mouseout event to get event and generate image with canvas data. My image it´s generated ok, and saved in my folder.


  2. If nothing works, you can use window.addEventListener('click', e => {}) and check if the element is other than the canvas. You can use a flag to make it run only once, like:

    // Create the flag
    let leftCanvasFocused = false
    
    // Place this inside your function that guarantee 
    // that the user is interacting with the canvas 
    // (probably something related to draw)
    leftCanvasFocused = true
    
    
    window.addEventListener('click', e => {
      if (!leftCanvasFocused || e.target.id !== 'pizarra_cliente') return
    
      leftCanvasFocused = false
    
      // Your logic goes here
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search