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

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.

Related

line contracts and expands in html

i want to make a line that contracts and expands along x-axis randomly it should start from the middle of canvas . I was only able to move the line one way, not both ways! i have the code, if you could please help me i would really appreciate it !
<!DOCTYPE html>
<style>
canvas {
border: solid;
border-color: black; }
</style>
<canvas id="canvas">
</canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.strokeStyle = "black";
var posX = 0;
var lineLength = 50;
var speed = 2;
function drawLine() {
ctx.beginPath();
ctx.moveTo(posX, 50);
ctx.lineTo(posX + lineLength, 50);
ctx.stroke();
}
function moveLine() {
posX += speed;
if (posX < 0 || posX > canvas.width - 50) {
speed = speed * -1;
}
}
function loop() {
// clear old frame;
ctx.clearRect(0, 0, canvas.width, canvas.height);
moveLine();
drawLine();
requestAnimationFrame(loop);
}
requestAnimationFrame(loop);
</script>
You want to be modifying the value of lineLength in your loop, not posX. Like this:
function moveLine() {
lineLength += speed;
if (lineLength < 0 || lineLength > canvas.width - 50) {
speed = speed * -1;
}
}
Then you just need to center your line:
function drawLine() {
var center = canvas.width/2;
ctx.beginPath();
ctx.moveTo(center - (lineLength/2), 50);
ctx.lineTo(center + (lineLength/2), 50);
ctx.stroke();
}
Since the X position of your line isn't variable, you don't need posX at all.

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.

DrawImage() doesn't draw on canvas

