gpt4 book ai didi

javascript - 独立的javascript同时移动同一个圆?

转载 作者:行者123 更新时间:2023-11-28 18:48:35 25 4
gpt4 key购买 nike

我正在使用 html 和 javascript 来制作游戏,并且我已经在这方面停留了一段时间,这部分代码都是关于让敌人从屏幕的一侧移动到另一侧,这不是我的问题与其他 Angular 色一起完成。最大的问题是我无法克隆它们并让它们独立移动。

var canvas = document.getElementById('canvas');
var h = canvas.height;
var w = canvas.width;
var ctx = canvas.getContext("2d");
var x = w
var y = Math.floor((Math.random() * 500) + 1);

clear();
circleE();

function clear(){
ctx.fillStyle = "Blue"
ctx.fillRect(0, 0, w, h)
}

function circleE(){
ctx.fillStyle = "Pink";
ctx.beginPath();
ctx.arc(x,y,15,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
}
<canvas id="canvas" width="1000" height="500" style="border:1px solid #000000;"></canvas>

最佳答案

由于它们共享 x 和 y 坐标,因此所有克隆都将在完全相同的空间中渲染。每个圆圈都需要有自己的坐标。

var canvas = document.getElementById('canvas');
var h = canvas.height;
var w = canvas.width;
var ctx = canvas.getContext("2d");

clear();

function clear(){
ctx.fillStyle = "Blue"
ctx.fillRect(0, 0, w, h)
}

function circleE(){
var x = Math.floor((Math.random() * w) + 1);
var y = Math.floor((Math.random() * h) + 1);
ctx.fillStyle = "Pink";
ctx.beginPath();
ctx.arc(x,y,15,0,Math.PI*2,false);
ctx.closePath();
ctx.fill();
}
<button onclick="circleE()">Spawn</button><br>
<canvas id="canvas" height="200" width="300"></canvas>

关于javascript - 独立的javascript同时移动同一个圆?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34911198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com