pedram pedram - 5 months ago 30
Javascript Question

Openlayers 3 - Create custom symbol like openlayers 2 -> OpenLayers.Renderer.symbol.anySymbol

In the

Openlayers v2
I could add symbols like:

OpenLayers.Renderer.symbol.pointToIcon = [100, 70, 20, 50, 42, 70, 20, 90];


How can I do it with Openlayers 3 ?

In the
openlayers 3
I can use this feature:

var starSymbol = new ol.style.RegularShape({
points: 4,
opacity: .5,
radius: 10,
radius2: 10 * .5,
angle: 130,
fill: new ol.style.Fill({
color: "blue"
}),
stroke: new ol.style.Stroke({
color: "red",
width: 1
})
});


I can make the other figures,but I can't make the following figure.

enter image description here

In addition, I don't use 'Icon' like:

new ol.style.Style({
image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.75,
src: 'data/icon.png'
}))
})


Because the color of icon is fixed and I can't use my needed colors.

I really appreciate it if you help me.

Answer Source

You can draw your custom symbol to a canvas, and use that as icon image. OpenLayers provides a very nice API for this. You may want to take a look at the example: http://openlayers.org/en/v3.12.1/examples/earthquake-custom-symbol.html.

For your specific symbol, the code could look like this:

var canvas = document.createElement('canvas');
var render = ol.render.toContext(canvas.getContext('2d'),
    {size: [50, 45]});
render.setFillStrokeStyle(
    new ol.style.Fill({ color: 'red' }),
    new ol.style.Stroke({ color: 'black' }));
render.drawPolygonGeometry(new ol.geom.Polygon(
    [[[50, 35], [10, 25], [21,35], [10, 45], [50, 35]]]));
var style = new ol.style.Style({
  image: new ol.style.Icon({
    img: canvas,
    imgSize: [canvas.width, canvas.height],
  })
});