0

画布无法获取从 xmlhttpresponse 传递的值。难道是编码顺序有问题?我是否以错误的顺序放置画布?这是我使用的代码。

<script>
function loadXMLDoc()
{
str="GT299.842.65.416 2002";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var result=xmlhttp.responseText;
var n=result.split(" ");
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(n[0],n[1]);
ctx.stroke();
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
 <body>

 <button type="button" onclick="loadXMLDoc()">Change Content</button>
<div id="myDiv"></div>
 <canvas id="myCanvas" width="400" height="400" style="border:1px solid #d3d3d3;">
 </body>
4

1 回答 1

0

获取并解析 XMLHttpRequest

[编辑:清理上下文绘图代码]

首先,请务必将 ctx.beginPath() 添加到您的画布绘图代码中:

ctx.beginPath();  // required for all line,curve,arc,path draws
ctx.moveTo(0,0);
ctx.lineTo(n[0],n[1]);
ctx.stroke();

假设您有一个这样的 XML 文件 (myLineXYs.xml):

<?xml version="1.0" encoding="ISO-8859-1"?>
<lineXYs>
    <line="0">
      <X>50</X>
      <Y>25</Y>
    </line>
    <line="1">
      <X>100</X>
      <Y>25</Y>
    </line>
</lineXYs>

您将 GET 并解析出 2 行的 X/Y,如下所示:

// IE--there you go again being different!
if (window.XMLHttpRequest)
  { xhttp=new XMLHttpRequest(); }
else
  { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); }

// GET myLineXYs.xml
xhttp.open("GET","myLineXYs.xml",false);
xhttp.send();
xmlDoc=xhttp.responseXML;

// Parse out the X/Y for the 2 lines
var x0=xmlDoc.getElementsByTagName("X")[0].childNodes[0].nodeValue
var y0=xmlDoc.getElementsByTagName("Y")[0].childNodes[0].nodeValue

var x1=xmlDoc.getElementsByTagName("X")[1].childNodes[0].nodeValue
var y1=xmlDoc.getElementsByTagName("Y")[1].childNodes[0].nodeValue
于 2013-03-13T12:06:11.830 回答