我使用d3.js渲染世界地圖的svg(使用https://github.com/johan/world.geo.json/blob/master/countries.geo.json作爲特徵)。我將渲染邏輯封裝在Backbone View中。當我渲染視圖並將其附加到DOM時,雖然在查看生成的HTML時正確生成了SVG標記,但瀏覽器中沒有顯示任何內容。當沒有封裝在Backbone.View中時,這呈現很好。下面是使用Backbone.view我的代碼:SVG沒有正確渲染作爲骨幹視圖
/**
* SVG Map view
*/
var MapView = Backbone.View.extend({
tagName: 'svg',
translationOffset: [480, 500],
zoomLevel: 1000,
/**
* Sets up the map projector and svg path generator
*/
initialize: function() {
this.projector = d3.geo.mercator();
this.path = d3.geo.path().projection(this.projector);
this.projector.translate(this.translationOffset);
this.projector.scale(this.zoomLevel);
},
/**
* Renders the map using the supplied features collection
*/
render: function() {
d3.select(this.el)
.selectAll('path')
.data(this.options.featureCollection.features)
.enter().append('path')
.attr('d', this.path);
},
/**
* Updates the zoom level
*/
zoom: function(level) {
this.projector.scale(this.zoomLevel = level);
},
/**
* Updates the translation offset
*/
pan: function(x, y) {
this.projector.translate([
this.translationOffset[0] += x,
this.translationOffset[1] += y
]);
},
/**
* Refreshes the map
*/
refresh: function() {
d3.select(this.el)
.selectAll('path')
.attr('d', this.path);
}
});
var map = new MapView({featureCollection: countryFeatureCollection});
map.$el.appendTo('body');
map.render();
下面是工作的代碼,而無需使用Backbone.View
var projector = d3.geo.mercator(),
path = d3.geo.path().projection(projector),
countries = d3.select('body').append('svg'),
zoomLevel = 1000;
coords = [480, 500];
projector.translate(coords);
projector.scale(zoomLevel);
countries.selectAll('path')
.data(countryFeatureCollection.features)
.enter().append('path')
.attr('d', path);
我還附上生成的SVG標記的屏幕截圖。任何想法在這裏可能會出錯?
編輯 - 下面是重寫的化妝方法,它結束瞭解決這個,每個請求:
/**
* Custom make method needed as backbone does not support creation of
* namespaced HTML elements.
*/
make: function(tagName, attributes, content) {
var el = document.createElementNS('http://www.w3.org/2000/svg', tagName);
if (attributes) $(el).attr(attributes);
if (content) $(el).html(content);
return el;
}
謝謝!在我看來,我忽略了'make',並用'http://www.w3.org/2000/svg'而不是createElement來使用createElementNS,這看起來有訣竅。欣賞指導。 – 2012-03-11 06:43:22
@rr:你可以在某處發佈make方法嗎? – 2012-07-23 13:58:33
@PierreSpring:完成,不確定這與更新版本的骨幹有多相關,我一直沒有跟上。 – 2012-07-28 06:08:33