将小照片作为画布粒子移动

时间:2019-06-22 05:04:42

标签: javascript html canvas

我正在使用一些我在网上找到的代码来创建canvas并在屏幕上随机移动小粒子。

我是一个初学者,所以这可能是一个简单的问题,但是我将如何使用此代码或更简单的代码,而不是在屏幕上随机移动5-10个小图标(图像)?

这有效,但也可以缩放,并具有一些奇怪的效果:

var canvas = document.querySelector('canvas')
var c = canvas.getContext('2d')


canvas.width = window.innerWidth
canvas.height = window.innerHeight

var canvasX = window.innerWidth
var canvasY = window.innerHeight




var speeds = [0.17, 0.15,0.2, 0.215,0.13,0.25,0.62]
var colors = ['#F04B5780', '#EED34F80','#5EBC8780','#3E9FD680', '#F7F2E780','#F7F2F780','#FFF2F780']
function rndArray(array) {
    return array[Math.floor(Math.random() * array.length)]
}

function rndInt(min,max){
  return Math.floor(Math.random() * (max - min + 1)) + min
}

function Bubble(x,y,radius,color, speed, moveSpeedX, moveSpeedY){
  this.x = x
  this.y = y
  this.radius = radius
  this.color = color
  this.speed = speed
  this.moveSpeedX = moveSpeedX
  this.moveSpeedY = moveSpeedY
  this.canShrink = true

  this.update = function(){
    this.show()
    this.radius += this.speed
    this.x += this.moveSpeedX
    this.y += this.moveSpeedY

    if(this.radius > radius){
      this.speed = -this.speed
    }

    if(this.radius < 2){
      //this.speed = rndArray(speeds) * -1
      this.speed = -this.speed
      /*this.moveSpeed = rndInt(-2,2)
      this.color = rndArray(colors)
      this.y = rndInt(0 + this.radius, canvas.height - this.radius)
      this.x = rndInt(0 + this.radius, canvas.width - this.radius)*/
    }

    if(this.x < 0 - this.radius){
      this.x = rndInt(0+this.radius, canvasX - this.radius)
      this.moveSpeedX = rndInt(-2,2)
    }else if(this.x > canvasX + this.radius){
      this.x = rndInt(0+this.radius, canvasX - this.radius)
      this.moveSpeedX = rndInt(-2,2)
    }

    if(this.y < 0 - this.radius){
      this.y = rndInt(0 + this.radius, canvasY - this.radius)
      this.moveSpeedY = rndInt(-2,2)
    }else if(this.y > canvasY + this.radius){
      this.y = rndInt(0 + this.radius, canvasY - this.radius)
      this.moveSpeedY = rndInt(-2,2)
    }

  }

  this.show = function(){
    c.beginPath()
    c.fillStyle = this.color
    c.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false)
    c.fill()
    c.closePath()
  }
}


var bubbles = []

for(var i = 0; i < 180; i++){
  var radius = rndInt(4,4)
  var x = rndInt(0 + radius, canvasX - radius)
  var y = rndInt(0 + radius, canvasY - radius)
  var color = rndArray(colors)
  var speed = rndArray(speeds)
  var moveSpeedX = rndInt(-2,2)
  var moveSpeedY = rndInt(-2,2)
  bubbles.push(new Bubble(x,y,radius,color, speed, moveSpeedX, moveSpeedY))
}

var pX
var pX
function draw(){
  window.requestAnimationFrame(draw)
  c.fillStyle = "rgba(249, 240, 210, 1.0)";
  c.fillRect(0,0,canvas.width,canvas.height)

  for(var i = 0; i < bubbles.length; i++){
    bubbles[i].update()
    if(bubbles[i].moveSpeedY == 0){
      bubbles[i].moveSpeedY = rndInt(-2,2)
    }
  }
}
draw()

0 个答案:

没有答案