What is wrong with my Javascript code? Things that are not working correctly: 1.
ID: 3706418 • Letter: W
Question
What is wrong with my Javascript code? Things that are not working correctly:
1. I first need to start the white ball at the upper left corner of the screen like this before even pressing the start button:
2. Then, the ball is supposed to bounce off every wall without disappearing off the canvas. When I press start, halfway through the ball starts acting crazy and then leaves the canvas. How do I fix this?
HERE IS THE JAVASCRIPT CODE:
const CANVAS_WIDTH = 640;
const CANVAS_HEIGHT = 480;
const REPAINT_DELAY = 25;
const CIRCLE_RADIUS = 10;
const CIRCLE_SPEED = 1.5;
var repaintTimer = null;
function startAnimation()
{
if (repaintTimer == null)
repaintTimer = setInterval(repaint, 100);
}
function stopAnimation()
{
if (repaintTimer != null)
{
clearInterval(repaintTimer);
repaintTimer = null;
}
}
var circleX = -CIRCLE_RADIUS,
circleY = Math.floor(Math.random() * CANVAS_HEIGHT),
circleRadius = CIRCLE_RADIUS,
circleSpeedX= 1.5,
circleSpeedY= 2.75;
function repaint()
{
if (circleX + CIRCLE_RADIUS >= CANVAS_WIDTH)
{
circleSpeedX = -circleSpeedX;
circleY = Math.floor(Math.random() * CANVAS_HEIGHT);
}
else if (circleX - CIRCLE_RADIUS < 0)
{
circleSpeedX= -circleSpeedX;
}
if (circleY + CIRCLE_RADIUS >= CANVAS_HEIGHT)
{
circleSpeedY = -circleSpeedY;
circleY = Math.floor(Math.random() * CANVAS_HEIGHT);
}
else if (circleY - CIRCLE_RADIUS < 0)
{
circleSpeedY= -circleSpeedY;
}
circleX = circleX + circleSpeedX
circleY = circleY + circleSpeedY
var myCanvas = document.getElementById("myCanvas"),
context = myCanvas.getContext("2d");
context.fillStyle = "#0000FF";
context.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
context.fillStyle = "white";
context.beginPath();
context.arc(circleX, circleY, circleRadius, 0, 2 * Math.PI);
context.fill();
circleX = circleX + CIRCLE_SPEED;
}
D. ::: Apps D2L D IT M TitanApps Titan Web -UW Oshkosh ?Degree Requiremen. Start StopExplanation / Answer
Hi,
It seems dimensions you have given are not appropriate. Try changing the dimensions of the screen specially, the hieght or width. Try with a set of values first lesser than then greater than what you have declared now.
By dimensions, I mean canvas hieght and width and all.
Hope that will help you!!! Thanks...Do give this answer a thumbs up!!!:)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.