Javascript 在画布中移动对象
我陷入了一个我不知道该怎么办的境地。我正在学习使用canvas元素的基础知识,所以我给自己布置了一个小任务。我想在画布上画一个圆圈,按下按钮可以向前推。因此,每次按下按钮时,圆圈应向前移动10像素。但现在我被困了一段时间,我不知道我做错了什么。我对javascript编程和总体编程也是新手 这是我目前掌握的代码Javascript 在画布中移动对象,javascript,canvas,Javascript,Canvas,我陷入了一个我不知道该怎么办的境地。我正在学习使用canvas元素的基础知识,所以我给自己布置了一个小任务。我想在画布上画一个圆圈,按下按钮可以向前推。因此,每次按下按钮时,圆圈应向前移动10像素。但现在我被困了一段时间,我不知道我做错了什么。我对javascript编程和总体编程也是新手 这是我目前掌握的代码 <html> <head></head> <body> <button onclick="animationStep()"
<html>
<head></head>
<body>
<button onclick="animationStep()" id="startAnimation" style="width:200px; height:50px; color:"green";">Press here to move</button>
<canvas id="myCanvas" width="500" height="300"
style="border: 1px dotted black">
</canvas>
<script>
function drawDisc( x,y,r ) {
theContext.beginPath();
theContext.arc(x,y,r,0,Math.PI*2,false);
theContext.closePath();
theContext.fill();
}
function startDrawing(canvasId) {
var canvasElement = document.getElementById(canvasId);
var drawingContext = canvasElement.getContext("2d");
return drawingContext;
}
var theContext = startDrawing("myCanvas")
var x = 100;
function animationStep(){
while( x <= 400 ) {
x = x + 10;
theContext.clearRect(0,0,500,300);
drawDisc( x, 100, 30 );
console.log("animated");
}
}
</script>
</body>
</html>
当我查看控制台日志时,它立即执行动画36次。我认为它被困在while循环中,但我不知道如何让它正常工作。也许我忽略了一些简单的事情
谢谢你 摆脱while循环 所以
成功了!哇,那就这么简单了。问题是我的代码挂起在while循环中,只显示了最后一个可能的循环?你的while循环将x增加到410,当你第二次调用它时,while循环将不起作用,因为x大于400。嘿,我知道你是新来的。如果您认为答案解决了问题,请单击绿色复选标记将其标记为“已接受”。这有助于将注意力集中在仍然没有答案的老年人身上。
function animationStep(){
while( x <= 400 ) {
x = x + 10;
theContext.clearRect(0,0,500,300);
drawDisc( x, 100, 30 );
console.log("animated");
}
}
function animationStep(){
x = x + 10;
theContext.clearRect(0,0,500,300);
drawDisc( x, 100, 30 );
console.log("animated");
}