2013-12-15 199 views
1

jVectormap插件,有沒有辦法用漸變背景填充地圖?jVectormap漸變背景填充

我通過做這個代碼給了一個鏡頭,但它的確認只是實心全黑。

fillColor: { 
     linearGradient: { 
      stops: [ 
       [0, 'rgba(255,255,255,0.5)'], 
       [1, 'rgba(255,255,255,0.0)'], 
      ] 
     } 
}, 
+0

我不認爲這是可能的,不修改jvectormap源。我相信jvectormap識別的屬性是'fill'和'fill-opacity'。 – dhc

回答

0

您可以漸變元素添加到地圖的<defs>元素,然後將fill屬性鏈接到其ID。要添加漸變您可以使用3d.js庫

初始化地圖,並設置填充屬性

$(function() { 
    $('#map').vectorMap({ 
     map: 'world_mill_en', 
     regionStyle: { 
      initial: { 
       fill: 'url(#my-gradient)' 
      }, 
     } 
    }); 
}); 

添加漸變定義與d3.js

$(function() { 
    var defs = d3.select('defs'); 
    var myGradient = defs.append('linearGradient') 
     .attr('id', 'my-gradient') 
     .attr('x1', '0%') 
     .attr('y1', '100%') 
     .attr('x2', '100%') 
     .attr('y2', '0%'); 
    myGradient.append('stop') 
     .attr('offset', '0%') 
     .attr('style', 'stop-color:rgb(255,255,255)') 
     .attr('stop-opacity', 1); 
    myGradient.append('stop') 
     .attr('offset', '100%') 
     .attr('style', 'stop-color:rgb(51,51,51)') 
     .attr('stop-opacity', 1); 
}); 
0

,如果你不想使用d3.js你可以使用我創建的這個功能來設置梯度爲svg

function createGradient(svg, id, stops) { 
    var svgNS = svg.namespaceURI; 
    var grad = document.createElementNS(svgNS, 'linearGradient'); 
    grad.setAttribute('gradientUnits', 'userSpaceOnUse'); 
    grad.setAttribute("x1", "0%"); 
    grad.setAttribute("x2", "0%"); 
    grad.setAttribute("y1", "0%"); 
    grad.setAttribute("y2", "100%"); 
    grad.setAttribute('id', id); 

    for (var i = 0; i < stops.length; i++) { 
     var attrs = stops[i]; 
     var stop = document.createElementNS(svgNS, 'stop'); 
     for (var attr in attrs) { 
      if (attrs.hasOwnProperty(attr)) stop.setAttribute(attr, attrs[attr]); 
     } 
     grad.appendChild(stop); 
    } 

    var defs = svg.querySelector('defs') || svg.insertBefore(document.createElementNS(svgNS, 'defs'), svg.firstChild); 
    return defs.appendChild(grad); 
}; 


function initializeMapColors() { 
    createGradient($('svg')[0], 'MyGradient', [{ 
    offset: '0%', 
    'stop-color': '#D96B6C' 
    }, { 
    offset: '100%', 
    'stop-color': '#E35980' 
    }]); 

    $('path').attr('fill', 'url(#MyGradient)'); 
}; 

initializeMapColors();