記錄一個(gè)使用canvas 將一張圖片等比縮放,裁剪為一個(gè)圓
1、原始圖片
在這里插入圖片描述
2、繪制后在地圖中呈現(xiàn)的樣式
在這里插入圖片描述
3、設(shè)置樣式的函數(shù)
/**
* 設(shè)置Style
*/
setStyleOnPersonLocation (feature) {
const data = feature.values_
var imgUrl = 'https://person_head_img/avatar.jpg'
// 繪制圓角矩形
let canvas = document.createElement('canvas')
canvas.width = 80
canvas.height = 80
var context = canvas.getContext('2d')
var img = new Image()
img.src = imgUrl // 原始圖片
let w = canvas.width
let h = canvas.height
img.onload = function () {
context.save()
// context.arc(x,y,r,sAngle,eAngle,counterclockwise);
context.arc(40, 40, 20, 0, 2 * Math.PI) // 從畫布上裁剪出這個(gè)圓形
context.clip()
// context.drawImage(img,x,y,width,height);
context.drawImage(img, 20, 20, 40, 40)
}
// 設(shè)置style
return new Style({
image: new Icon({
crossOrigin: 'anonymous',
img: canvas,
imgSize: [w, h]
}),
text: new Text({
text: data.name,
offsetY: -26,
scale: 0.6,
font: '12px Microsoft YaHei',
fill: new Fill({
color: '#808080'
}),
stroke: new Stroke({
color: '#333',
width: 1
})
})
})
},
4、繪制
上面樣式設(shè)置的函數(shù)寫好后,這里就可以開始實(shí)例化vector , 將其添加到地圖中去了
import {Vector as VectorLayer} from 'ol/layer'
import GeoJSON from 'ol/format/GeoJSON'
import VectorSource from 'ol/source/Vector'
import {Point} from 'ol/geom'
import {boundingExtent, getCenter} from 'ol/extent'
import {Style, Icon, Stroke, Text, Fill} from 'ol/style'
methods:{
addlayerToMap(){
const geologyData = {
type: 'FeatureCollection',
crs: {
type: 'Feature'
},
features: [
type: 'Feature',
properties: 'extraData',
id:'userId',
geometry: {
type: 'Point',
coordinates: [104.050629,30.65769]
}
]
}
let nomalSource = new VectorSource({
features: (new GeoJSON()).readFeatures(geologyData)
})
this.shareLocationLayer = new VectorLayer({
source: nomalSource,
// style: _this.setStyleOnPersonLocation // 不能在此設(shè)置style 否則地圖移動(dòng)會(huì)持續(xù)觸發(fā)重繪
})
this.map.addLayer(this.shareLocationLayer)
this.shareLocationLayer.getSource().forEachFeature(featureObj => {
featureObj.setStyle(_this.setStyleOnPersonLocation(featureObj))
})
}
}
記錄記錄便于查閱