Flashing dots on canvas [duplicate] - javascript

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>

Related

Making an object move back and forth in javascript [duplicate]

So I have this rectangle that animates across to the right. How can I get the rectangle to reverse it when it hits the boundaries. I'm trying to make it go back and forth.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'>
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
x++;
if(x <= 490) {
setTimeout(animate, 33);
}
}
animate();
}
</script>
</head>
<body>
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
</body>
</html>
https://codepen.io/forTheLoveOfCode/pen/wqdpeg
Is that what you need? (link to codepen above).
var canvas = document.getElementById("canvas_id");
var context = canvas.getContext('2d');
var x=5;
var y=5;
var velocity = 10;
function move(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
x =x + velocity
if ((x+50)>canvas.width || x<0){
velocity *=-1;
}
draw()
}
function draw(){
context.fillStyle = "#E80C7A";
context.strokeStyle = "#000000";
context.lineWidth = '3';
context.fillRect(x, y, 50, 100);
context.strokeRect(x, y, 50, 100);
}
setInterval(move, 100);
<html>
<body>
<canvas id = "canvas_id">
</canvas>
</body>
</html>
here's a solution with boundaries detection
window.onload=function(){
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var x = 0;
var y = 50;
var width = 10;
var height = 10;
var speed = 10; // speed
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, width, height);
if(
(x >= 500 - width && speed > 0) || // going to the right and bound reached
(x <= 0 && speed < 0) // going to the left and bound reached
) {
speed *= -1; // inverting the direction
}
x += speed;
setTimeout(animate, 33);
}
animate();
}
<canvas id="canvas" width="500" height="400"
style="border: 1px solid #000000;"></canvas>
consider using requestAnimationFrame instead of setTimeout to do this kind of work.

Javascript - Is there a more efficient method to repeat rectangle creation?

So i have this relatively simple code:
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(0, 0, c.width, c.height);
ctx.beginPath();
ctx.fillStyle = "yellow";
ctx.fillRect(400 * Math.random(), 400 * Math.random(), 3, 3);
ctx.stroke();
ctx.closePath();
Essentially it just creates a black canvas then randomly places a yellow square on it. Other than mindlessly copy and pasting, is there a more efficient method to redraw this multiple times? (Maybe some kind of setTimeout function?)
Hope this helps you out.
function myFunction() {
setInterval(function(){callRect();}, 3000);
}
function callRect(){
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
ctx.fillStyle = getRandomColor();
ctx.fillRect(0, 0, c.width, c.height);
ctx.beginPath();
ctx.fillStyle = "yellow";
ctx.fillRect(400 * Math.random(), 400 * Math.random(), 3, 3);
ctx.stroke();
ctx.closePath();
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inspiration</title>
</head>
<body>
<canvas id='canvas'></canvas>
<button type='button' onclick='myFunction();'>Button</button>
</body>
</html>

Ball won't load up for game

// 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>

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.

How would I align circles horizontally using loops?

I have managed to get the circles on top of each other but I have no clue how to make a line of circles that do not overlap.
This is what I have gotten so far.
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script src="js/main.js"></script>
</body>
</html>
JavaScript
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext('2d');
for(var i = 0; i < 10; i++) {
ctx.fillStyle="rgba(0,0,0,0.5)";
fillCircle(200,200,i*20)
}
var width = window.innerWidth;
var height = 100;
function fillCircle(x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
The x-value of any next circle must be at least be the sum of the current and next circle radii beyond the current circle's x-value.
So if:
var currentCircleX=20
var currentCircleRadius=15
var nextCircleRadius=25
Then:
var nextCircleX = currentCircleX + currentCircleRadius + nextCircleRadius
But if you are also stroking the circles:
Since a context stroke will extend half-outside the defined path, you must also add half the lineWidth for each circle to avoid the circles touching:
// account for the lineWidth that extends beyond the arc's path
var nextCircleX =
currentCircleX + currentCircleRadius + nextCircleRadius + context.lineWidth
Example code and a Demo:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
ctx.fillStyle="rgba(0,0,0,0.5)";
var currentCircleX=0;
var currentCircleRadius=0;
for(var i = 0; i < 10; i++) {
var nextCircleRadius=i*20;
var nextCircleX=currentCircleX+currentCircleRadius+nextCircleRadius;
fillCircle(nextCircleX,200,nextCircleRadius);
currentCircleX=nextCircleX;
currentCircleRadius=nextCircleRadius;
}
function fillCircle(x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.closePath();
ctx.fill();
}
body{ background-color: ivory; padding:10px; }
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Categories

Resources