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.
Related
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>
I have a web app that receives some array of points and I need to draw them on a canvas. Unfortunately, I get the dataset not the way I want. I need to rotate the shapes 180 degrees. I have no idea how to do this...
Please see the example in the snippet.
// Main template shape
let shape = [{x: 10, y:10}, {x: 120, y:10}, {x: 110, y:110}, {x: 50, y:175}];
let canvas = {}; // Canvas to draw on
let ctx = {}; // Context of the Canvas
// Init elements
$( document ).ready(function() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
drawShape();
});
// Draw the template
function drawShape() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'yellow';
ctx.fillStyle = 'red';
for(let point of shape) {
ctx.lineTo(point.x, point.y);
}
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Hahaha!</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
</body>
</html>
If I understand your question correctly, you want to turn the shape around by 180 degrees ?
As in vertically invert it ? If this is it, here's a solution, you need an axis relative to which to turn it. Problem is if you just invert for every point (x,y), you put (x,-y), canvas being defined for only positive values it won't show on your screen, imagine it outstide the screen, you need to "push" it back down onto the canvas, you do this by adding the height of the canvas after having inverted the shape.
// Main template shape
let shape = [ {x:10, y:10}, {x:120, y:10}, {x:110, y:110}, {x:50, y:175} ];
let canvas = {}; // Canvas to draw on
let ctx = {}; // Context of the Canvas
// Init elements
$( document ).ready(function() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
drawShape();
});
// Draw the template
function drawShape() {
ctx.save();
ctx.beginPath();
ctx.strokeStyle = 'yellow';
ctx.fillStyle = 'red';
for(let i = 0; i < shape.length; i++) {
ctx.lineTo(shape[i][0], -shape[i][1] + 200);
}
for(let point of shape) {
ctx.lineTo(point.x, -point.y + 200);
}
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<title>Hahaha!</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
</body>
</html>
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
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.
I have the following HTML. It draws a Colorado state flag, but only if I move the lines that are in the window.onload() function into the drawLogo() function, so I think the trouble is not that drawLogo() doesn't get called, but that the global canvas, ctx, x, and y are somehown not really global. I want to put in other functions that do other things in this same canvas, so that is why I want the canvas, ctx, x, and y to be global.
I know window.onload() gets executed, because I can also get it to draw the flag by putting the call to drawLogo() inside window.onload().
<!DOCTYPE html>
<html lang="en">
<head>
<title>Logo</title>
<script type="text/javascript">
var canvas;
var ctx;
var x;
var y;
window.onload = function () {
canvas = document.getElementById('logo');
ctx = canvas.getContext('2d');
x = canvas.width;
y = canvas.height;
};
var drawLogo = function() {
var radius = 23;
var counterClockwise = false;
ctx.beginPath();
ctx.rect(3, 20, 75, 30);
ctx.fillStyle = 'rgba(0,0,255,0.8)';
ctx.fill();
ctx.beginPath();
//ctx.globalAlpha = 0.5;
ctx.rect(3, y-60, 75, 30);
ctx.fillStyle = 'rgba(0,0,255,0.8)';
ctx.fill();
ctx.beginPath();
ctx.arc(40, 70, 30, 0, 2 * Math.PI, counterClockwise);
ctx.fillStyle = 'Yellow';
ctx.fill();
ctx.beginPath();
ctx.arc(40, 70, 30, 2.15 * Math.PI, 3.85 * Math.PI, counterClockwise);
ctx.strokeStyle = '#cc3333';
ctx.lineWidth = 18;
ctx.stroke();
};
</script>
</head>
<body>
<div>
<canvas id="logo" width="600" height="150"></canvas>
<script type="text/javascript">
drawLogo();
</script>
</div>
</body>
</html>
window.onload is called when the entire page is loaded, this means CSS, JS files, Fonts, images and almost everything is downloaded.
Your drawLogo function instead is executed when the script tag is evaluated while loading the page.
What is happening then is that the drawLogo function is called before you populate the global variables.
A simple solution would be to put your drawLogo function inside the window.onload function.
I 'd also suggest to change the onload event with a quicker onready in your case, but it is a minor thing.