javascript - 如何使用 html5 画布为多个形状的移动设置动画
问题描述
我的目标是使用 canvas 标签重新创建我在 Flash 中找到的此类项目。
这是我要复制的项目: https ://www.kongregate.com/games/Stillmerlin/the-empty-kingdom
我发现很难理解当形状必须逃离视野时如何为形状的运动设置动画。
这是我目前编译的代码,我设法使用键盘在各种矩形内移动正方形:https ://jsfiddle.net/mgus17db/
var canvas = document.querySelector("#demo_canvas");
var ctx = canvas.getContext("2d");
var pg = canvas.getContext("2d");
var xPos = 75;
var yPos = 75;
function draw() {
ctx.rect(50, 50, 150, 100);
ctx.stroke();
ctx.rect(250, 50, 150, 100);
ctx.stroke();
ctx.rect(450, 50, 150, 100);
ctx.stroke();
ctx.rect(250, 200, 150, 100);
ctx.stroke();
pg.rect(xPos, yPos, 50, 50);
pg.stroke();
};
draw();
console.log("x = " + xPos + ", y = " + yPos);
function move(e) {
//ARROW KEY RIGHT
if (e.keyCode == 39) {
if (xPos == 75 && yPos == 75) {
xPos += 225;
}
else if (xPos == 300 && yPos == 75) {
xPos += 225;
};
};
//ARROW KEY LEFT
if (e.keyCode == 37) {
if (xPos == 75 && yPos == 75) {
xPos -= 0;
}
else if (xPos == 300 && yPos == 75) {
xPos -= 225;
}
else if (xPos == 525 && yPos == 75) {
xPos -= 225;
};
};
//ARROW KEY UP
if (e.keyCode == 38) {
if (yPos == 75) {
yPos -= 0;
}
else if (yPos == 225) {
yPos -= 150;
}
};
//ARROW KEY DOWN
if (e.keyCode == 40) {
if (yPos == 75 && xPos == 300) {
yPos += 150;
}
};
canvas.width = canvas.width;
draw();
console.log("x = " + xPos + ", y = " + yPos);
};
document.onkeydown = move;
解决方案
推荐阅读
- android - Android 自适应电池设置检测
- python - pytest 不显示记录器记录
- sql - Hibernate QueryException 命名参数未绑定错误
- angular - 如何从 Angular 中的 url 禁用导航
- html - 为什么divison不显示?
- aggregation - 如何根据布尔列从真到假的变化对多索引熊猫系列求和?
- three.js - 三个js复制轮换
- angular - NGXS 延迟加载模块的状态与应用程序的其余部分不同
- verilog - 赋值语句左值中的语法
- python - OANDA API 连接错误:__init__(self, conf_file) 中的 tpqoa.py 包中的 TypeError