Openlayer3用canvas绘制圆角矩形标注

一、最终结果图下图所示

圆角矩形效果图

二、用canvas绘制圆角矩形
代码如下:

var canvas=document.getElementsByTagName("canvas")[0];
var context=canvas.getContext("2d");
context.strokeStyle="rgba(0,255,0,0.5)"//矩形边框颜色
context.beginPath();//开始绘制
context.lineTo(200,100);//移动到某个点
context.lineTo(300,100);
context.lineTo(300,200);
context.lineTo(200,200);
context.closePath();
context.stroke();
context.strokeStyle="rgba(255,255,0,1)"
context.beginPath();
context.moveTo(218,100);
context.arcTo(300,100,300,200,18);
context.arcTo(300,200,200,200,18);
context.arcTo(200,200,200,100,18);
context.arcTo(200,100,300,100,18);
context.closePath();
context.stroke();

效果如下:

黄色为圆角矩形,绿色为原始矩形

总结:绘制圆角矩形的arcTo方法参数为x1坐标y1坐标,x2坐标y2坐标;第五个参数为圆角半径。圆角的绘制其实是
三、canvas和Ol3结合绘制圆角矩形标注

           var layer = new ol.layer.Tile({
                   source: new ol.source.XYZ({
                   url: 'http://www.google.cn/maps/vt?pb=!1m5!1m4!1i{z}!2i{x}!3i{y}!4i256!2m3!1e0!2sm!3i342009817!3m9!2szh-CN!3sCN!5e18!12m1!1e47!12m3!1e37!2m1!1ssmartmaps!4e0&token=32965'
                     })
                });
   var vector=new ol.layer.Vector({
        source:new ol.source.Vector()
           });

    var view = new ol.View({
        center: new ol.proj.fromLonLat([120, 30]),
        zoom: 7
    });
    var map = new ol.Map({
        layers: [layer,vector],
        view: view,
        target: "map",
        logo: false
    });

    var feature=new ol.Feature({
        geometry:new ol.geom.Point(new ol.proj.fromLonLat([120,30]))
        });
      //绘制圆角矩形
   var roundRect = function (x, y, w, h, r) {
        if (w 

四、根据不同长度的中文,创建圆角矩形

  function createRectStyle(text) {
        var canvas, context, length;
        canvas = document.createElement("canvas");
        context = canvas.getContext("2d");
        length = text.length;
        canvas.width = length * 13;
        canvas.height = 20;
        var x = 0, y = 0, w = canvas.width, h = canvas.height, r = 8;
        if (w 

使用方法:

           var feature2 = new ol.Feature({
                 geometry: new ol.geom.Point(new ol.proj.fromLonLat([120.1, 30.1]))
             });
         feature.setStyle(createRectStyle("少的"));
使用如上方法自动创建不同长度的圆角矩形

You may also like...