CocosCreator Graphics实现心电图效果

这篇博客介绍了如何利用CocosCreator的Graphics组件创建心电图效果。作者提供了关键代码示例,包括数据保留、渲染和更新的逻辑,并在`update`函数中模拟了数据变化。心电图的宽度、高度、线宽和颜色都可以根据需求调整。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

CocosCreator Graphics实现心电图效果

前言

遇到一个要实时显示心电图的项目,用Graphics会比较方便,记录下来。

效果

效果

源码

实际使用把#region删掉。
心电图宽度高度由挂载组件的Node决定。
线的粗细颜色在Graphics组件内调节。
需要自己将值映射到0-100的区间内再调用addPoint(YourNumber)

const {ccclass, property} = cc._decorator;

/**
 * 心电图
 * 需要自己将值映射到0-100的区间内再传入
 * 数据个数为双数
 *
 * @export
 * @class Electrocardiogram
 * @extends {cc.Component}
 */
@ccclass
export default class Electrocardiogram extends cc.Component {

    /**
     * 渲染组件
     *
     * @type {cc.Graphics}
     * @memberof Electrocardiogram
     */
    @property(cc.Graphics)
    Graphic: cc.Graphics = null;

    /**
     * 保留多少个数据
     *
     * @type {number}
     * @memberof Electrocardiogram
     */
    @property(Number)
    numCount: number = 10;

    /**
     * 保留的数据
     *
     * @type {number[]}
     * @memberof Electrocardiogram
     */
    yArray:number[] = [];
    scaleX:number  = 0;
    scaleY:number  = 0;

    /**
     * 中间值
     *
     * @type {number}
     * @memberof Electrocardiogram
     */
    hafCount:number = 0;
    // LIFE-CYCLE CALLBACKS:
    // onLoad () {}

    start()
    {
        this.scaleX = this.node.width/this.numCount;
        this.scaleY = this.node.height*0.01;
        this.hafCount = this.numCount/2;
    }

    addPoint(y:number)
    {
        //如果大于则移除
        if(this.yArray.length > this.numCount)
        {
            this.yArray.shift();
        }
      
        this.yArray.push(y);

        //重新绘制
        this.Graphic.clear();
        if(this.yArray.length<1)
        {
            return;
        }

        const value0 =  this.yArray[0];
        const y0 = (value0-50)*this.scaleY;
        this.Graphic.moveTo(((this.yArray.length-1)- this.hafCount)*this.scaleX,y0);
        for (let index = 0; index <this.yArray.length ; index++) {
            const element =  this.yArray[index];
            let x = (((this.yArray.length-1)- this.hafCount)-index)*this.scaleX;
            let y = (element-50)*this.scaleY;
            this.Graphic.lineTo(x,y);
            this.Graphic.stroke();
        }
    }

    //#region 测试
    timer=0;
    update (dt) {
        this.timer+=dt;
        if (this.timer>0.2) {
            this.timer=0;
            this.addPoint(Math.random()*100);
        }
    }
    //#endregion
}

参数设置

使用一张纯色背景(Background),配合上层的Graphics实现最终效果。
参数设置

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值