Ball won't load up for game - javascript

// Main Javascript
//Variables to use
var canvas;
var context;
var ball;
canvas = documnet.getElementById("canvas");
context = canvas.getcontext("2d");
//Creates my ball function based off of what is on canvas for ball
ball = new Ball();
Well my ball is not showing up on screen and I am pretty sure I have done everything correctly but can someone look over it and find something I missed or made a mistake on? I really need some help and I appreciate the help!
I have two Javascript files in here because I have one for my main javascript and ball
//ball.js
function ball() {
//The ball itself
this.startAngle = 0;
this.endAngle = 360 * Math.PI * 2;
this.radius = 40;
this.drawBall = true;
//location for my ball
this.x = canvs / width / 2;
this.y = canvas / height / 2;
//coloring my ball
this.color = " #00FFFF";
//draw function
this.draw = function () {
context.fillStyle = this.color;
context.beginPath();
content.arc(this.x, this.y, this.redius, this.startAngle, this.Endangle, this.drawBall);
context.fill();
}
}
My HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" >
<title>Robert's Ball Game</title>
<link type="text/css" rel="stylesheet" href = css/robs.css" />
</head>
<body>
<canvas id="canvas" width="1000" height="720"></canvas>
</body>
//Javascript
<script type="text/javascript" src= "javas/ball.js"> </script>
<script type="text/javascript" src= "javas/rob.js"> </script>
</html>

You've got lots of spelling and capitalisation errors, and you hadn't actually called the ball.draw() function.
I've added comments in the code below to show what I've changed to make it work (click "run" to see the result):
var canvas;
var context;
var ball;
canvas = document.getElementById("canvas"); // "document", not "documnet"
context = canvas.getContext("2d"); // needs capital "C" in getContext
//Creates my ball function based off of what is on canvas for ball
ball = new Ball();
ball.draw(); // you didn't call .draw()
//ball.js
function Ball() {
//The ball itself
this.startAngle = 0;
this.endAngle = 360 * Math.PI * 2;
this.radius = 40;
this.drawBall = true;
//location for my ball
this.x = canvas.width / 2; // you had canvs / width / 2
this.y = canvas.height / 2; // you had canvas / height / 2
//coloring my ball
this.color = "#00FFFF";
//draw function
this.draw = function () {
context.fillStyle = this.color;
context.beginPath();
// on next line you had "content" instead of "context",
// and "Endangle" instead of "endAngle", and "redius" instead of "radius":
context.arc(this.x, this.y, this.radius, this.startAngle, this.endAngle, this.drawBall);
context.fill();
}
}
<canvas id="canvas" width="200" height="200"></canvas>

Related

Flashing dots on canvas [duplicate]

This question already has answers here:
clearRect not working
(2 answers)
Closed 6 months ago.
I don't see why this code isn't working. It should just draw a white rectangle covering the screen. Then a randomly placed blue dot and wait for the loop to complete. And then repeat the cycle by drawing the white rectangle again and turning off the dot and then redrawing it.
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8"/>
<title>Peripheral vision checker</title>
<script type="application/javascript">
function draw() {
// draw crosshairs
var onFor = 1000;
const intervalID = setInterval(mytimer, onFor);
function mytimer()
{
// draw white rects
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var x = 1280;//will be equal to window height
var y = 720;//will be equal to window width
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'white';
var xcoor =getRandomInt(x);
var ycoor =getRandomInt(y);
ctx.fillRect(0, 0, x, y);
ctx.fillStyle = 'blue';
var radius = 10;
moveTo(xcoor,ycoor);
ctx.arc(xcoor, ycoor, radius, 0, 2 * Math.PI);
//console.log(xcoor + ' ' + ycoor);//just temporary, to see they work
ctx.fill();
}
}
</script>
</head>
<h1>Peripheral vision checker</h1>
<body onload="draw();">
<canvas id="canvas" width="1280" height="720"></canvas>
</body>
</html>
You need to beginPath then closePath
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Peripheral vision checker</title>
<script type="application/javascript">
function draw() {
// draw crosshairs
var onFor = 1000;
const intervalID = setInterval(mytimer, onFor);
function mytimer() {
// draw white rects
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
var x = 500; //will be equal to window height
var y = 250; //will be equal to window width
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'white';
var xcoor = getRandomInt(x);
var ycoor = getRandomInt(y);
ctx.fillRect(0, 0, x, y);
ctx.fillStyle = 'blue';
var radius = 10;
ctx.beginPath();
moveTo(xcoor, ycoor);
ctx.arc(xcoor, ycoor, radius, 0, 2 * Math.PI);
//console.log(xcoor + ' ' + ycoor);//just temporary, to see they work
ctx.fill();
// no need to:
// ctx.closePath();
}
}
</script>
</head>
<h1>Peripheral vision checker</h1>
<body onload="draw();">
<canvas id="canvas" width="500" height="250"></canvas>
</body>
</html>

HTML5 Canvas: Not drawing

