Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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;
  }
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!