我在建立回应圈子时遇到了麻烦
到目前为止,这是我的代码:

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>


<button onclick = "myFunction()">Click me</button>
<script>
function myFunction(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
}
</script>

</body>
</html>


我要在这里实现的是,当我单击按钮时,它会产生一个圆,如果再次单击该按钮,它将产生另一个圆,现在它可以工作,但是它将自动从另一侧移动,如本例

first click: O

second click: O O

third click : O O

              O

fourth click: O O

              O O


像那样

最佳答案

您需要为每个圆的x和y位置使用两个变量posX和posY

ctx.arc(posX, posY, 50, 0, 2 * Math.PI);


这是一个例子



<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="550" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>


<button onclick = "myFunction()">Click me</button>
<script>
var posX = 100;
var posY = 75;
function myFunction(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(posX, posY, 50, 0, 2 * Math.PI);
ctx.stroke();
posX = posX + 120;
if(posX > 300)
{
  posY = posY + 120;
  posX = 100;
}
}
</script>

</body>
</html>

关于javascript - 响应圈(javascript,html5,css),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44744307/

10-12 12:57