我试图创建画布HTML 5来移动对象并在到达终点时停止。为此,我有10个X值和10个Y值。首先,我需要将所有值都作为X和Y的坐标。单击按钮时,动画应在到达结束时开始和停止。
注意:我必须用每个X和Y的10个值来计算,而且当达到X和Y的最后一个值时,必须停止Fish移动。这是我必须遵循的要求。
我的代码仅适用于前两个X和Y值。我不知道如何去做其余的事情。我尝试在for loop
函数内部创建GetStarted()
,但是它也没有正常工作。
function GetStarted(){
for(var i=0; i<10; i++){
// get the canvas's 2d context
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
// clear the canvas
context.clearRect(0, 0, canvas.width, canvas.height);
// get the position
var abc = Number(document.getElementById("x").value);
var xyz = Number(document.getElementById("y").value);
// creating an image from scratch
var image = new Image();
image.src = "https://www.uow.edu.au/~dong/w3/assignment/a8/fish.png";
// when the image are loaded,
// draw the image at the specified position
image.onload = function() {
context.drawImage(image, abc, xyz);
};
}
}
#x,#y {
width : 60px;
}
<table>
<tr>
<td> X </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
<td> <input id="x" /> </td>
</tr>
<tr>
<td> Y </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
<td> <input id="y" /> </td>
</tr>
</table>
<button onClick="GetStarted()">
Swim little fish</button>
<br /><br />
<canvas id="canvas" width="1200" height="300"
style="border:1px solid black;">
Your browser does not support canvas.
<img src="https://www.uow.edu.au/~dong/w3/assignment/a8/fish.png" id="fishes">
</canvas>
</body>
</html>
答案 0 :(得分:0)
这是移动鱼的起点:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var x = y = 0
// creating an image from scratch
var image = new Image();
image.onload = function() {
context.drawImage(image, x, y);
};
image.src = "https://www.uow.edu.au/~dong/w3/assignment/a8/fish.png";
function GetStarted() {
setInterval(Move, 20)
}
function Move() {
x = (x + 9) % canvas.width;
y = (y + 1) % canvas.height;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(image, x, y);
}
<button onClick="GetStarted()">Swim little fish</button> <br /><br />
<canvas id="canvas" width="600" height="170" style="border:1px solid black;"></canvas>
如您所见,我已经大大更改了您的代码!
现在鱼可以移动了,但是没有地方可以像以前那样输入X和Y了,所以原本就不会进行非常平滑的运动,反而更像是跳来跳去,同样, id到html元素,并期望您可以使用document.getElementById("y")
来获得所需的元素,