簡體   English   中英

怎么畫在畫布上讀一個json?

[英]how draw in canvas read a json?

我試圖在HTML5 canvasHTML5 canvas 我設法畫在畫布上,但我需要動態地做。 這是我的JavaScript代碼:

var c=document.getElementById("yellow");
var ctx=c.getContext("2d");

ctx.beginPath();
ctx.moveTo(247,373);
ctx.lineTo(0,390);
ctx.lineTo(5,21);
ctx.lineTo(245,0);
ctx.lineTo(247,373);
ctx.closePath();
ctx.fillStyle="#ffca05";
ctx.globalAlpha=0.7;
ctx.strokeStyle = '#ffca05';
ctx.fill();
ctx.stroke();

我需要從這個json array讀取數據並使用這些坐標進行繪制。

[{"x":"247", "y":"373"}, {"x":"0", "y":"390"},{"x":"5", "y":"21"},{"x":"245", "y":"0"}, {"x":"247", "y":"373"}]

您所要做的就是在for循環中遍歷JS對象並重復執行ctx.lineTo() 注意: ctx.lineTo()之后的第一個ctx.beginPath()就像ctx.moveTo()

您可以運行此代碼段來驗證結果:

 var c=document.getElementById("yellow"); var ctx=c.getContext("2d"); var json=[ {"x":"247", "y":"373"}, {"x":"0", "y":"390"}, {"x":"5", "y":"21" }, {"x":"245", "y":"0" }, {"x":"247", "y":"373"} ]; ctx.beginPath(); for(var i in json){ ctx.lineTo(json[i].x,json[i].y); } ctx.closePath(); ctx.fillStyle="#ffca05"; ctx.globalAlpha=0.7; ctx.strokeStyle="#ffca05"; ctx.fill(); ctx.stroke(); 
 <canvas id="yellow" width="250" height="400"></canvas> 

PS:我可以注意到畫布頂邊的頂角(也可能是左邊的那個)有點被切掉了。 只需在每個坐標上添加1左右即可解決此問題:

[
  {"x":"248", "y":"374"},
  {"x":"1",   "y":"391"},
  {"x":"6",   "y":"22" },
  {"x":"246", "y":"1"  },
  {"x":"248", "y":"374"}
];

我還不能評論,但是關於讀取外部JSON文件的問題:如果您的文件在某個URL上可用,您可以通過jQuery使用AJAX輕松獲取所需的JSON數據,解析它並將其存儲在變量中您的網頁/應用程序的本地。 快速舉例:

var myJSON; //the json object data you're going to draw to canvas with

$(document).ready(function(){
        $.ajax({
            url: "myurl.com/myjsonfile",
            dataType: "text",
            success: function(data) {
                myJSON = $.parseJSON(data);
                drawToCanvas(myJSON); //you can, perhaps, make the code
                                      //Xufox provided into a function that
                                      //you pass your myJSON var to once it
                                      //is loaded.
            }
        });
    })

'$ .ajax'調用將處理從上面指定的URL獲取數據,並且只有在數據加載並傳遞給myJSON(然后傳遞給方法)后才會執行'drawToCanvas()'方法。

您可以直接在函數中引用參數,或將其存儲在局部變量中:

function drawToCanvas(jsonObj) {
    var json = jsonObj;

    ctx.beginPath();
    for(var i in json){
       ctx.lineTo(json[i].x,json[i].y);
    }
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM