HTML холст с javascript - PullRequest
       8

HTML холст с javascript

1 голос
/ 21 апреля 2020

У меня есть индекс. hTML файл, который просто отображает холст, подобный этому

<body>
    <canvas>
    </canvas>
    <script src="./JS/index.js" type="module"></script>
</body>

У меня есть один javascript файл, который я использую для управления холстом, как показано ниже

let canvas = document.querySelector('canvas')
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const c = canvas.getContext('2d')

class Circle {
    constructor(x, y, radius, color){
        this.x = x
        this.y = y
        this.radius = radius
        this.color = color
    }

    draw(){
        c.beginPath()
        c.arc(this.x, this.y, this.radius, Math.PI*2, false)
        c.strokeStyle = this.color

        c.stroke()

    }

}
 function manyCircles (numberOfCircles){
     requestAnimationFrame(manyCircles)
     c.clearRect(0,0,innerWidth, innerHeight)
     for (let i = 0; i <numberOfCircles; i++) {
        let x = Math.random()*innerWidth
        let y = Math.random() * innerHeight
        const circ1 = new Circle(x, y, 50, 'blue')
        circ1.draw()
     }   
     debugger
 }

manyCircles(5)

цель здесь - нарисовать 5 кругов на холсте в случайных координатах каждый раз, когда функция запускается и очищаться, а цикл повторяться, но, очевидно, для l oop работает вечно и просто заполняет экран с кругами. Однако, если у меня это так

 function manyCircles (){
     requestAnimationFrame(manyCircles)
     c.clearRect(0,0,innerWidth, innerHeight)
     for (let i = 0; i <5; i++) {
        let x = Math.random()*innerWidth
        let y = Math.random() * innerHeight
        const circ1 = new Circle(x, y, 50, 'blue')
        circ1.draw()
     }   
     debugger
 }

manyCircles()

, это похоже на работу Может кто-нибудь сказать мне, почему это работает второй случай, но не первый? какой принцип я здесь упускаю

1 Ответ

0 голосов
/ 21 апреля 2020

Если вам нужно передать аргументы внутри requestAnimationFrame, вам нужно сделать это внутри функции.

По умолчанию аргумент, передаваемый в функцию обратного вызова внутри raf, является отметкой времени. Как указано в комментариях, это число становится все более огромным.

let canvas = document.querySelector('canvas')
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const c = canvas.getContext('2d')

class Circle {
  constructor(x, y, radius, color) {
    this.x = x
    this.y = y
    this.radius = radius
    this.color = color
  }

  draw() {
    c.beginPath()
    c.arc(this.x, this.y, this.radius, Math.PI * 2, false)
    c.strokeStyle = this.color

    c.stroke()

  }

}

function manyCircles(numberOfCircles) {
  requestAnimationFrame(function() {
    manyCircles(numberOfCircles)
  })
  c.clearRect(0, 0, innerWidth, innerHeight)
  for (let i = 0; i < numberOfCircles; i++) {
    let x = Math.random() * innerWidth
    let y = Math.random() * innerHeight
    const circ1 = new Circle(x, y, 50, 'blue')
    circ1.draw()
  }
  debugger
}

manyCircles(5)
<canvas></canvas>
...