首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Javascript画布绘制顺序

Javascript画布绘制顺序
EN

Stack Overflow用户
提问于 2018-07-03 04:48:51
回答 1查看 1.2K关注 0票数 0

我正在用javascript循环中的一些序列值绘制条形图。即使绘制序列值的代码位于绘制条形图的代码的下方,在循环的下一次迭代中,刚刚绘制的文本也会被覆盖。

当出现警告框时,您可以在下面的代码中看到此效果。

为什么在画布的另一部分上的绘制操作会覆盖之前在完全不同的位置绘制的内容?

更新:有人很有帮助地指出,使用fillRect()隐藏了这个问题,但我的问题是:为什么会发生这种情况?

代码语言:javascript
复制
var exampleData = {
  "Series 1": 10,
  "Series 2": 14,
  "Series 3": 2,
  "Series 4": 12
};

var BarChart = function(options) {
  this.options = options;
  this.canvas = options.canvas;
  this.ctx = this.canvas.getContext("2d");
  this.colors = options.colors;

  this.plot = function() {
    var maxValue = 0;
    for (var categ in this.options.data) {
      maxValue = Math.max(maxValue, this.options.data[categ]);
    }

    var noBars = Object.keys(this.options.data).length;
    var barWidth = (this.canvas.height) / noBars;
    var barIdx = 0;

    for (categ in this.options.data) {
      var barLength = Math.round(this.canvas.width * this.options.data[categ] / maxValue);
      this.ctx.save();
      alert("plotting series line " + categ);
      this.ctx.fillStyle = this.colors[barIdx % this.colors.length];
      this.ctx.rect(30, barIdx * barWidth, barLength, barWidth);
      this.ctx.fill();
      alert("plotting series value " + categ);
      this.ctx.fillStyle = "#000000";
      this.ctx.font = "24px Georgia";
      this.ctx.textBaseline = "middle";
      this.ctx.fillText(this.options.data[categ], 25, barIdx * barWidth + barWidth / 2); //will be covered in the loop's next iteration. Why?
      this.ctx.restore();
      barIdx++;
    }
  }
}

function init() {
  var myCanvas = document.getElementById("myCanvas");
  myCanvas.width = 800;
  myCanvas.height = 300;
  var ctx = myCanvas.getContext("2d");
  var myBarChart = new BarChart({
    canvas: myCanvas,
    seriesName: "Example Series",
    padding: 40,
    data: exampleData,
    colors: ["#D1E3F3", "#D1E3F3", "#D1E3F3", "#D1E3F3"]
  });
  myBarChart.plot();
}
document.addEventListener("DOMContentLoaded", init, false);
代码语言:javascript
复制
<canvas id="myCanvas"></canvas>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-03 05:02:59

更改:

代码语言:javascript
复制
this.ctx.rect(30, barIdx * barWidth, barLength, barWidth);
this.ctx.fill();

改用fillRect()可以解决这个问题:

代码语言:javascript
复制
this.ctx.fillRect(30, barIdx * barWidth, barLength, barWidth);

Working example here (与原始示例here相比)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51143526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档