CanvasRenderingContext2D

CanvasRenderingContext2D

我是Javascript新手,写了一个基本的pong街机游戏。我想在游戏中用一个图像作为球。我试着用以下几行代码替换下面的代码:

var img = new Image();
img.src = "http://yourimage.jpg";

但没用。有什么建议或暗示吗?创建一个HTML对象会更容易吗。顶部的代码片段和下面的完整代码。谢谢。
//snippet
function colorCircle(centerX,centerY, radius, drawColor){
    canvasContext.fillStyle = drawColor;
    canvasContext.beginPath();
    canvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true);
    canvasContext.fill();

    // ball
    colorCircle(ballX, ballY, 10, 'green')
}

全场比赛:
<html>

<canvas id="gameCanvas" width="800" height="600"></canvas>



<script>
// set my vars
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 10;
var ballSpeedY = 5;

var player1Score = 0;
var player2Score = 0;
const WINNING_SCORE = 3;
var showingWinScreen = false;

var paddle1Y = 250;
var paddle2Y = 250;

// consts cannot be changed when game is played.
const PADDLE_HEIGHT = 100;
const PADDLE_THICKNESS= 10;

function calculateMousePos(evt) {
    var rect = canvas.getBoundingClientRect();
    var root = document.documentElement;
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return {

        x:mouseX,
        y:mouseY
    }



}

function handleMouseClick(evt) {
    if(showingWinScreen) {
        player1Score = 0;
        player2Score = 0;
        showingWinScreen = false;
    }


}

window.onload = function() {
    canvas = document.getElementById('gameCanvas');
    canvasContext = canvas.getContext('2d');

    var framesPerSecond = 30;
    setInterval(function() {
        moveEverything();
        drawEverything();
    }, 1000/framesPerSecond );

    canvas.addEventListener('mousedown', handleMouseClick);

    // rewatch section 2 lecture 7
    canvas.addEventListener('mousemove',
        function(evt) {
            var mousePos = calculateMousePos(evt);
            paddle1Y = mousePos.y-(PADDLE_HEIGHT/2);


        });
}

function ballReset() {
    if(player1Score >= WINNING_SCORE ||
        player2Score >= WINNING_SCORE) {
        showingWinScreen = true;

    }
    ballSpeedX = -ballSpeedX;
    ballX = canvas.width/2;
    ballY = canvas.height/2;
}

function computerMovement() {
    var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
    if(paddle2YCenter < ballY-35) {
        paddle2Y += 6;
    } else if(paddle2YCenter > ballY+35) {
        paddle2Y -= 6;
    }
}

function moveEverything() {
    if(showingWinScreen){
        return;
    }
    computerMovement();
    ballX += ballSpeedX;
    ballY += ballSpeedY;

    if(ballX < 0) {
        if(ballY > paddle1Y &&
            ballY < paddle1Y+PADDLE_HEIGHT) {
            ballSpeedX = -ballSpeedX
        var deltaY = ballY-(paddle1Y+PADDLE_HEIGHT/2);
            ballSpeedY = deltaY * .35;
        } else {
            player2Score += 1; //must be BEFORE ball reset
            ballReset();
            //++ adds one and

        }

    }
    if(ballX > canvas.width) {
        if(ballY > paddle2Y &&
            ballY < paddle2Y+PADDLE_HEIGHT) {
            ballSpeedX = -ballSpeedX

            var deltaY = ballY-(paddle2Y+PADDLE_HEIGHT/2);
            ballSpeedY = deltaY * .35;
        } else {
            player1Score ++;
            ballReset();
            //--removes one

        }
    }
        if(ballY < 0) {
        ballSpeedY = -ballSpeedY;
    }
    if(ballY > canvas.height) {
        ballSpeedY = -ballSpeedY;
    }




}

function drawNet() {
    for(var i=0;i<canvas.height; i+=40) {
        colorRect(canvas.width/2-1, i, 2, 20, 'red');


    }


}

function drawEverything() {

    // next line blanks out the screen with black
    colorRect(0,0,canvas.width,canvas.height,"black");



    if(showingWinScreen){
        canvasContext.fillStyle = "orange";
        if(player1Score >= WINNING_SCORE) {
            canvasContext.fillText("Left Player Wins!", 350, 200);

        } else if( player2Score >= WINNING_SCORE) {
            canvasContext.fillText("Right Player Wins!", 350, 200);

        }

        canvasContext.fillText("Click to Continue!", 350, 500);
        return;
    }

    drawNet();

    //left player paddle
    colorRect(0,paddle1Y,PADDLE_THICKNESS,PADDLE_HEIGHT, 'white');

    //right player paddle
    colorRect(canvas.width-PADDLE_THICKNESS,paddle2Y,PADDLE_THICKNESS,PADDLE_HEIGHT, 'white');

    // ball
    colorCircle(ballX, ballY, 10, 'green')

    canvasContext.fillText(player1Score, 100, 100);
    canvasContext.fillText(player2Score, canvas.width - 100, 100);

    }

function colorCircle(centerX,centerY, radius, drawColor){
    canvasContext.fillStyle = drawColor;
    canvasContext.beginPath();
    canvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true);
    canvasContext.fill();

}

function colorRect(leftX,topY, width,height, drawColor){
    canvasContext.fillStyle = drawColor;
    canvasContext.fillRect(leftX,topY, width,height);

}

最佳答案

您需要使用CanvasRenderingContext2D.drawImage()
定义函数drawBall()

function drawBall(centerX, centerY, radius) {
    // get the ball diameter
    var diameter = radius * 2;

    canvasContext.drawImage(
        img,
        // the region of clipping from the img
        0, 0, img.width, img.height,
        // the region of drawing the ball on the canvas
        centerX - radius, centerY - radius, diameter, diameter
    );
}

替换function drawEverything()中的以下代码
// ball
colorCircle(ballX, ballY, 10, 'green');


// ball
drawBall(ballX, ballY, 10);

有关CanvasRenderingContext2D.drawImge()的更多信息,请转到MDNCanvasRenderingContext2D.drawImage()

09-18 08:01