如何将圆圈连续放置在随机位置?

How to place the circle in random positions continuously?

如何将圆圈连续放置在随机位置??

我想把这个圆圈放在随机位置,比如从一个随机位置跳到另一个位置等等...请回答怎么做??

let canvas = document.getElementById("canvas");
    let context = canvas.getContext("2d");
    // for canvas size
    var window_width = window.innerWidth;
    var window_height = window.innerHeight;
    
    canvas.width = window_width;
    canvas.height = window_height;
    let hit_counter=0;
    function randomIntFromInterval(min, max) { // min and max included 
      return Math.floor(Math.random() * (max - min + 1) + min)
    }
    
    class Circle {
      constructor(xpos, ypos, radius, color, text) {
        this.position_x = xpos;
        this.position_y = ypos;
        this.radius = radius;
        this.text = text;
        this.color = color;
      }
      
      // creating circle
      draw(context) {
        context.beginPath();
        context.strokeStyle = this.color;
        context.fillText(this.text, this.position_x, this.position_y);
        context.textAlign = "center";
        context.textBaseline = "middle"
        context.font = "20px Arial";
        context.lineWidth = 5;
        context.arc(this.position_x, this.position_y, this.radius, 0, Math.PI * 2);
        context.stroke();
        context.closePath();
      }
      
      update() {
        if(hit_counter%70 == 0){
          this.text =Math.floor((randomIntFromInterval(1, 20)));
          hit_counter = 1;
      }
      hit_counter++;
        context.clearRect(0, 0, window_width, window_height)
        this.draw(context);
    
        if ((this.position_x + this.radius) > window_width) {
          this.dx = -this.dx;
          
        }
    
        if ((this.position_x - this.radius) < 0) {
          this.dx = -this.dx;
          
        }
    
        if ((this.position_y - this.radius) < 0) {
          this.dy = -this.dy;
          
        }
    
        if ((this.position_y + this.radius) > window_height) {
          this.dy = -this.dy;
          
        }
    
        this.position_x += this.dx;
        this.position_y += this.dy;
      }
    }
      
    let my_circle = new Circle(100, 100, 50, 'Black', hit_counter);
    
    
      my_circle.update();
 <canvas id="canvas"></canvas>

您可以使用 setInterval 在延迟的时间后调用函数。

根据您的代码片段,我建议使用 setInterval 在新位置构造然后破坏一个圆:

// Circle Definition
...

const WAIT_TIME_IN_MS = 3000;
let circle = new Circle(x, y, 50, 'Black', hit_counter); // Assuming you want one circle

const interval = setInterval(() => {
    circle.update();
}, WAIT_TIME_IN_MS);

只需在 Circle.update 调用 Circle.draw:

之前更新 Circle.position_xCircle.position_y
...

    update() {
        ...
        context.clearRect(0, 0, window_width, window_height);
        this.position_x = randomIntFromInterval(window_width, window_height);
        this.position_y = randomIntFromInterval(window_width, window_height);
        ...
    }
...

当你想停止这个间隔时,你可以调用clearInterval(interval)