gpt4 book ai didi

javascript - 带箭头移动 Canvas 框

转载 作者:行者123 更新时间:2023-12-02 16:10:18 26 4
gpt4 key购买 nike

我一直在尝试使用箭头键移动一个简单的 Canvas 框。这是代码:http://cssdeck.com/labs/stexplorer

这里还有:

$(function() {
var n = 3;
var xD = 0;
var yD = 0;
//var move;
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");

var ss = {
"x": 0,
"y": 0,
"width": 100,
"height": 75
};

function render() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.rect(ss.x, ss.y, ss.width, ss.height);
ctx.lineWidth = 1;
ctx.strokeStyle = "black";
ctx.stroke();
}

function move() {
x = ss.x + (xD * n);
y = ss.y + (yD * n);
ss.x = x;
ss.y = y;
}

$(document).keydown(function(e) {
xD = e.which == 37 ? -1 : xD;
xD = e.which == 39 ? 1 : xD;
yD = e.which == 38 ? -1 : yD;
yD = e.which == 40 ? 1 : yD;
e.preventDefault();
});

$(document).keyup(function(e) {
xD = e.which == 37 ? 0 : xD;
xD = e.which == 39 ? 0 : xD;
yD = e.which == 38 ? 0 : yD;
yD = e.which == 40 ? 0 : yD;
e.preventDefault();
});

render();
setInterval(move, .01);
});
body {
margin: 0;
}

#canvas {
border: 1px solid #000000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="canvas" width="300" height="200"></canvas>

这段代码应该执行以下操作:

  • 每当我按下箭头键时,该框就会移动
  • 如果我可以制作 Canvas width = "100vw"height = "100vh"

最佳答案

您的渲染方法只会在最初被触发,您应该将其添加为移动方法的最后一行,以便 Canvas 在每次移动后渲染新位置。

function move() {
x = ss.x + (xD * n);
y = ss.y + (yD * n);
ss.x = x;
ss.y = y;
render(); // add this line
}

关于javascript - 带箭头移动 Canvas 框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281640/

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