I'm currently creating a simple program using HTML Canvas and Javascript. All that I need to happen is for a ball to be drawn at coordinates on the canvas and then move around using some velocity variables etc.
The issue is, I've created a Ball object as I intend to have multiple balls on screen at a time, however nothing is showing on my canvas.
I've read over this a few times, I'm receiving no errors so I'm struggling to figure out what's happening with this.
EDIT:
I've added a console log to check the drawSelf() is running, which it is but still no error/result
CODE
<!DOCTYPE html>
<html>
<head>
<title>Bouncing Ball</title>
</head>
<script>
var Date
var canvas;
var ctx;
var dx=5;
var dy=5;
function init(){
canvas = document.getElementById('game');
ctx = canvas.getContext('2d');
setInterval(draw,10);
console.log("Initialised: " + new Date());
}
function Ball(x, y, dx, dy){
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.drawSelf = function () {
ctx.beginPath();
ctx.fillStyle = "#4286f4";
ctx.arc(this.x,this.y,20,0,Math.PI*2,true);
ctx.closePath();
console.log("Ball is drawing self!");
if(this.x<0 || this.x>800){
dx=-dx;
}
if(this.y<0 || this.y>800){
dy=-dy;
}
this.x+=this.dx;
this.y+=this.dy;
}
this.getX = function () {
console.log("X:" + this.x);
console.log("Y:" + this.y);
}
}
//Creating Ball object.
let ball1 = new Ball(400, 400, 5, 5);
function draw(){
ball1.drawSelf();
}
</script>
<body onLoad="init()">
<div id="canvas-area">
<canvas id="game" width="800" height="800"></canvas>
</div>
</body>
<html>
You forgot to add ctx.stroke() or ctx.fill(), taken from the Mozilla docs
this.drawSelf = function () {
ctx.beginPath();
ctx.fillStyle = "#4286f4";
ctx.arc(this.x,this.y,20,0,Math.PI*2,true);
ctx.stroke();
ctx.closePath();
console.log("Ball is drawing self!");
if(this.x<0 || this.x>800){
dx=-dx;
}
if(this.y<0 || this.y>800){
dy=-dy;
}
this.x+=this.dx;
this.y+=this.dy;
}
Also sidenote, since you don't set the background every draw, your canvas will just add the ball to it's current state, resulting in a cool pattern, but something you probably don't want. To fix this, make this your draw method.
function draw(){
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ball1.drawSelf();
}
EDIT: Instead of using setInterval I recommend using requestAnimationFrame. You can read more about it here

Javascript Canvas one item flickering

