当我放大并缩小地图时,我试图准确调整文本的字体。每次。这是我能做的最好的事情。不确定如何准确地做到这一点,因为这是1.非常慢和迟滞2.当我放大文本比地图大。
我试图理解这个是如何工作的
但我不确定比例或字体大小的设置位置。
d3.json("../../json/mapped.json", function(json){
var mapped = topojson.feature(json, json.objects.mapped);
// projection
var center = d3.geo.centroid(mapped);
var scale = 100;
var offset = [width/2, height/2];
projection.scale(scale).center(center).translate(offset);
path.projection(projection);
var bounds = d3.geo.bounds(northluzon);
var hscale = scale*width / (bounds[1][0] - bounds[0][0]);
var vscale = scale*height / (bounds[1][1] - bounds[0][1]);
var scale = (hscale < vscale ) ? hscale : vscale;
var offset = [width - (bounds[0][0] + bounds[1][0])/2,
height - (bounds[0][1] + bounds[1][1])/2];
projection = d3.geo.mercator()
.center(center)
.scale(scale)
.translate(offset);
path = path.projection(projection);
svg.append("rect").attr('width', width).attr('height', height)
.style('stroke', 'black').style('fill', 'none');
g.selectAll("path")
.data(mapped.features)
.enter()
.append("path")
.attr("d", path)
.attr('id', function(d){
return d.properties._id; }
)
.on('mouseover', function(d){
$('#toolTip').fadeOut(100, function(){
$('#toolTipBody').html('tool tip test');
var popLeft = mousePos[0] + 20;
var popTop = mousePos[1] + 70;
$('#toolTip').css({ 'left': popLeft, 'top': popTop});
$('#toolTip').fadeIn(100);
});
d3.select(this).attr('fill', 'red');
})
.style("fill", "steelblue")
.style("stroke-width", "1")
.style("stroke", "black");
svg.call(d3.behavior.zoom()
.scale(projection.scale())
.translate(projection.translate())
.on('zoom', redraw));
gLabels = g.append('g').attr('id', 'labels')
.selectAll('text')
.data(mapped.features)
.enter()
.append('text')
.attr('x', function(d){ return path.centroid(d)[0]; })
.attr('y', function (d) { return path.centroid(d)[1]; })
.style('font-size', function(d){
return '6px';
})
.text(function(d){ return d.properties._id; });
redraw();
});
function redraw(){
if(d3.event){
projection
.translate(d3.event.translate)
.scale(d3.event.scale);
}
svg.selectAll('path').attr('d', path);
gLabels
.attr("x", function (d) { return path.centroid(d)[0]; })
.attr("y", function (d) { return path.centroid(d)[1]; })
.style('font-size', function(d){
var currSize = parseInt(getElementStyleValue(this.attributes, 'font-size'));
var newSize = Math.min(2 * currSize, (2 * currSize - 8)/ this.getComputedTextLength() * 12 ) + 'px';
return newSize;
});
}