首页 > 解决方案 > 对象没有出现在 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);

标签: javascriptfunction

解决方案


您忘记在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;
    }
}

推荐阅读