canvas實現的彈力小球效果程式碼例項

admin發表於2017-02-10
分享一段程式碼例項,它實現了彈力小球效果。

點選滑鼠可以建立一個小球,然後具有彈力效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
body {
  padding: 0;
  margin: 0;
}
</style>
</head>
<body>
<div>
<canvas id='canvas' style="background-color:#333"></canvas>
</div>
<script>
var canvas = document.getElementById('canvas'),
  context = canvas.getContext('2d');
var x1, y1, x2, y2, paused = false,
  suzu = [],
  collarg = 0.8; //彈力系數;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
 
canvas.onmousedown = function(e) {
  x1 = e.clientX;
  y1 = e.clientY;
  paused = true;
}
 
function draw() {
  if (paused) {
    context.beginPath();
    context.moveTo(x1, y1);
    context.lineTo(x2, y2);
    context.strokeStyle = "#fff"
    context.stroke();
  }
}
 
canvas.onmousemove = function(e) {
  x2 = e.clientX;
  y2 = e.clientY;
  if (paused) {
    draw();
  }
}
 
canvas.onmouseup = function() {
  paused = false;
  var ball = new createCircle(x2, y2, (x1 - x2) / 6, (y1 - y2) / 6);
  suzu.push(ball);
  if (suzu.length > 100) {
    suzu.shift();
  }
  console.log(ball)
}
 
 
 
loop();
 
function loop() {
  context.clearRect(0, 0, canvas.width, canvas.height)
  draw();
  suzu.forEach(function(circle) {
    circle.draw(context);
    circle.update();
  })
  requestAnimationFrame(loop);
 
}
 
 
function createCircle(x, y, speedx, speedy) {
  this.radius = Math.random() * 10 + 10;
  this.x = x;
  this.y = y;
  this.color = (Math.random() * 360).toFixed(0);
  this.vX = speedx;
  this.vY = speedy;
  this.draw = function(c) {
    c.beginPath();
    c.arc(this.x, this.y, this.radius - 1, 0, Math.PI * 2);
    c.fillStyle = 'hsla(' + this.color + ',100%,60%,1)';
    c.fill();
    c.strokeStyle = 'hsla(0,100%,100%,0.6)';
    c.stroke();
    c.beginPath();
    c.arc(this.x, this.y, 5, 0, Math.PI * 2);
    c.fillStyle = 'hsla(0,100%,100%,0.6)';
    c.fill();
  }
 
  this.update = function() {
    this.vY += 0.5;
    this.y += this.vY;
    if (this.vX > 0) {
      this.vX -= 0.05;
      if (this.vX < 0) {
        this.vX = 0;
      }
    } else {
      this.vX += 0.05;
      if (this.vX > 0) {
        this.vX = 0;
      }
    }
    this.x += this.vX;
 
    if (this.y > (canvas.height - this.radius) || this.y < this.radius) {
      this.y = this.y < this.radius ? this.radius : canvas.height - this.radius;
      this.vY = -this.vY * collarg;
    }
 
    if (this.x > (canvas.width - this.radius) || this.x < this.radius) {
      this.x = this.x < this.radius ? this.radius : canvas.width - this.radius;
      this.vX = -this.vX * collarg;
    }
  }
}
 
canvasMj()
 
function canvasMj() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
}
window.addEventListener('resize', function() {
  canvasMj();
})
</script>
</body>
</html>

相關文章