gpt4 book ai didi

javascript - 在 HTML Canvas 上清除并重新绘制正方形的过程

转载 作者:太空宇宙 更新时间:2023-11-04 16:11:45 25 4
gpt4 key购买 nike

我一直在研究一些 HTML/Javascript 代码,我希望发生的主要事情是当您按下任何箭头键时,我绘制的正方形会向该方向移动。

我对必须做的事情的总体思路是,当我单击该键时,它首先清除 Canvas ,然后根据函数使用不同的 x 和 y 值重新绘制它。

我尝试过,但发生的情况是正方形消失了,我不知道为什么。

我已经尝试调试这个有一段时间了,如果有人有任何指示,我很乐意在这里!

<!DOCTYPE html>
<html>
<head>
<title> HTML </title>
<style>
canvas {
border: 1px solid #000000;
}
</style>
</head>
<body>
<center>
<canvas width = "620" height = "620" id = "myCanvas" ></canvas>
</center>
<script src = "script.js" > </script>
</body>
</html>

这是 Javascript 代码(抱歉,格式不太好,仍在 StackOverflow 中掌握格式化代码的窍门)

document.addEventListener('keydown', function(event) {
if(event.keyCode == 37)
moveLeft();
if(event.keyCode == 39 )
moveRight();
if(event.keyCode == 38)
moveUp();
if(event.keyCode == 40)
moveDown();
});

function moveLeft() {
context.clearRect(0, 0, canvas.width, canvas.height);

//Edit X and Y Values

var newX, newY;
newX = squareX + 1;
newY = squareY;

context.rect(newX, newY, squareSizeX, squareSizeY);
context.fill(newX, newY, squareSizeX, squareSizeY);
}

function moveRight() {/* Needs to be Finished */}

function moveUp() {/* Needs to be Finished */}

function moveDown() {/* Needs to be Finished */}



var canvas;
var context;

var squareX, squareY;

var squareSizeX = 75;
var squareSizeY = 75;

function renderToCanvas() {
var didRender = false;

try {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
/* INPUT DRAWING HERE */

//Drawing Square

squareX = canvas.width / 2;
squareY = canvas.height / 2;

context.rect(squareX, squareY, squareSizeX, squareSizeY);
context.fillRect(squareX, squareY, squareSizeX, squareSizeY);
context.stroke();

/* END DRAWING HERE */

didRender = true;
console.log("Rendered Drawing: " + didRender);
}

catch(err) {
console.log("Rendered Drawing: " + didRender);
console.log(err.message);
}
}


renderToCanvas();

最佳答案

在你的moveLeft中而不是这个

context.rect(newX, newY, squareSizeX, squareSizeY);
context.fill(newX, newY, squareSizeX, squareSizeY);

这样做

context.fillRect(newX, newY, squareSizeX, squareSizeY);

Check out the docs for Canvas Context

当您使用 context.beginPath() 处理路径时,只能使用 context.rect()context.fill() >

关于javascript - 在 HTML Canvas 上清除并重新绘制正方形的过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41418902/

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