I am trying to make a screen following the player so that the player is in the middle of the screen. I have already made it in another game, but here it doesn't work. Here is my code :
var c = document.getElementById("main");
var ctx = c.getContext("2d");
var screen = document.getElementById("screen").getContext("2d");
var WhatUSeeWidth = document.getElementById("screen").width;
var WhatUSeeHeight = document.getElementById("screen").height;
ctx.beginPath();
for (i = 0; i < 100; i ++) {
if (i % 2) {
ctx.fillStyle = "red";
}
else {
ctx.fillStyle = "blue";
}
ctx.fillRect(0, i * 100, 500, 100);
}
var player = {
x : 700,
y : 800
}
setInterval(tick, 100);
function tick() {
screen.beginPath();
screen.drawImage(c, player.x - WhatUSeeWidth / 2, player.y - WhatUSeeHeight / 2, WhatUSeeWidth, WhatUSeeHeight, 0, 0, WhatUSeeWidth, WhatUSeeHeight);
}
canvas {
border: 2px solid black;
}
<canvas id="main" width="500" height="500"h></canvas>
<canvas id="screen" width="500" height="500"></canvas>
I want to draw The Blue and red canvas in The "screen" canvas Using drawImage
Ok , from your comment I understood what you are looking for. But the problem is that you probably start by an example without having understood. I try to give you my interpretation of what you do , but you should look for a good guide that starts with the basics and deepen animations (for example this: http://www.html5canvastutorials.com/).
HTML
<canvas id="canvasLayer" width="500" height="500"></canvas>
Javascript
var canvas = document.getElementById("canvasLayer");
var context = canvas.getContext("2d");
var WhatUSeeWidth = document.getElementById("canvasLayer").width;
var WhatUSeeHeight = document.getElementById("canvasLayer").height;
var player = {
x : 0,
y : 0
}
function drawBackground() {
for (i = 0; i < 100; i ++) {
if (i % 2) {
context.fillStyle = "red";
}
else {
context.fillStyle = "blue";
}
context.fillRect(0, i * 100, 500, 100);
}
}
function playerMove() {
context.beginPath();
var radius = 5;
context.arc(player.x, player.y, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'green';
context.fill();
context.lineWidth = 1;
context.strokeStyle = '#003300';
context.stroke();
}
setInterval(tick, 100);
function tick() {
context.clearRect(0, 0, canvas.width, canvas.height);
drawBackground();
player.x++;
player.y++;
playerMove();
}
This is the JSFiddle.
EDIT WITH THE CORRECT ANSWER
The error is in the position of the object "player". It is located outside of the canvas, width:500 height:500 and the "player" is in position x:700 y:800.
Changing the position of the player your copy will appear.
var player = {
x : 50,
y : 50
}
Here the jsfiddle example.

Moving and rotating with HTML5

What needs to be done:
The pink object should move from the left to the right (by itself). And then when it's 5px from the edge it should rotate 90 degrees.
Does anyone know how to do this?
I haven't been learning javascript for a long time, and it's the first time I'm creating something using HTML5. So it's all new. I really hope you can help me understand the code better and how I can make it move and rotate.
<!DOCTYPE html>
<html>
<head>
<script>
var canvas, ctx;
window.onload = function draw() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var height = 90;
var width = 40;
var radius = width / 2;
ctx.clearRect(0,0, canvas.width, canvas.height);
ctx.fillStyle = "#FFE2E8";
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(20,20);
ctx.lineTo(70,20);
ctx.arc(70,40,20, -Math.PI/2, Math.PI/2);
ctx.lineTo(20,60);
ctx.lineTo(20,20);
ctx.closePath;
ctx.fill();
ctx.stroke();
requestAnimationFrame(draw);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
draw();
}
</script>
</head>
<body>
<canvas id="myCanvas" width="400" height="300" style="background:#00CC66">
</canvas>
</body>
</html>
var canvas, ctx;
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
var radius = 20;
var width = 70;
var margin = 5;
var offsetx = -20
var translate = {
x: 0,
y: 0,
xmax: canvas.width - margin - width + offsetx,
ymax: canvas.height - margin - width
};
var rotate = 0;
var to_radians = Math.PI / 180;
function draw() {
ctx.save();
ctx.translate(translate.x, translate.y);
if (translate.x >= translate.xmax) {
translate.x = translate.xmax;
if (rotate >= 90) {
rotate = 90;
} else {
rotate++;
}
ctx.rotate(rotate * to_radians);
} else {
translate.x++;
}
var height = 90;
var width = 40;
var radius = width / 2;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#FFE2E8";
ctx.strokeStyle = "black";
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(70, 20);
ctx.arc(70, 40, 20, -Math.PI / 2, Math.PI / 2);
ctx.lineTo(20, 60);
ctx.lineTo(20, 20);
ctx.closePath;
ctx.fill();
ctx.stroke();
ctx.restore();
requestAnimationFrame(draw);
}
function init() {
canvas = document.getElementById("myCanvas");
ctx = canvas.getContext("2d");
draw();
}
init();
<canvas id="myCanvas" width="400" height="300" style="background:#00CC66">
</canvas>

Animation canvas

I have a rectangle (which should appear) on a canvas, that I want to move from side to side of the canvas. The code I have atm however isn't working, as nothing is showing up at all! Any help would be appreciated, cheers!
<!DOCTYPE html>
<html>
<head>
<title>Simple animations in HTML5</title>
<!--<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "blue";
context.fillRect (20, 50, 200, 100);
</script> -->
<script>
function drawMessage()
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "blue";
context.fillRect(x, y, WIDTH, HEIGHT);
context.fillStyle = "white";
context.font = "30px Arial";
context.fillText ("Hello World", MESSAGE_WIDTH, MESSAGE_HEIGHT);
x += dx;
y += dy;
if(x <= 0 || x >= 500)
{
dx = -dx;
}
if(y <= 0 || y >= 200)
{
dy = -dy
}
function animate()
{
return setInterval(drawMessage, 10);
}
</script>
</head>
<body>
<h2> Optical Illusion </h2>
<video id="illusion" width="640" height="480" controls>
<source src="Illusion_movie.ogg">
</video>
<div id="buttonbar">
<button onclick="changeSize()">Big/Small</button>
</div>
<p>
Watch the animation for 1 minute, staring at the centre of the image. Then look at something else near you.
For a few seconds everything will appear to distort.
Source: Wikipedia:Illusion movie
</p>
<script type="text/javascript">
var myVideo=document.getElementById("illusion");
var littleSize = false;
function changeSize()
{
myVideo.width = littleSize ? 800 : 400;
littleSize = !littleSize;//toggle boolean
}
</script>
<canvas id="myCanvas" width="500" height="500">
</canvas>
<!--<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "blue";
context.fillRect(20, 50, 200, 100);
context.fillStyle = "white";
context.font = "30px Arial";
context.fillText ("Hello World", 35, 110);
</script> -->
<script>
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var x = 20; // x coordinate of box position
var y = 50; // y coordinate of box position
var dx = 2; // amount to move box to the right
var dy = 4; // amount to move box down
var WIDTH = 500; // width of canvas
var HEIGHT = 200; // height of canvas
var MESSAGE_WIDTH = 200; // width of message
var MESSAGE_HEIGHT = 100; // height of message
animate(); // run the animation
</script>
</body>
</html>
It seems to me like the first script portion of your code might be missing curly braces.
Specifically, the portion:
function drawMessage()
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "blue";
context.fillRect(x, y, WIDTH, HEIGHT);
context.fillStyle = "white";
context.font = "30px Arial";
context.fillText ("Hello World", MESSAGE_WIDTH, MESSAGE_HEIGHT);
x += dx;
y += dy;
if(x <= 0 || x >= 500)
{
dx = -dx;
}
if(y <= 0 || y >= 200)
{
dy = -dy
}
Might work better as:
function drawMessage()
{
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
context.fillStyle = "blue";
context.fillRect(x, y, WIDTH, HEIGHT);
context.fillStyle = "white";
context.font = "30px Arial";
context.fillText ("Hello World", MESSAGE_WIDTH, MESSAGE_HEIGHT);
x += dx;
y += dy;
if(x <= 0 || x >= 500)
{
dx = -dx;
}
if(y <= 0 || y >= 200)
{
dy = -dy
}
}

Categories

Resources