jquery 把名字印在画布上

6fe3ivhb  于 2023-04-05  发布在  jQuery
关注(0)|答案(2)|浏览(143)

我想在我的网页上创建一个画布,让用户以“Journal”字体输入他们的名字。我有下面的代码,但是,正如你在dokeyDown中看到的,我只能输入“Z”。我如何为所有字母表制作它,以便用户可以输入他们的全名。我需要为每个字母表指定keyId吗?或者他们有更简单的方法吗?下面是我的代码

<div id="my_painter">
    <canvas id="canvas" tabindex="0"></canvas>
</div>
<script>
    var tempContext = null;
    window.onload = function () {
        var canvas = document.getElementById("canvas");
        console.log(canvas.parentNode.clientWidth);
        canvas.width = canvas.parentNode.clientWidth;
        canvas.height = canvas.parentNode.clientHeight;        
        tempContext = canvas.getContext("2d");
        tempContext.fillStyle = "blue";
        tempContext.font = "20px Journal";
        canvas.addEventListener('keydown', doKeyDown, true);
        canvas.focus();        
        window.addEventListener('keydown', doKeyDown, true);
       
    }

function doKeyDown(e) {
        var keyID = e.keyCode ? e.keyCode : e.which;
        if (keyID === 90) {
            tempContext.fillText("A", 100, 60);
            e.preventDefault();
        }
    }

任何帮助都将不胜感激

9njqaruj

9njqaruj1#

这将允许您显示任何字符

不提取.keyCode,而是获取.key,这是字符本身。然后您可以轻松显示该字符。
要显示一系列字符,您需要在每一步向右移动光标,例如每次将光标向前移动几个像素。
为了让它工作得更好,你最好不要使用Journal,而是选择一个等宽字体,比如Courier New

var tempContext = null;
var x = 100
window.onload = function() {
  var canvas = document.getElementById("canvas");
  console.log(canvas.parentNode.clientWidth);
  canvas.width = canvas.parentNode.clientWidth;
  canvas.height = canvas.parentNode.clientHeight;
  tempContext = canvas.getContext("2d");
  tempContext.fillStyle = "blue";
  tempContext.font = "20px Journal";

  canvas.focus();
  window.addEventListener('keydown', doKeyDown, true);

}

function doKeyDown(e) {

  tempContext.fillText(e.key, x, 60);
  x += 9
  e.preventDefault();

}
<div id="my_painter">
  <canvas id="canvas" tabindex="0"></canvas>
</div>
k5ifujac

k5ifujac2#

您可以使用String.fromCharCode()方法将keyID变量转换为字符。这样,您就不需要匹配每个键的代码。
canvas上的监听器已经添加了,所以我在窗口上注解了监听器,否则每个字符都会被打印两次。

var tempContext = null;
window.onload = function() {
  var canvas = document.getElementById("canvas");
  canvas.width = canvas.parentNode.clientWidth;
  canvas.height = canvas.parentNode.clientHeight;
  tempContext = canvas.getContext("2d");
  tempContext.fillStyle = "blue";
  tempContext.font = "20px Journal";
  canvas.addEventListener('keydown', doKeyDown, true);
  canvas.focus();
  // window.addEventListener('keydown', doKeyDown, true);

}

var x_pos = 100;

function doKeyDown(e) {
  var keyID = e.keyCode ? e.keyCode : e.which;
  var character = String.fromCharCode(keyID);
  tempContext.fillText(character, x_pos, 60);
  x_pos += 15; // Add space between letters
  e.preventDefault();
}
<div id="my_painter">
    <canvas id="canvas" tabindex="0"></canvas>
</div>

相关问题