我正在尝试将plotly模式栏中的全屏选项添加到python Dash应用程序中的所有plotly图表中。我见过很多在 R ou JS 中实现它的自定义代码片段。但是,我在 Dash 应用程序的 python 中找不到类似的东西。有人可以帮助我吗?
我在 JS 中发现了这个技巧,如果它可以嵌入/改编在 python 中用于 dash 应用程序,那将是完美的:https://gist.github.com/p1-rde/2120938f1c7f44c26755cfd83f8562e8。或者 R 中的这个:https://stackoverflow.com/a/69096923/23027270
将以下 javascript 代码保存在 asset 文件夹中:
//Script to show Plotly graph to fullscreen mode
//Dependence on Font Awesome icons
//Author: Dhirendra Kumar
//Created: 26-Nov-2024
function addToModbar() {
const modeBars = document.querySelectorAll(".modebar-container");
for(let i=0; i<modeBars.length; i++) {
const modeBarGroups = modeBars[i].querySelectorAll(".modebar-group");
const modeBarBtns = modeBarGroups[modeBarGroups.length - 1].querySelectorAll(".modebar-btn");
if (modeBarBtns[modeBarBtns.length - 1].getAttribute('data-title') !== 'Fullscreen') {
const aTag = document.createElement('a');
aTag.className = "modebar-btn";
aTag.setAttribute("rel", "tooltip");
aTag.setAttribute("data-title", "Fullscreen");
aTag.setAttribute("style", "color:gray");
aTag.setAttribute("onClick", "fullscreen(this);");
const iTag = document.createElement('i');
iTag.className = 'fa-solid fa-maximize';
aTag.appendChild(iTag);
modeBarGroups[modeBarGroups.length - 1].appendChild(aTag);
}
}
}
function fullscreen(el) {
elem = el.closest('.dash-graph');
if (document.fullscreenElement) {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) { // Firefox
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) { // Chrome, Safari and Opera
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) { // IE/Edge
document.msExitFullscreen();
}
}
else {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) { // Firefox
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) { // Chrome, Safari and Opera
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { // IE/Edge
elem.msRequestFullscreen();
}
}
}
window.fetch = new Proxy(window.fetch, {
apply(fetch, that, args) {
// Forward function call to the original fetch
const result = fetch.apply(that, args);
// Do whatever you want with the resulting Promise
result.then((response) => {
if (args[0] == '/_dash-update-component') {
setTimeout(function() {addToModbar()}, 1000)
}})
return result
}
})