How to click a canvas element?

0

How could click 'if the person enters a link for fillText in Canvas ?

Edito: I'm still investigating and I've seen you say that I can associate an event handler to the canvas , then take the text coordinates and if you click the text, l or redirects , but also my problem is that it does not help me to do it for a STATIC TEXT , so what should I do?

With ' clickable ' I mean you can click if it's a URL , and take you to that URL by opening another tab.

Investigating I read this, but I still do not know how to do it in practice:

  

You can detect clicks on the canvas if you add an event handler   click on the canvas element and then extract the parameters from   mouse position of the event, converts them into local coordinates,   check the items that you click and perform any action that   be necessary.

var h = document.getElementById("go");
h.addEventListener("click",function() {
  
var texto = prompt("Ingresa texto a dibujar");
var context = document.getElementById("canvas");
var ctx = context.getContext("2d");

ctx.font = "20px monospace";
ctx.fillText(texto, 20, 60);
  
ctx.font = "40px monospace";
ctx.fillText("Creando textos..", 70, 30);
  
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <input value="Crear texto" type="button" id="go"/>
  <canvas width="1080" height="720" id="canvas"></canvas>
</body>
</html>
    
asked by Eduardo Sebastian 30.06.2017 в 04:53
source

1 answer

0
  

With 'cliqueable' I mean you can click if it's a URL, and you   take that URL by opening another tab

It is not possible what you intend at least not with canvas , remember that the elements that are drawn have no representation except px and color

  

You can detect clicks on the canvas if you add an event handler   click on the canvas element

You're already doing clickeable in your code by adding addEventListener

  

then extracts the mouse position parameters from the event, converts them to local coordinates, checks the elements that you click and performs any necessary actions.

It is true that in the event click as data of the event is the position of the event mouse x , y with this you can draw where you from click within canvas has many utilities

Ejm

var canvas  = document.getElementById('canvas');
canvas.addEventListener("click",function(e){
  var texto = prompt("Ingresa texto a dibujar");
  var context = document.getElementById("canvas");
  var ctx = context.getContext("2d");

  ctx.font = "20px monospace";
  /* Agregamos el texto en la pos x y del click */
  ctx.fillText(texto, e.x, e.y);

});
<canvas width="1080" height="720" id="canvas"></canvas>
    
answered by 30.06.2017 в 05:11