1. 程式人生 > >在地圖上使用canvas繪製面板

在地圖上使用canvas繪製面板

html頁面中引入:

<div id="result">
	<canvas id="canvas" width="300" height="150"></canvas>
</div>

css樣式:

#canvas {
    filter:alpha(opacity=60);/*IE*/
    opacity:0.6;/*Mozilla*/
    /*background: #fff;*/
    padding: 7px;
    position: absolute;
    z-index: 100;
    bottom: 5px;
    right: auto;
    top: auto;
    left: 5px;/*old:225*/
}

js方法:

function showOriginPanel(splitList){
    var canvas = document.getElementById('canvas');
    if(1 == splitList.length && splitList[0].color == "#d9d9d9" ){
        canvas.style.display = 'none';
    }
    if(5<splitList.length){
        canvas.width = 300;//130
        canvas.height = 35;//130+(splitList.length-5)*26
        canvas.style.width = '300px';//130px
        canvas.style.height = '35px';//'130px'+(splitList.length-5)*26
    }else{
        canvas.width = splitList.length * 100;
        canvas.height = 35;
        canvas.style.width = (splitList.length * 100) + 'px';
        canvas.style.height = '35px';
    }

    canvas.style.display = 'block';
    canvas.style.background = '#115FB1';//#fff
    canvas.style.boxShadow = 'rgba(0,0,0,0.2) 0 0 4px 2px';
    canvas.style.border = '1px solid #0C345C';
    canvas.style.borderRadius = '4px';
    // 新增DOM元素到地圖中
    //map.getContainer().appendChild(canvas);

    var ctx=canvas.getContext("2d");
    ctx.fillStyle="#0000ff";
    //ctx.globalAlpha = 0.8;
    //ctx.fillRect(20,20,80,20);
    for (var i = 0; i < splitList.length; i++) {
        ctx.beginPath();
        //ctx.arc(15, i * 25 + 15, 5, 0, Math.PI * 2, false);
        ctx.arc(15 + i * 100, 15, 5, 0, Math.PI * 2, false);
        var text = '';
        text = splitList[i].alarmName;
        ctx.closePath();
        ctx.fillStyle = splitList[i].color;
        ctx.fill();
        ctx.font='12px 微軟雅黑';
        ctx.fillStyle = '#fff';//#d2691e
        //ctx.fillText(text, 25, i * 25 + 20);
        ctx.fillText(text, 25 + i*100, 20);
    };

}

呼叫:

var panelColorList = new Array();
panelColorList.push({color: "#700000", alarmName: "小偷"});
panelColorList.push({color: "#F0F8FF", alarmName: "強盜"});
showOriginPanel(panelColorList);