canvas笔记-绘制运动小球(落地弹起,遇边回弹)
生活随笔
收集整理的這篇文章主要介紹了
canvas笔记-绘制运动小球(落地弹起,遇边回弹)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
程序運行截圖如下:
就是這個球,遇到底端及左右兩邊都可以彈
?
源碼如下:
canvas4.html
<!DOCTYPE html> <html lang="en"> <head><meta charset="UTF-8"><title>Title</title> </head> <body><canvas id="canvas" style="display: block; margin: 50px auto;"></canvas><script src="js/test4.js"></script> </body> </html>test4.js
;const WIDTH = 1024; const HEIGHT = 768; const RADIUS = 15;let ball = {x: WIDTH / 2,y: 30,g: 1.5 + Math.random(),vx: Math.pow(-1, Math.ceil(Math.random() * 10)) * 4,vy: -5,color: '#CC0000' };window.onload = function(){let canvas = document.getElementById("canvas");let context = canvas.getContext("2d");contextBuffer.width = WIDTH;contextBuffer.height = HEIGHT;canvas.width = WIDTH;canvas.height = HEIGHT;render(context, contextTmp);setInterval(function(){render(context, contextTmp);update();},50); }function update(){ball.x += ball.vx;ball.y += ball.vy;ball.vy += ball.g;//最頂端不放if(ball.y > HEIGHT - RADIUS){ //最低端ball.y = HEIGHT - RADIUS;ball.vy = -ball.vy * 0.75;}if(ball.x < 0 + RADIUS){ //最左端ball.x = RADIUS;ball.y = HEIGHT - RADIUS;ball.vy = -Math.random() * 100 + 30;ball.vx = Math.random() * 100 + 30;}if((WIDTH - RADIUS) - ball.x < 0){ //最右端ball.x = WIDTH - RADIUS;ball.y = HEIGHT - RADIUS;ball.vy = -Math.random() * 100 + 30;ball.vx = -Math.random() * 100 + 30;} }function render(cxt){cxt.clearRect(0, 0, WIDTH, HEIGHT);cxt.fillStyle = ball.color;cxt.beginPath();cxt.arc(ball.x, ball.y, 15, 0, 2 * Math.PI);cxt.closePath();cxt.fill();; }這里只提示幾個地方,一個是clearRect()可以清空指定位置的畫板。
ball里面的vx指水平方向的速度,vy指垂直方向的速度,g值加速度。
?
?
?
?
總結
以上是生活随笔為你收集整理的canvas笔记-绘制运动小球(落地弹起,遇边回弹)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Spring Cloud笔记-eurek
- 下一篇: Oracle笔记-Oracle基本结构及