canvas画布绘制钟摆

位置: 首页 > 代码集锦
[发布: 2024.5.19  作者: 马黑  阅读: 69]

效果:

代码:

<canvas id="pdcanv" width="600" height="240"></canvas>   <script>   var pdCtx = pdcanv.getContext('2d'); //画笔   //创建钟摆的类 class Pendulum {
    /* 构造函数     ctx : 画笔     line : 配置对象,格式为 { x: x, y: y, len: len, vx: vx, speed: speed }     */
    constructor(ctx,line) {         this.ctx = ctx;         this.line = line;     };       //draw方法 : 绘制静态钟摆     draw() {
        /* x1、y1是线段底端XY坐标也是摆锤圆心坐标         x1 等于顶端 x + 摆幅(即vx)         y1 等于,根据长度 len 和 x1 用勾股定理计算出来         */
        var x1 = this.line.x + this.line.vx;         var y1 = Math.sqrt(this.line.len ** 2 - (x1 - this.line.x) ** 2);         //画线         this.ctx.beginPath();         this.ctx.fillStyle = this.ctx.strokeStyle = 'plum';         this.ctx.lineWidth = 2;         this.ctx.moveTo(this.line.x, this.line.y);         this.ctx.lineTo(x1, y1);         this.ctx.stroke();         //画圆         this.ctx.beginPath();         this.ctx.arc(x1, y1, 20, 0, 2*Math.PI);         this.ctx.fill();     };     //update 方法 : 改变摆幅 vx 并调用 draw 静态绘制方法     update() {         this.draw();         this.line.vx += this.line.speed; //改变摆幅         //水平方向摆动幅度不超过 ±30         if (Math.abs(this.line.vx) >= 30) this.line.speed = -this.line.speed;     }; };   //配置钟摆 : 顶端XY坐标、长度、摆幅、速度 var option = { x: 300, y: 10, len: 200, vx: 0, speed: 1 }; //创建钟摆类实例(参数两个 : 画笔、配置) var pd = new Pendulum(pdCtx, option);   //渲染函数 var render = () => {     pdCtx.clearRect(0, 0, pdcanv.width, pdcanv.height);     pd.update(); //调用类的 update 方法     requestAnimationFrame(render); };   render(); //启动渲染   </script>

前一篇: JS函数式编程中的纯函数
下一篇: 叶子和七星瓢虫

发表评论:

  
 

评论列表 [2条]

#2 | 知名不具 于 2024-5-20 23:18 发布: 永动钟摆。

#1 | 悄然 于 2024-5-19 15:34 发布: 看上去十分漂亮的小钟摆。。这个解说很详细~~一句一句的教的。。

Copyright © 2023 All Right Reserved 马黑PHP文章管理整站系统v1.8
联系我们: gxblk@163.com