从json获取图像位置

时间:2019-02-22 13:25:54

标签: javascript jquery json

我正在从Json文件获取图像路径,并将图像路径分配给JS变量,如下所示:

var maskedImageUrla = "";

    $.getJSON('test.json', function(json) {
        for (let layer of json.layers) {
            if (layer.layers && layer.layers.length > 0) {
                for (let temp of layer.layers) {
                    if (temp.src) maskedImageUrla = temp.src;
                    else if (temp.layers) {
                        for (let tl of temp.layers)
                            if (tl.src) maskedImageUrla = tl.src;
                    }
                }
            }
        }

现在,我需要获取该图像的左[x]和顶部[y] 位置。...

从json文件下面,如何获取 x和y 值并在类 img.css

中显示

Json

{
  "path" : " shape\/",
  "info" : {
    "author" : ""   
  },
  "name" : "shape",
  "layers" : [
    {     
      "height" : 612,
      "layers" : [
        {         
          "name" : "bg_rectangle_1"
        },
        {         
          "x" : 50,
          "layers" : [
            {

              "src" : "http://sitename.com/images/oneheart.png",             
              "name" : "mask_image_1"
            },
            {              
              "name" : "useradd_ellipse1"
            }
          ],   
          "y" : 69,       
          "name" : "user_image_1"
        }
      ],      
      "name" : "loveshape_17"
    }
  ]
}

img.css

var mask1 = $(".container").mask({
            maskImageUrl: maskedImageUrla,
            onMaskImageCreate: function(img) {

                img.css({
                    "position": "fixed",
                    "left": 50, // get x value from json
                    "top": 69   // get y value from json
                });
            }
        });

这里是 Full json in pastebin full JS code

1 个答案:

答案 0 :(得分:1)

在解析JSON数据时,将x / y存储在变量中。

var maskedImageUrla = "";
var coordinates = { x: 0, y: 0 };

$.getJSON('test.json', function(json) {
    for (let layer of json.layers) {
        if (layer.layers && layer.layers.length > 0) {
            for (let temp of layer.layers) {
                if (temp.src) maskedImageUrla = temp.src;
                else if (temp.layers) {
                    for (let tl of temp.layers)
                        if (tl.src) {
                            maskedImageUrla = tl.src;
                            coordinates.x = tl.x;
                            coordinates.y = tl.y;
                        }
                }
            }
        }
    }

然后检索数据并将正确的单位添加到CSS。

img.css({
    "position": "fixed",
    "left": coordinates.x + "px",
    "top": coordinates.y + "px" 
});

我已经编辑了答案,以更好地满足您的需求。您仍应注意,这可能不是您想要的,因为您的文件格式在此处和此处散布着多个X / Y值。带有src的值只有x:0和y:0,因此您应该存储temp.xtemp.y

我对您的JSON文件格式不熟悉,但是我希望这能使您走上正确的轨道。