你可以聽window.beforeunload
事件保存plotChart
的變焦/阻力狀態的translate
和scale
值,那麼你可以應用它們在頁面旁邊裝,否則你恢復到默認值。
見下文代碼:
window.onbeforeunload = function (e) {
localStorage.setItem("myScale", myScale);
localStorage.setItem("myTranslateX", myTranslate[0]);
localStorage.setItem("myTranslateY", myTranslate[1]);
};
var margin = {
top: 40,
right: 20,
bottom: 20,
left: 20
},
width = 700 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
window.myScale = 1;
window.myTranslate = [margin.left, margin.top];
if (localStorage.getItem('myScale') !== null) {
myScale = localStorage.getItem('myScale');
}
if (localStorage.getItem('myTranslateX') !== null && localStorage.getItem('myTranslateY') !== null && (localStorage.getItem('myTranslateX') !== 0 && localStorage.getItem('myTranslateY') !== 0)) {
myTranslate = [localStorage.getItem('myTranslateX'), localStorage.getItem('myTranslateY')];
}
var currentDate = new Date();
var minDate = new Date().setMonth((currentDate.getMonth() - 5));
var maxDate = new Date().setMonth((currentDate.getMonth() + 2));
var plotChart = d3.select("body").classed('chart', true).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var myZoom = d3.behavior.zoom().scale(myScale).translate(myTranslate).on("zoom", redraw);
plotChart.call(myZoom)
.append('g');
var plotArea = plotChart.append('g')
.attr('clip-path', 'url(#plotAreaClip)');
plotArea.append('clipPath')
.attr('id', 'plotAreaClip')
.append('rect')
.attr({
width: width,
height: height
});
//x and y axis
var xScale = d3.time.scale()
.domain([minDate, maxDate])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([0, 4])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(5)
.tickSize(height)
.orient("top");
var yAxis = d3.svg.axis()
.scale(yScale)
.ticks(4)
.tickSize(width)
.orient("right");
plotChart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
var gy = plotChart.append("g")
.attr("class", "y axis")
.call(yAxis);
gy.selectAll("text")
.attr("x", 0)
.attr("y", -30)
.attr("dy", -4);
plotChart.append('rect')
.attr("y", 0)
.attr('width', width)
.attr('height', height)
.attr('fill', 'white')
.attr("fill-opacity", 0);
if (myTranslate != [0, 0]) {
plotChart.attr('transform', "translate(" + myTranslate[0] + "," + myTranslate[1] + ")" + " scale(" + myScale + ")");
}
function redraw() {
plotChart.attr("transform",
"translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
myScale = d3.event.scale;
myTranslate = d3.event.translate;
}
演示:http://jsfiddle.net/robschmuecker/wnrmjrc9/