我希望能够使用箭头键移动一个矩形(我使用javascript创建)。我也希望它在我的画布结束时停止。我怎么做?我对此都很陌生,绝对没有任何线索。
function fillRect () {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var rectX=10;
var rectY=10;
context.rect(rectX,rectY,50,50);
context.fillStyle = "#666666";
context.fill();
}
function onkeydown(e) {
if(e.keyCode==39) {rectX++;} //right arrow
elseif(e.keyCode==37) {rectX--;} //left arrow
elseif(e.keyCode==38) {rectY--;} //up arrow
elseif(e.keyCode==40) {rectY++;} //down arrow
fillRect();
}
window.addEventListener("keydown", onkeydown);

#myCanvas {
margin: auto;
display: block;
width: 80%;
height: 400px;
background-color: white;
border: 3px solid black;
}

<!-- Jessica Odefjord -->
<!DOCTYPE HTML>
<html lang="sv">
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="inlämningsuppgift_javascript_jessicaodefjord.css" />
<script type="text/javascript" src="inlämningsuppgift_javascript_jessicaodefjord.js"></script>
<title>Flytta rektangeln</title>
</head>
<body>
<header>
<h1>Flytta rektangeln</h1>
<h2>Flytta runt rektangeln med hjälp av piltangenterna</h2>
</header>
<main>
<section id="firstsection">
<h3>
</h3>
</section>
<canvas id="myCanvas">
</canvas>
</main>
</body>
</html>
&#13;
答案 0 :(得分:0)
首先声明将保存矩形位置的变量。例如:
var rectX=0;
var rectY=0;
然后在context.rect(0,0,50,50);
将0,0
替换为上述变量,如下所示:
context.rect(rectX,rectY,50,50);
最后在窗口上添加一个密钥处理程序:
function onkeydown(e) {
if(e.keyCode==39) {rectX++;} //right arrow
else if(e.keyCode==37) {rectX--;} //left arrow
else if(e.keyCode==38) {rectY--;} //up arrow
else if(e.keyCode==40) {rectY++;} //down arrow
fillRect();
}
window.addEventListener("keydown", onkeydown);
答案 1 :(得分:0)
使用代码gdros并自己提供:
小提琴: https://jsfiddle.net/k3akqz3c/1/
// Basic variables
var canvas;
var context;
var rectX = 10;
var rectY = 10;
// Set canvas context
window.onload = function() {
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
}
function fillRect() {
context.beginPath();
context.fillStyle = "#ffffff";
context.fillRect(0, 0, 1000 + canvas.width, 1000 + canvas.height);
context.beginPath();
context.fillStyle = "#666666";
// Check if the rect isn't out of bounds, if so: place it back.
if (rectX < 0) {
rectX = 0;
} else if (rectX > 250) {
rectX = 250;
}
if (rectY < 0) {
rectY = 0;
} else if (rectX > 100) {
rectX = 100;
}
context.fillRect(rectX, rectY, 50, 50);
}
function onkeydown(e) {
if (e.keyCode == 39) {
rectX++;
} //right arrow
else if (e.keyCode == 37) {
rectX--;
} //left arrow
else if (e.keyCode == 38) {
rectY--;
} //up arrow
else if (e.keyCode == 40) {
rectY++;
} //down arrow
fillRect();
}
window.addEventListener("keydown", onkeydown);
基本上,每当您按下其中一个箭头键,就会在不同的位置重新创建矩形。