gpt4 book ai didi

javascript - 在 Google 折线图中的线注释之上添加图像

转载 作者:行者123 更新时间:2023-11-29 23:54:37 26 4
gpt4 key购买 nike

这是创建折线图的代码。我正在尝试在线注释的顶部添加图像。这是关于 jsfiddle 的演示.这是代码:

google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);

function drawBasic() {

var data = new google.visualization.DataTable();

data.addColumn('number', 'X');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn('number', 'Dogs');
data.addColumn('number', 'Cats');

data.addRows([
[0,null, 0, 1], [1,'', 10,3], [2,null, 23,6], [3,null, 17,7], [4,null, 18,4], [5,null, 9,7]
]);

var options = {
curveType : 'function',
hAxis: {
title: 'Time',
gridlines: {
color: 'transparent'
}
},
vAxis: {
title: 'Popularity',
gridlines: {
color: 'transparent'
}
},
annotations: {
style: 'line',
position: 'top'
}
};

var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

chart.draw(data, options);
}

我真的不知道该怎么做。有人做过吗?

最佳答案

您可以向图表添加元素,一旦'ready'事件触发
(或 'animationfinish' 使用动画时)

首先,需要找到注释,这将是<rect>元素

类似于轴线,它们会有一个'width'1

但他们会有不同的'fill'属性
(记住这一点,如果在 annotations 选项上设置了更多的样式设置)

以下工作代码段找到注释行并将图像添加到顶部

google.charts.load('current', {
callback: drawBasic,
packages: ['corechart']
});

function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn('number', 'Dogs');
data.addColumn('number', 'Cats');
data.addRows([
[0, null, 0, 1],
[1, '', 10, 3],
[2, null, 23, 6],
[3, null, 17, 7],
[4, null, 18, 4],
[5, null, 9, 7]
]);

var options = {
annotations: {
position: 'top',
style: 'line'
},
hAxis: {
gridlines: {
color: 'transparent'
},
title: 'Time'
},
vAxis: {
gridlines: {
color: 'transparent'
},
title: 'Popularity'
},
};

var container = document.getElementById('chart_div');
var chart = new google.visualization.LineChart(container);

google.visualization.events.addListener(chart, 'ready', function () {
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function(rect) {
if ((rect.getAttribute('width') === '1') && (rect.getAttribute('fill') === '#999999')) {
var xPos = parseFloat(rect.getAttribute('x'));
var yPos = parseFloat(rect.getAttribute('y'));

var whiteHat = container.appendChild(document.createElement('img'));
whiteHat.src = 'http://findicons.com/files/icons/512/star_wars/16/clone_old.png';
whiteHat.className = 'whiteHat';

// 16x16 (image size in this example)
whiteHat.style.top = (yPos - 8) + 'px';
whiteHat.style.left = (xPos) + 'px';
}
});
});

chart.draw(data, options);
}
.whiteHat {
border: none;
position: absolute;
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

关于javascript - 在 Google 折线图中的线注释之上添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41978687/

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