html5

关注公众号 jb51net

关闭
网页制作 > html5 >

HTML5 Canvas 绘制股市走势图

刘煎蛋

前言

分时大盘回顾功能是一种用于分析股票行情的工具,在多个股票软件中都有应用。通过这个功能,用户可以查看一段时间内大盘的走势图以及涨跌停数量对比,并回放历史数据。在这个过程中,用户可以暂停、播放、拖动时间轴等操作,以便在复盘时更好地分析市场走势。

效果

实现思路

启动、暂停

play() {
    const { node } = this;
    if (!this.data.paused) return false;
    if (this.currentIndex >= this.data.list.length - 1) {
        this.triggerEvent('endEvent');
        clearTimeout(this.time);
        return false;
    }
    this.ctx.clearRect(0, 0, node.width, node.height);
    this.currentIndex += 1;
    this.startDraw();
    this.time = setTimeout(this.play.bind(this), 16.667);
},

绘制矩形

矩形文字居中处理方法

首先,使用ctx.measureText(text)方法获取文字的实际宽度,然后根据Canvas的大小和文字的宽度计算出文字左上角在Canvas中的坐标。具体来说,将Canvas的宽度除以2,减去文字宽度的一半,即可得到文字左上角的横坐标;将Canvas的高度除以2,加上文字高度的一半,即可得到文字左上角的纵坐标。

var text = "Hello world!";
var width = ctx.measureText(text).width;
var height = 20; // 假设文字高度为20px
ctx.font = `${height}px Arial`;
var x = canvas.width / 2 - width / 2;
var y = canvas.height / 2 + height / 2;
ctx.fillText(text, x, y);

矩形缓入效果

要实现Canvas中矩形的透明度从0到1的出现过程,可以使用rgba的最后一个值来控制矩形的透明度,并在每一帧更新矩形的颜色和位置来实现矩形的淡入效果。具体实现步骤如下:

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");

var x = canvas.width / 2 - 50; // 矩形位于屏幕中央
var y = canvas.height / 2 - 50;
var width = 100;
var height = 100;
var speed = 2; // 矩形移动速度
var opacity = 0; // 矩形初始透明度为0

function drawRect() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清空画布
    ctx.fillStyle = `rgba(254,82,105, ${opacity})`;
    ctx.fillRect(x, y, width, height); // 绘制矩形

    opacity += 0.01; // 每帧透明度增加0.01,从而使矩形缓慢淡入屏幕
    if (opacity >= 1) {
        cancelAnimationFrame(animation); // 矩形完全进入Canvas后停止动画
    } else {
        requestAnimationFrame(drawRect); // 继续更新状态
    }
}

var animation = requestAnimationFrame(drawRect); // 开始动画循环

时间轴拖动

在拖动圆点时最主要的就是计算当前拖到了哪个时间点,将计算结果赋值给currentIndex画布再重新绘制,从而实现拖动回放的效果。

this.throttle(() => {
    const { ctx2, ctx, canvas2, minTime, node } = this;
    const x = e.touches[0].x;
    this.currentIndex = Math.floor(Math.max(minTime, Math.min(240, x / canvas2.width * (240 - minTime))));
    ctx.clearRect(0, 0, node.width, node.height);
    ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
    this.startDraw()
}, 16.667)

currentIndex计算说明

总结

到此这篇关于HTML5 Canvas 绘制股市走势图的文章就介绍到这了,更多相关HTML5 Canvas股市走势图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章,希望大家以后多多支持脚本之家!