gpt4 book ai didi

javascript - 图例在javascript中的定位

转载 作者:行者123 更新时间:2023-11-29 23:16:06 24 4
gpt4 key购买 nike

我正在尝试在 js 中定位直方图的图例。我卡住的部分是图例的位置:

enter image description here

我正在尝试将图例放在右侧。

这是代码的快照:

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

this.draw = function(){
var maxValue = 0;
for (var categ in this.options.data){
maxValue = Math.max(maxValue,this.options.data[categ]);
}
var canvasActualHeight = this.canvas.height - this.options.padding * 2;
var canvasActualWidth = this.canvas.width - this.options.padding * 2;

//drawing the grid lines
var gridValue = 0;
while (gridValue <= maxValue){
var gridY = canvasActualHeight * (1 - gridValue/maxValue) + this.options.padding;
drawLine(
this.ctx,
0,
gridY,
this.canvas.width,
gridY,
this.options.gridColor
);

//writing grid markers
this.ctx.save();
this.ctx.fillStyle = this.options.gridColor;
this.ctx.font = "bold 10px Arial";
this.ctx.fillText(gridValue, 10,gridY - 2);
this.ctx.restore();

gridValue+=this.options.gridScale;
}

//drawing the bars
var barIndex = 0;
var numberOfBars = Object.keys(this.options.data).length;
var barSize = (canvasActualWidth)/numberOfBars;

for (categ in this.options.data){
var val = this.options.data[categ];
var barHeight = Math.round( canvasActualHeight * val/maxValue) ;
drawBar(
this.ctx,
this.options.padding + barIndex * barSize,
this.canvas.height - barHeight - this.options.padding,
barSize,
barHeight,
this.colors[barIndex%this.colors.length]
);


//drawing series name
this.ctx.save();
this.ctx.textBaseline="bottom";
this.ctx.textAlign="center";
this.ctx.fillStyle = "#000000";
this.ctx.font = "bold 14px Arial";
this.ctx.fillText(this.options.seriesName, this.canvas.width/2,this.canvas.height);
this.ctx.restore();
barIndex++;
}

//draw legend
barIndex = 0;
var legend = document.querySelector("legend[for='myCanvasBAR']");
var ul = document.createElement("ul");
legend.append(ul);
for (categ in this.options.data){
var li = document.createElement("li");
li.style.listStyle = "none";
li.style.borderLeft = "20px solid "+this.colors[barIndex%this.colors.length];
li.style.padding = "5px";
li.textContent = categ;
ul.append(li);
barIndex++;
}

}
}

var MyBARs = {
"10%": 10,
"20%": 31,
"30%": 70,
"40%": 50,
"50%": 30,
"60%": 20,
"70%": 14,
"80%": 17,
"90%": 155,
"100%": 100
};

由于我是 js 的新手,所以我只是不明白右侧甚至条形图下方的图例。

最佳答案

我相信这样的事情应该可行:

legend.style.position = "absolute";
legend.style.top = "0px";
legend.style.right = "0px";

相应地调整像素。

关于javascript - 图例在javascript中的定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52729517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com