【问题标题】:Weird rendering on a HTML canvasHTML 画布上的奇怪渲染
【发布时间】:2021-05-27 02:28:32
【问题描述】:

简介

我设计了一个网站来显示一些统计数据。我想添加圆形图表作为数据的可视化表示(例如温度、速度等)。我的方法是添加一个画布,然后使用画布的上下文绘制一个弧度值的适当角度。如下所示,效果很好。

守则

CircleChart类:

class CircleChart {

    constructor(ID, radius, maxValue, barColor, textSymbol, textColor) {
        this.ID = ID;
        this.radius = radius;
        this.maxValue = maxValue;
        this.barColor = barColor;
        this.textSymbol = textSymbol;
        this.textColor = textColor;
        this.lineWidth = radius/4;
    }

    draw(value) {
        const canvas = document.getElementById("stats-canvas" + this.ID);
        const context = canvas.getContext("2d");

        context.clearRect(0, 0, this.radius*2, this.radius*2);

        context.strokeStyle = this.barColor;
        context.lineWidth = this.lineWidth;

        let angle = ((2 * Math.PI) / this.maxValue) * value;

        context.arc(canvas.width/2, canvas.height/2, this.radius - (this.lineWidth/2), 0, angle);
        context.stroke();

        //context.fillStyle = this.textColor;
        //context.font = (this.radius/2) + 'px san-serif';
        //context.fillText(value + this.textSymbol, this.x - (this.radius/2) - 15, this.y+10);
    }

}

然后我有以下定义:

const temp1Circle = new CircleChart(0, 100, 100, 'red', '°C', 'blue');
const temp2Circle = new CircleChart(1, 100, 100, 'red', '°F', 'blue');
const speedCircle = new CircleChart(2, 100, 100, 'red', 'Mph', 'blue');

这些是从一个函数中提取的,该函数每 3000 毫秒读取一次 GET 请求的响应。该过程概述如下

  1. setTimeout(attemp_request, 3000); -> 每 3000 毫秒发送一次 HTTP GET 请求,并处理响应
  2. 将响应正文拆分为适当的数据(温度、速度等)
  3. 绘制每个圆形图,应用收到的值。

目前我正在生成随机数据并绘制如下所示

function process_response(http_response_text) {
    // process all data into temp1, temp2 and speed
    update_stats(temp1, temp2, speed);
}

function update_stats(temp1, temp2, speed) {
    temp1Circle.draw(getRandomValue(0, 100));
    temp2Circle.draw(getRandomValue(0, 100));
    speedCircle.draw(getRandomValue(0, 100));
}

问题

第一次加载页面时,图表绘制完美。当它们被更新时,会发生以下情况,一段时间后页面看起来像图像 2。

图片 1(第一次加载):

图 2(经过几次更新):

我有什么遗漏吗? 我确保每次绘制都调用 `context.clearRect()' 以确保画布在绘制新弧之前是干净的。有什么建议吗?

【问题讨论】:

    标签: javascript java html web webserver


    【解决方案1】:

    在绘制新路径(进行更新时)之前,您错过了对 beginPath 的调用,因此旧路径仍然存在(并且它是指向新起点的结束链接,这会创建线条)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-25
      • 2012-08-25
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多