我有一个JavaScript代码,用于从网站获取JSON数据,并在收集的数据与if语句中的数据匹配时在图像上写入文本。但它不起作用,我不确定原因。我尝试在没有readline()
语句的情况下执行context.drawText
并且它可以工作,但是当我把它放在if
语句中时,代码就不会绘制。请帮忙。
if
答案 0 :(得分:2)
你必须在$ .get函数中移动你的DrawText只有你得到结果才能检查值,因为你在Get函数之前调用的Drawtext所以结果值是未定义的,
请检查此代码
<强> JS 强>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<canvas id="myCanvas" width="900" height="800"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var imageObj = new Image();
var result;
imageObj.onload = function()
{
DrawScreen();
};
$.get(
"https://dweet.io/get/latest/dweet/for/james",
function(data)
{
result = data['with'][0]['thing'];
DrawText();
}
);
imageObj.src = 'https://s31.postimg.org/v85n3kvez/dummyfp.jpg';
function DrawScreen()
{
context.drawImage(imageObj, 10, 10);
}
function DrawText()
{
context.fillStyle = "green";
context.font = "18px sans-serif";
context.textBaseline = 'top';
alert(result)
if (result == '' || result == null)
{
context.fillText('noooo', 430, 100);
}
if (result == 'james')
{
context.fillText('james', 430, 100);
}
else
{
context.fillText('thisisnt', 430, 100);
}
}
</script>
答案 1 :(得分:1)
我更新了$ .get调用以获得onComplete事件:JSFIDDLE
$.get({
url: "https://dweet.io/get/latest/dweet/for/james",
success: function(data)
{
result = data['with'][0]['thing'];
//show what is inside result
//document.write(result);
},
complete: function(){
DrawText();
}
});
答案 2 :(得分:0)
在imageObj.onload中放入$ .get,在$ .get回调函数中放入DrawScreen / DrawText。