使用Ajax将JSON数据绘制到画布中,并将JSON项目存储在变量中



嗨,我已经编写了此代码以从文本文件中获取JSON数据,并在我设法将数据从JSON中获取数据的画布上绘制了形状想要将每个形状作为变量存储,以便我以后在代码中单击它的稍后。

我已经编写了此代码来尝试此代码,但它仅绘制一个矩形,甚至没有绘制其内部的文本。

这是我的代码...

function ajax_GetCanvasData(){
    var req = new XMLHttpRequest();
    var context = document.getElementById("drawing_canvas").getContext('2d');
    req.open("GET", "List.php", true);
    req.setRequestHeader("Content-type", "application/json");
        req.onreadystatechange = function() {
        if(req.readyState == 4 && req.status == 200) {
            var data = JSON.parse(req.responseText);
            for(var item in data){
                if (data[item].type == "Node"){
                    var text = data[item].text;
                    var cx = data[item].cx;
                    var cy = data[item].cy;
                    var width = data[item].width;
                    var height = data[item].height;
                    var colour = data[item].colour;
                    node = new nodeObj(context,text,cx,cy,width,height,colour);
                }
            }
        }
    }
    req.send(null);
}
function nodeObj(context,text,cx,cy,width,height,colour) {
    this.text = text;
    this.cx = cx;
    this.cy = cy;
    this.width = width;
    this.height = height;
    this.colour = colour;
    var lineheight = 15
    context.fillStyle = colour;
    context.fillRect(cx,cy,width,height);
    context.strokeRect(cx,cy,width,height);
    context.fillStyle = '#000000';
    context.font = 'bold 12px Ariel, sans-serif';
    context.textAlign = 'center';
    context.textBaseline = 'ideographic';
    wrapText(context, text, cx + (width*0.5), cy+(height*0.5), width, lineHeight);
}

我会考虑使用诸如Paper.js之类的库。它使您可以将对象引用以路径形式保留在画布上的内容。这些您可以在以后通过编程操作。

似乎正是您想做的。

这是我在使用PaperJs上创建的屏幕录像:http://tagtree.tv/canvas-with-paper-js,这是您想做的事情的完美入门。

最新更新