'keyIsPressed to write on canvas where mouse is clicked p5js

I am working on a function which enables users to write onto screen where mouse has been clicked however there are a few problems.

Firstly: keyIsPressed is executed multiple times making each key appear more than once with a single click.

Secondly: It will only allow for a single letter to be printed before the mouseX and mouseY are set back to -1.

Here is my code:

function setup() {
  createCanvas(400, 400);
  var startMouseX = -1;
  var startMouseY = -1;
  var drawing = false;
}

function draw() {
  background(220);
  if(mouseIsPressed)
    {
       startMouseX = mouseX;
       startMouseY = mouseY;

       drawing = true;
    }
    else if(keyIsPressed)
        {
            textSize(20);
            text(key,startMouseX,startMouseY);
            startMouseX += textWidth(key);            
        }
    else{
        drawing = false;
        startMouseX = -1;
        startMouseY = -1;
    }

}

Any help would be appreciated thanks



Solution 1:[1]

I think the approach with the 'drawing' variable works. But instead of drawing the new letter in draw you can use the keyTyped() function. In the same manner you could use mouseMoved() to reset the 'drawing' variable

var drawing = true;

function setup() {
    createCanvas(400, 400);
}

function keyTyped() {
    if (drawing) text(key, mouseX, mouseY);
    drawing = false;
}

function mouseMoved() {
    drawing = true;
  }

Solution 2:[2]

my solution:

let drawing = false;
let drawMouseX = -1;
let drawMouseY = -1;


function setup() {
  
  createCanvas(400, 400);
  
  background("white");
  
}

function keyTyped(){
  
  if(!drawing){
  
    drawing = true;
    
    drawMouseX = mouseX;
    drawMouseY = mouseY;
  
  }
  
  text(key, drawMouseX, drawMouseY)
    
  drawMouseX += textWidth(key);
  
}

function mouseMoved(){
  
  drawing = false;
  
}

This makes it so the things you type are permanently on the canvas. Is this what you wanted? if not, it would be a lot harder.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Philipp Lehmann
Solution 2 KoderM