javascript - 对象没有出现在 JS 中
问题描述
我正在尝试在 JS 上创建一个典型的突围游戏。到目前为止,一切都完美无缺,除了我试图绘制的桨没有出现在屏幕上。下面我提供了jscode。你能建议可能是什么问题吗?
var canvas = document.getElementById("myCanvas"); var ctx = canvas.getContext("2d");
var x = canvas.width/2;
var y = canvas.height-30;
var dx = 2;
var dy = -2;
var ballRadius = 10;
/* Defining the parameters of the paddle and its starting point */
var paddleHeight = 10;
var paddleWidth = 75;
var paddleX = (canvas.width-paddleWidth) / 2;
/* Control variables */
var rightPressed = false;
var leftpressed = false;
/* Functions */
function drawBall() {
ctx.beginPath();
ctx.arc(x, y, ballRadius, 0, Math.PI*2);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function drawPaddle() {
ctx.beginPath();
ctx.rect(paddleX, canvas.height-paddleHeight, paddleWidth, paddleHeight);
ctx.fillStyle = "#0095DD";
ctx.fill();
ctx.closePath();
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
x += dx;
y +=dy;
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
}
}
/* Speed of the ball */
setInterval(draw, 10);
解决方案
您忘记在drawPaddle()
函数内部调用draw()
函数。尝试这个,
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawBall();
drawPaddle();
x += dx;
y +=dy;
if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
dx = -dx;
}
if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
dy = -dy;
}
}
推荐阅读
- python - 将临床文档名称映射到 LOINC 名称
- django - 保存到 JSONField 时 Django 和 Celery 的意外行为
- html - 是否可以将数据 URL 放入 QR 码中?
- python-3.x - Boto3 Kafka API 未出现
- amazon-web-services - Codedeploy 回滚未选择先前成功的构建版本
- java - 如何在 Spring Boot 中防止外部连接失败(如 Redis 服务器)快速失败?
- rest - REST API 用户资源及其密码
- php - 从控制器获取数据并通过 AJAX 显示
- java - Java 中的类序列化:更改字段名称或 getter/setter 名称后的兼容性
- python - 每次都在 django-sqlite3 中创建相同的数据对象?