首页 > 解决方案 > Html Canvas 随机开始位置之后移动

问题描述

我目前正在学习 JavaScript。

我希望立方体的随机起始位置上下移动。这将导致立方体在 Y 轴上上下跳跃。

我想让立方体上下移动

图片

也许是这样:

Y = Y + speed;
if(Y <= 0) {
    speed = -speed;
}
if(Y >= canvas.width) {
    speed = -speed;
}

这就是我的代码:

window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
draw();
}
function draw(){
    canvasContext.fillStyle = "white";
    canvasContext.fillRect(0,0,canvas.width,canvas.height, "#cc33ff");
    for (var i=0; i <= 50; i++) {
        var randX = Math.floor(Math.random() * 800);
        X = randX;
        var randY = Math.floor(Math.random() * 600);
        Y = randY;
        speed = 10;
        var colorArray = ['#2185C5', '#7ECEFD', '#FFF6E5', '#FF6666'];    
        var randColor = colorArray[Math.floor(Math.random() * colorArray.length)];    
        canvasContext.beginPath();
        canvasContext.rect(X, Y, 20, 20);   
        canvasContext.fillStyle = randColor;
        canvasContext.fill();
        canvasContext.strokeStyle = "black";
        canvasContext.stroke();
        canvasContext.closePath();
    }
}

标签: javascripthtmlcanvasrandom

解决方案


在这种情况下,您需要将正方形保存在数组中。您还需要一个函数来更新正方形的位置。在我的回答中,我使用了一个更新所有正方形的函数和另一个绘制所有正方形的函数。更好的解决方案是使用绘制或更新单个正方形的函数,并为每个正方形调用该函数。

var cw,ch,w = 20;
var squares = []

canvas = document.getElementById('gameCanvas');
// set the canvas width and height
cw = canvas.width = 800;
ch = canvas.height = 600;
canvasContext = canvas.getContext('2d');

for (var i=0; i <= 50; i++) {
  // make a new square object
  var sq = {}
        var randX = Math.floor(Math.random() * (cw - w));
        sq.X = randX;
        var randY = Math.floor(Math.random() * (ch - w));
        sq.Y = randY;
        sq.speed = 1;
        var colorArray = ['#2185C5', '#7ECEFD', '#FFF6E5', '#FF6666'];    
        var randColor = colorArray[Math.floor(Math.random() * colorArray.length)]; 
        sq.color = randColor;
        // push the new square object into the squares array
        squares.push(sq);

    }

function Draw() {
// to animate the squares you will need to use the requestAnimationFrame method
window.requestAnimationFrame(Draw);
canvasContext.clearRect(0,0,cw,ch);

draw();
update();
}

Draw();

function draw(){
    canvasContext.fillStyle = "white";
    canvasContext.fillRect(0,0,canvas.width,canvas.height);
    for (var i=0; i < squares.length; i++) {
        var sq = squares[i];
        canvasContext.beginPath();
        canvasContext.rect(sq.X, sq.Y, w, w);   
        canvasContext.fillStyle =sq.color;
        canvasContext.fill();
        canvasContext.strokeStyle = "black";
        canvasContext.stroke();
        canvasContext.closePath();
    }
}

function update(){
// a function to update the squares position with every frame.
  for (var i=0; i < squares.length; i++) {
        var sq = squares[i];
        if(sq.Y >= ch - w || sq.Y <= 0){sq.speed *= -1;}
        sq.Y += sq.speed;
}
}
<canvas id="gameCanvas"></canvas>


推荐阅读