繁体   English   中英

JavaScript画布绘制顺序

[英]Javascript Canvas Draw Order

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

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

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

更新:有人有用地指出使用fillRect()隐藏了此问题,但是我的问题是:为什么它首先发生?

 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); 
 <canvas id="myCanvas"></canvas> 

变更中:

this.ctx.rect(30, barIdx * barWidth, barLength, barWidth);
this.ctx.fill();

改为使用fillRect()解决此问题:

this.ctx.fillRect(30, barIdx * barWidth, barLength, barWidth);

工作示例这里 (比原来的例子在这里

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM