gpt4 book ai didi

javascript - 通过 JavaScript 使用 Canvas,如何通过箭头键移动对象?

转载 作者:行者123 更新时间:2023-11-30 14:07:09 24 4
gpt4 key购买 nike

我刚开始尝试为一个有趣的小项目制作一款游戏。我还是 canvas 的新手,只是想知道如何通过箭头键移动这个红色方 block ?我了解 keyup 事件,但不确定如何将它与 Canvas 合并。提前致谢

<canvas id="myCanvas" height="400" width="400" style="border: 1px solid black"></canvas>

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.translate(120,120);
ctx.lineTo(0,0);
ctx.lineTo(160,0);
ctx.lineTo(160,160);
ctx.lineTo(0,160);
ctx.lineTo(0,0);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();

document.addEventListener('keydown', function(event) {
console.log(event.keyCode);
if (event.keyCode == 37) {
ctx.clearRect(0, 0, c.width, c.height);
ctx.translate(0,0);
}

最佳答案

我已将您绘制的形状放入函数中,以便在您按下按键清除 Canvas 后再次调用它。此外,由于您正在翻译上下文,因此您需要从 (-120, -120) 中清除。我希望它有所帮助。

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");

ctx.translate(120,120);
myShape()

document.addEventListener('keydown', function(event) {
console.log(event.keyCode);
if (event.keyCode == 37) {
ctx.clearRect(-120, -120, canvas.width + 120, canvas.height + 120);
ctx.translate(-120,-120);
myShape()
}});


function myShape(){
ctx.beginPath();
ctx.lineTo(0,0);
ctx.lineTo(160,0);
ctx.lineTo(160,160);
ctx.lineTo(0,160);
ctx.lineTo(0,0);
ctx.fillStyle = "red";
ctx.fill();
ctx.stroke();}
<canvas id="myCanvas" height="400" width="400" style="border: 1px solid black"></canvas>

关于javascript - 通过 JavaScript 使用 Canvas,如何通过箭头键移动对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55155637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com