canvas小球落地彈動效果

antzone發表於2018-02-11

分享一段程式碼例項,他事先了拋落小球,然後小球會因為重力原因出現彈動效果。

程式碼是由canvas實現,感興趣的朋友可以做一下參考。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
var ball = {
  x: 512,
  y: 100,
  r: 20,
  g: 2,
  vx: -4,
  vy: -5,
  color: "#005588"
}; // g:速度
window.onload = function() {
  var canvas = document.getElementById("canvas");
 
  width = canvas.width = 1024;
  height = canvas.height = 768;
 
  var context = canvas.getContext("2d");
  time = 50;
  setInterval(function() {
    render(context);
    update();
  }, time)
}
 
function update() {
  ball.x += ball.vx;
  ball.y += ball.vy;
  ball.vy += ball.g;
  if (ball.y >= 768 - ball.r) {
    ball.y = 768 - ball.r;
    ball.vy = -ball.vy * 0.5;
  }
}
 
function render(cxt) {
  cxt.clearRect(0, 0, cxt.canvas.width, cxt.canvas.height);
  cxt.beginPath();
  cxt.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI);
  cxt.closePath();
  cxt.fill();
}
</script>
</body>
</html>

相關文章