var canvas = document.getElementById("draw"); var x = canvas.getContext("2d"); x.font = '32px Arial'; x.fillStyle = '#007439'; x.fillText("A", 15, 35); $("#a").click(function() { var clone = $(this).clone(); console.log(clone); }); 
  #stroka { position: absolute; top: 20px; left: 20px; right: 10px; height: 100px; background: white; padding: 5px; border: solid 1px black; } #a { position: absolute; top: 140px; left: 20px; width: 50px; height: 50px; background: white; padding: 5px; border: solid 1px black; } 
 <div> <div id="stroka"></div> <div id="a" class="item"> <canvas id='draw' width='50' height='50'></canvas> </div> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="//ajax.aspnetcdn.com/ajax/jquery.ui/1.10.3/jquery-ui.min.js"></script> 

How to make so that when you press the A key with the mouse, the symbol A is displayed in the field above (as a string)?

  • If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - ߊߚߤߘ

1 answer 1

Here is a solution that takes into account a number of observations:

  1. JQuery is completely unnecessary here.
  2. It makes sense to execute a keyboard as a set of full-fledged buttons ( button elements), rather than pseudo-buttons on canvas .
  3. To event.preventDefault() text selection, call event.preventDefault() in a button click handler.
  4. Absolute positioning is replaced by relative. Let the browser do everything for us.

 "use strict"; var textLine; function onLoad() { textLine = document.getElementById("textLine"); } function addChar(character) { textLine.textContent += character; } 
 #textLine { height: 100px; background: white; margin: 10px 0px; padding: 5px; border: solid 1px black; } button { width: 50px; height: 50px; cursor: pointer; font: 32px Arial; color: #007439; /* На случай, если необходимы именно белые кнопки с чёрной границей */ /* background: white; */ /* padding: 5px; */ /* border: solid 1px black; */ } 
 <body onload="onLoad()"> <div> <div id="textLine"></div> <button onclick="addChar('a'); event.preventDefault()">A</button> <button onclick="addChar('b'); event.preventDefault()">B</button> <button onclick="addChar('c'); event.preventDefault()">C</button> <button onclick="addChar('∧'); event.preventDefault()">∧</button> <button onclick="addChar('∨'); event.preventDefault()">∨</button> <button onclick="addChar('¬'); event.preventDefault()">¬</button> </div> </body> 

  • and signs of conjunction or disjunction, and denial? - Svetlana
  • @ Svetlana, updated the example. If you need to add other buttons, do the same. - ߊߚߤߘ