Set focus on canvas

Hi.
In my project, I want to select shapes with radio buttons and move them with my keyboard arrow keys.
The problem is that I need to click on the canvas after each button choice, or else the radio buttons will alternate. To avoid this I tried to solve this to set the focus on canvas with each mouse release, but without success.
What could be the solution?

let rectan = false; let ball = true;
let rx = 150; ry = 150; cx = 200; cy = 250;

function setup() {
  let canvas = createCanvas(400, 400);
  radio = createRadio();
  radio.option(" rectangle");
  radio.option(" circle");
  radio.style("width", "80px");
  radio.style("line-height", "0");
  radio.position(10, 13);
  radio.style("font-size", "13px");
  radio.option(" rectangle").checked = true;
}

function draw() {
  background(220);
  if (keyIsPressed){
    if(radio.value() == " rectangle") {rectan = true; ball = false;}
    if(radio.value() == " circle") {ball = true; rectan = false;}
    if (rectan) {
      if (keyCode === RIGHT_ARROW ) rx++;
      if (keyCode === LEFT_ARROW) rx--;
      if (keyCode === UP_ARROW) ry--;
      if (keyCode === DOWN_ARROW) ry++;
    }
    if (ball) {
      if (keyCode === RIGHT_ARROW ) cx++;
      if (keyCode === LEFT_ARROW) cx--;
      if (keyCode === UP_ARROW) cy--;
      if (keyCode === DOWN_ARROW) cy++;
    }
  }
  rect(rx, ry, 100, 50);
  circle(cx, cy, 50);
}

function mouseReleased() {
  //canvas.elt.focus();
  this.focus;
}

Hi @J_Silva,

that won’t work … use blur() instead

function draw() {
  background(220);  
  radio.option(" rectangle").blur(); // remove focus from element
  radio.option(" circle").blur();    // remove focus from element
  if (keyIsPressed){    
    if (radio.value() === " rectangle") { // you can also change the if like this, then you not need the booleans rectan, ball
      if (keyCode === RIGHT_ARROW ) rx++;
      if (keyCode === LEFT_ARROW) rx--;
      if (keyCode === UP_ARROW) ry--;
      if (keyCode === DOWN_ARROW) ry++;
    }
    else {
      if (keyCode === RIGHT_ARROW ) cx++;
      if (keyCode === LEFT_ARROW) cx--;
      if (keyCode === UP_ARROW) cy--;
      if (keyCode === DOWN_ARROW) cy++;
    }
  }
  rect(rx, ry, 100, 50);
  circle(cx, cy, 50);
}  

Cheers
— mnse

2 Likes

Great! Thank you . …

@mnse
And if I want to remove the focus of a slider? How can you achieve that?
Thanks

Hi @J_Silva

sliderObj.elt.blur();

Cheers
— mnse

2 Likes

Once again, many thanks.