1

So I displayed text to the html canvas with c.fillText. I want to make it so that when I click/hover over the displayed text, a box will show up where we can input text. Is this possible?

var canvas = document.querySelector('canvas');
canvas.width = "1290";
canvas.height = "580";
var c = canvas.getContext("2d");

function ques() {
  var question = document.getElementById("qInput").value;
  //window.alert(question);
  var randomColor = Math.floor(Math.random() * 16777215).toString(16);
  var fontSize = Math.floor(Math.random() * 45 + 12);
  var x = Math.floor(Math.random() * 1200);
  var y = Math.floor(Math.random() * 580);

  c.fillStyle = "#" + randomColor;
  c.font = fontSize + "px Times New Roman";
  c.fillText(question, x, y);
}
canvas {
 /*
  position: absolute;
 top: 9%;
 left: 2.5%;
  */
  border: 1px solid #ddd;
}
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

<p class="title">Days in the Sun</p>
<canvas></canvas>

<!--for the search bar-->
<div class="search">
  <input type="text" placeholder="Search.." name="search" id="qInput">
  <button type="submit" onclick="ques()">
  <i class="fa fa-search"></i>
 </button>
</div>
Daniel Sixl
  • 2,488
  • 2
  • 16
  • 29
Novelcie
  • 56
  • 7

2 Answers2

0

If i understand you , you can do it with :
1)Make cursor pointer of the text with CSS.

canvas{
cursor:pointer;
}

2)Use javaScript.

document.getElementByTagName('canvas').addEventListener('click' , myFunction);

And in this function you can use javasript to change the DOM .If you want to be hovered replase "click" with mouseover ,but if you use mouse over you have to make another event on same element with "mouseout"

Nikolay
  • 17
  • 5
0

in such cases uses frameworks like Phaser/PIXI. But if you want make it by native canvas, hm:

  • You has x/y coordinates of your text(relatively to canvas element)(left and top x/y)
  • You can get right and bottom coordinates of text by using:

    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    ctx.measureText(text).width/height
    
  • now on click or on mousemove(hover analog) events, just compare the coordinates of the cursor(e.clientX, e.clientY) and the frame of the text, do they converge.

here is more descriptions with example, in link below: HTML Canvas Hover Text