当用户给出X和Y坐标时,我试图在Canvas中绘制一条线。这就是我到目前为止所拥有的。我可以得到它赢得的画布和输入框。我是一个新手,所以任何建议都表示赞赏。
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x1 = document.getElementById("x1").value;
var x2 = document.getElementById("x2").value;
var y1 = document.getElementById("y1").value;
var y2 = document.getElementById("y2").value;
function draw(){
context.beginPath();
context.moveTo(x1.value,y1.value);
context.lineTo(x2.value,y2.value);
context.stroke();
}
</script>
<br><br>
<h1>Draw a Line</h1>
X-coordinate 1 <input type="text" id="start_x"><br><br>
Y-coordinate 1<input type="text" id="start_y"><br><br>
X-coordinate 2<input type="text" id="end_x"><br><br>
Y-coordinate 2<input type="text" id="end_y"><br><br>
<input type="button" value="draw" onclick="draw()">
答案 0 :(得分:1)
它给你未定义,因为你将输入id设置为start_x,start_y,end_x,end_y,并且在你的js中你得到的值是x1,x2,y1,y2。
HTML
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;">
</canvas>
<h1>Draw a Line</h1>
<form>
X-coordinate 1 <input type="text" id="start_x"><br><br>
Y-coordinate 1<input type="text" id="start_y"><br><br>
X-coordinate 2<input type="text" id="end_x"><br><br>
Y-coordinate 2<input type="text" id="end_y"><br><br>
<input type="button" value="draw" onclick="draw()">
</form>
JS
function draw(){
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x1 = document.getElementById("start_x").value;
var x2 = document.getElementById("start_y").value;
var y1 = document.getElementById("end_x").value;
var y2 = document.getElementById("end_y").value;
context.beginPath();
context.moveTo(x1,x2);
context.lineTo(y1,y2);
context.stroke();
}
答案 1 :(得分:0)
您的draw
函数名为onclick
,但该函数使用的input
value
设置为&#39; undefined&#39;因为在加载窗口时未定义input
的值,要解决此问题,您应该包含在draw
函数中获取这些值的代码。
答案 2 :(得分:0)
以这种方式重写代码;
> nslookup test.sub.domain.com <domain.com server>
Name: test.sub.domain.com
Served by:
- <sub.domain.com server>
sub.domain.com