2

I can't find any simple way to clone an ol3 style. There is no clone() method and creating a style from a style (new ol.style.Style(style)) doesn't do it. JSON.stringify doesn't produce anything usable, either.

Is there any ol3 code I might be overlooking for cloning styles?

1

Adapted from ol-debug.js:

var typeOf = function(obj){
    return ({}).toString.call(obj)
        .match(/\s([a-zA-Z]+)/)[1].toLowerCase();
};
function cloneObject(obj){
    var type = typeOf(obj);
    if (type == 'object' || type == 'array') {
        if (obj.clone) {
            return obj.clone();
        }
        var clone = type == 'array' ? [] : {};
        for (var key in obj) {
            clone[key] = cloneObject(obj[key]);
        }
        return clone;
    }
    return obj;
}
var circle = new ol.style.Style({
    image: new ol.style.Circle({
        radius: 5,
        fill: null,
        stroke: new ol.style.Stroke({
            color: [0,0,0,.9],
            width: 3
        })
    })
});
var cloned = cloneObject(circle);
console.info(cloned.getImage().getOpacity());
  • This would be fine for a JSON object and would probably work but it is unsafe; it's copying methods and internal state; unfortunately, there is also no clone on fill, stroke, etc. – ca0v Aug 18 '15 at 18:27
  • 1
    Actually it does clone fill and stroke - fiddle. – Jonatas Walker Aug 18 '15 at 19:40
  • It does it but they don't have a clone on them. Your code would probably work but it's not the "simple way" I was looking for. – ca0v Aug 19 '15 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.