| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>速度变化图</title>
- </head>
- <body>
- <canvas style="position: fixed; top: 0px; left: 0px;"></canvas>
- </body>
- <script>
- var canvas = document.querySelector("canvas")
- var ctx = canvas.getContext("2d");
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- canvas.width = innerWidth;
- canvas.height = innerHeight;
- ctx.fillStyle = "rgb(0,0,0)";
- ctx.fillRect(0,0,canvas.width,canvas.height);
- ctx.lineWidth = 1;
- ctx.strokeStyle = "rgb(255,0,0)";
- ctx.beginPath();
- ctx.moveTo(0, innerHeight - 100);
- ctx.lineTo(innerWidth, innerHeight - 100);
- ctx.moveTo(100, 0);
- ctx.lineTo(100, innerHeight);
- ctx.closePath();
- ctx.stroke();
- ctx.fillStyle = "rgb(255,0,0)";
- ctx.textBaseline = "top";
- ctx.textAlign = "center";
- ctx.font = "40px Arial"
- ctx.fillText("v", 130, 100);
- ctx.fillText("t", 350, innerHeight - 85);
- //积分求变加速直线运动位移
- function seekDistance(acc, time, draw) {
- let dt = 0.001;
- let v0 = 0;
- let sum = 0;
- for (let t = dt; t <= time; t += dt) {
- let dv = 1 / 2 * acc * dt;
- sum += v0 * dt + dv * dt;
- v0 += dv;
- //提高加速度
- acc += dt * acc * 3;
- if (draw) {
- ctx.moveTo(100 + (t / 5 * 1000) << 0, innerHeight - 100);
- ctx.lineTo (100 + (t / 5 * 1000) << 0, innerHeight - 100 - v0 / 5);
- ctx.stroke();
- }
- }
- return sum;
- }
-
- //寻找最佳的加速度
- function findBestAcc(distance, time) {
- //为了后面减少运算量,先粗略找到比较接近的区间
- let accRangeMin = null;
- let accRangeMax = null;
- for (let acc = 0; acc < 10000; acc += 10) {
- let result = seekDistance(acc, time);
- let dx = result - distance;
- if (dx < 0) {
- accRangeMin = acc;
- } else if (dx > 0) {
- accRangeMax = acc;
- break;
- } else {
- return acc;
- }
- }
- if (accRangeMin == null || accRangeMax == null) {
- throw "寻找区间失败"
- }
- //在指定区间寻找最佳结果
- for (let acc = accRangeMin; acc <= accRangeMax; acc += 0.001) {
- let result = seekDistance(acc, time);
- let dx = result - distance;
- if (Math.abs(dx) < 0.1) {
- return acc;
- }
- }
- throw "找不到最佳加速度";
- }
- let acc = findBestAcc(640, 1);
- seekDistance(acc, 1, true);
- </script>
- </html>
|