I am trying to make to objects move towards each other in Canvas, when they meet and overlap one should then disappear and the other should fall down. Now I got the animation to do that, but one of the items is flickering.
<!DOCTYPE html>
<html>
<head>
<style>
canvas{border:#666 3px solid;}
</style>
</head>
<body onload="draw(530,15); draw1(1,15);">
<canvas id="canvas" width="600" height="400"></canvas>
<script>
function draw(x,y){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(x, y, 600, 400);
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect (x, y, 70, 50);
ctx.restore();
x -= 0.5;
if(x==300)
{
return;
};
var loopTimer = setTimeout('draw('+x+','+y+')',5);
};
function draw1(w,e){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(w-1,e-2,600,400);
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect (w, e, 70, 50);
ctx.restore();
w += 1;
if(w==265)
{
w -= 1;
e +=2;
};
var loopTimer = setTimeout('draw1('+w+','+e+')',10);
};
</script>
</body>
</html>
Been trying for two days, but can't seem to fix it properly. Thanks in advance.
You are rendering too many frames per second forcing the browser to present frames. Each time a draw function returns the browser presumes you want to present the frame to the page.
Animations need to be synced to the display refresh rate which for most devices is 60FPS. To do this you have one render loop that handles all the animation. You call this function via requestAnimationFrame (RAF) which ensures that the animation stays in sync with the display hardware and browser rendering.
<!DOCTYPE html>
<html>
<head>
<style>
canvas{border:#666 3px solid;}
</style>
</head>
<!-- dont need this <body onload="draw(530,15); draw1(1,15);">-->
<body>
<canvas id="canvas" width="600" height="400"></canvas>
<script>
var canvas,ctx,x,y,w,e;
var canvas,ctx,x,y,w,e;
function draw() {
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect(x, y, 70, 50);
};
function draw1(w, e) {
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect(w, e, 70, 50);
};
function update(time){ // high precision time passed by RAF when it calls this function
ctx.clearRect(0,0,canvas.width,canvas.height); // clear all of the canvas
if(w + 70 >= x){
e += 2;
}else{
x -= 0.75;
w += 1;
};
draw(x,y);
draw1(w,e);
requestAnimationFrame(update)
// at this point the function exits and the browser presents
// the canvas bitmap for display
}
function start(){ // set up
x = 530;
y = 15;
w = 1;
e = 15;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
requestAnimationFrame(update)
}
window.addEventListener("load",start);
</script>
</body>
</html>
You're method of animation is very outdated (ie, the use of setTimeout). Instead you should be using requestAnimationFrame as demonstrated below. This will give smooth, flicker free animation.
<!DOCTYPE html>
<html>
<head>
<style>
canvas{border:#666 3px solid;}
</style>
</head>
<body onload="requestAnimationFrame(animate);">
<canvas id="canvas" width="600" height="400"></canvas>
<script>
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 530, y = 15;
function animate(){
requestID = requestAnimationFrame(animate);
ctx.clearRect(x, y, 600, 400);
ctx.fillStyle = "rgba(0,200,0,1)";
ctx.fillRect (x, y, 70, 50);
x -= 0.5;
if(x==300)
{
cancelAnimationFrame(requestID)
};
}
</script>
</body>
</html>
the first 2 parameters of ctx.clearReact in both draw functions should be 0:
ctx.clearRect(0, 0, 600, 400);
This means you clear all canvas.

Paint circle method JavaScript

I am trying to find a way to draw a circle using JavaScript and redraw it while erasing the old circle.
i got this code:
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 15;
drawCircle(centerX,centerY,radius);
drawCircle(150,150,25);
function drawCircle(centerX,centerY,radius)
{
var canvas = document.getElementById('myCanvas');
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'black';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
};
</script>
The problem is that this two methods draw two circles instead of drawing one instead of the other.
I am beginner in JS would appreciate help on making better way of drawing and erasing the circle
Thanks
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 15;
function drawCircle(centerX,centerY,radius)
{
// Erase context
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'black';
context.fill();
context.lineWidth = 5;
context.strokeStyle = '#003300';
context.stroke();
};
drawCircle(centerX,centerY,radius);
drawCircle(150,150,25);
<html>
<head>
<style>
body {
margin: 0px;
padding: 0px;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="578" height="200"></canvas>
If you want to remove a circle from the canvas you will have to draw a circle (same position; same size) but this time with the color of the canvas background.
drawCircle(150,150,25,'black');
// ...
drawCircle(150,150,25,'white'); // removes previous circle if the canvas was white colored
If you want to erase everything from the canvas before drawing something new you can just execute this
context.clearRect(0, 0, canvas.width, canvas.height);

Having trouble with canvas, I've followed online tutorials but nothing shows in browser window

I've been learning how to use html5 recently and one aspect that really interests me is the canvas's ability to create animations. I have followed some online tutorials to some success but recently I found "thecodeplayer" where there are some awesome tutorials (if your in to it, check it out). I've got to the point where I've gone through it various times but still with no luck. The canvas does not show in my browser window when I load it up in chrome. Ive even turned off extensions like adblocker as suggested from some answers on this site. Its probably something obvious but I cant find where I seem to have gone wrong. Anyone who can point me in the right direction, thanks
Heres the code.
<html>
<head>
<script type="text/javascript">
//Initializing the canvas
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//Canvas dimensions
var W = 500; var H = 500;
//create an array of particles
var particles = [];
for(var i = 0; i < 50; i++)
{
//This will add 50 particles to the array with random positions
particles.push(new create_particle());
}
//function to create multiple particles
function create_particle()
{
//Random position on the canvas
this.x = Math.random()*W;
this.y = Math.random()*H;
//add random velocity to each particle
this.vx = Math.random()*20-10;
this.vy = Math.random()*20-10;
//Random colors
var r = Math.random()*255>>0;
var g = Math.random()*255>>0;
var b = Math.random()*255>>0;
this.color = "rgba("+r+", "+g+", "+b+", 0.5)";
//Random size
this.radius = Math.random()*20+20;
}
var x = 100; var y = 100;
//animate the particle
function draw()
{
//paint canvas black, remove particle trails
ctx.globalCompositeOperation = "source-over";
//reduce the opacity of the BG paint to give the final touch
ctx.fillStyle = "rgba(0, 0, 0, 0.3)";
ctx.fillRect(0, 0, W, H);
//blend the particle with the BG
ctx.globalCompositeOperation = "lighter";
//draw particles from the array now
for(var t = 0; t < particles.length; t++)
{
var p = particles[t];
ctx.beginPath();
//colors
var gradient = ctx.createRadialGradient(p.x, p.y, 0, p.x, p.y, p.radius);
gradient.addColorStop(0, "white");
gradient.addColorStop(0.4, "white");
gradient.addColorStop(0.4, p.color);
gradient.addColorStop(1, "black");
ctx.fillStyle = gradient;
ctx.arc(p.x, p.y, p.radius, Math.PI*2, false);
ctx.fill();
//velocity
p.x += p.vx;
p.y += p.vy;
//Stops balls moving out of canvas
if(p.x < -50) p.x = W+50;
if(p.y < -50) p.y = H+50;
if(p.x > W+50) p.x = -50;
if(p.y > H+50) p.y = -50;
}
}
setInterval(draw, 33);
</script>
</head>
<body>
<canvas id="canvas"width="500"height="500"></canvas>
</body>
</html>
Place the code in a function, and add a script tag below the body HTML, calling the canvas drawing function. The canvas element is not yet created when you want to use it for drawing on.
Result:
<html>
<head>
<script type="text/javascript">
function doCanvasStuff () {
//Initializing the canvas
var canvas = document.getElementById("canvas");
...
setInterval(draw, 33);
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
<script>
doCanvasStuff();
</script>
</html>

Categories

Resources