JavaScript+canvas實現框內跳動小球
更新時間:2022年04月12日 15:38:27 作者:麥兜:)
這篇文章主要為大家詳細介紹了JavaScript+canvas實現框內跳動小球,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了JavaScript+canvas實現框內跳動小球的具體代碼,供大家參考,具體內容如下
效果如下:

思路:
1.制定畫布,確定好坐標
2.繪制出圓形小球
3.給圓一個原始坐標,xy軸的速度
4.每20毫秒刷新一次,達到變化的目的
5.判斷邊緣
全部代碼及釋義如下:
<!DOCTYPE html>
<html lang="en">
<head>
? <meta charset="UTF-8">
? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? <title>Document</title>
</head>
<body>
? <canvas id="canvas" style="border:1px solid #aaa;display:block;margin: 50px auto;">
? ? 當前瀏覽器不支持canvas,請更新瀏覽器或者升級瀏覽器后再試
? </canvas>
? <script>
? ? // x: 小球原始x坐標,y: 小球原始y坐標, r: 小球半徑, vx: x軸速度,vy: y軸的速度 (速度都以向量表示,所以可為負數)
? ? var ball = { x: 512, y: 100, r: 20, vx: -8, vy: 8, color: '#005588' }
? ? window.onload = function () {
? ? ? var canvas = document.getElementById("canvas");
? ? ? // 制定canvas畫布的大小
? ? ? canvas.width = 860;
? ? ? canvas.height = 600;
? ? ? // 判斷瀏覽器是否支持canvas
? ? ? if (canvas.getContext("2d")) {
? ? ? ? // 下面所有調用的函數都是基于context這個上下文環(huán)境來進行的
? ? ? ? var context = canvas.getContext("2d");
? ? ? ? setInterval(() => {
? ? ? ? ? render(context)
? ? ? ? ? update()
? ? ? ? }, 20);
? ? ? } else {
? ? ? ? alert("當前瀏覽器不支持canvas,請更新瀏覽器或者升級瀏覽器后再試");
? ? ? }
? ? };
? ? //十六進制顏色隨機
? ? function color16() {
? ? ? var r = Math.floor(Math.random() * 256);
? ? ? var g = Math.floor(Math.random() * 256);
? ? ? var b = Math.floor(Math.random() * 256);
? ? ? var color = '#' + r.toString(16) + g.toString(16) + b.toString(16);
? ? ? return color;
? ? }
? ? // 小球的坐標的刷新
? ? function update() {
? ? ? ball.x += ball.vx // x軸坐標 vx是x軸的速度,勻速增加
? ? ? ball.y += ball.vy ?// y軸坐標 由于g的原因,速度是勻變速
? ? ??
? ? ? // 觸底的條件
? ? ? if (ball.y >= canvas.height - ball.r) {
? ? ? ? ball.color = color16()
? ? ? ? ball.y = canvas.height - ball.r ? ?// 觸下底
? ? ? ? ball.vy = -ball.vy
? ? ? } else if (ball.x <= ball.r) {
? ? ? ? ball.color = color16()
? ? ? ? ball.x = ball.r // 觸左
? ? ? ? ball.vx = -ball.vx
? ? ? } else if (ball.x >= canvas.width - ball.r) {
? ? ? ? ball.color = color16()
? ? ? ? ball.x = canvas.width - ball.r ?// 觸右
? ? ? ? ball.vx = - ball.vx
? ? ? } else if (ball.y <= ball.r) {
? ? ? ? ball.color = color16()
? ? ? ? ball.y = ball.r ? // 觸上
? ? ? ? ball.vy = -ball.vy
? ? ? }
? ? }
? ? // 繪制圓形小球
? ? function render(cxt) {
? ? ? // 利用clearRect,清空畫布
? ? ? cxt.clearRect(0, 0, cxt.canvas.width, cxt.canvas.height)
? ? ? cxt.fillStyle = ball.color
? ? ? cxt.beginPath()
? ? ? //context.arc(圓心橫坐標, 原型縱坐標, 半徑的長度,繪制的起點, 繪制的終點)
? ? ? cxt.arc(ball.x, ball.y, ball.r, 0, 2 * Math.PI)
? ? ? cxt.closePath()
? ? ? cxt.fill()
? ? }
? </script>
</body>
</html>以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
在JavaScript中查找字符串中最長單詞的三種方法(推薦)
這篇文章主要介紹了在JavaScript中查找字符串中最長單詞的三種方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01

