A simple program to display a rolling ball - javascript

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var canvas_variable;
var init_x = 200;
var init_y = 300;
var x_move = 1;
function initialize_canvas()
{setInterval(draw_ball, 10);
canvas_variable = bouncing_ball_canvas.getContext('2d');
}
function draw_ball()
{
canvas_variable.clearRect(0,0, 1000, 500);
canvas_variable.beginPath();
canvas_variable.fillStyle="#FF0000";
canvas_variable.arc(init_x, init_y, 50, 0+init_x/50, Math.PI*2+init_x/50, true);
canvas_variable.lineTo(init_x, init_y);
canvas_variable.stroke();
if( init_x<0 || init_x>1000) x_move = -x_move;
init_x += x_move;
}
</script>
</head>
<body>
<canvas id="bouncing_ball_canvas" width="1000" height="500">
</canvas>
<body onLoad="initialize_canvas();">
</body>
</html>
This is a program of a rolling ball. The function draw_ball is called after every 10 milliseconds.The ball blinks during its motion. What is the solution for this problem?

You forgot to declare the variable bouncing_ball_canvas
Try adding:
bouncing_ball_canvas = document.getElementById("bouncing_ball_canvas");
before you declare canvas_variable.
EDIT:
The problem lies in the line:
canvas_variable.arc(init_x, init_y, 50, 0+init_x/50, Math.PI*2+init_x/50, true);
Change the last variable to false and it should work.

It is blinking because your computation is wrong.
You need to compute the perimeter: 2*pi*r.
Then do a simple cross product:
distance = x
perimeter = 2*pi
So the angle (in radian) is distance*2*pi/perimeter
So try this:
const getAngle=function(distance) {
return distance*2*Math.PI/perimeter;
}
const getPos=function(x, y, angle, r) {
return [x + Math.cos(angle)*r, y + Math.sin(angle)*r];
}
canvas_variable.arc(init_x, init_y, 50, 0, Math.PI*2, true);
canvas_variable.moveTo(..getPos(init_x, init_y, getAngle(init_x-starting_x), r));
canvas_variable.lineTo(init_x, init_y);
canvas_variable.stroke();

Related

How to stop a rectangle from moving off of the canvas in Javascript using the p5 library

Here is my Javascript:
var x;
var y;
var ymod = 0;
function setup() {
createCanvas(600, 600);
x = 10;
y = 12;
}
function draw() {
background(48, 48, 48);
noStroke();
fill(255, 255, 255);
rect(x, y, 10, 30);
y = y + ymod;
}
function keyPressed() {
if (keyCode === UP_ARROW) {
ymod = -1;
} else if (keyCode === DOWN_ARROW) {
ymod = 1;
}
}
Here is my HTML:
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>Game</title>
<script src="libraries/p5.js" type="text/javascript"></script>
<script src="libraries/p5.dom.js" type="text/javascript"></script>
<script src="libraries/p5.sound.js" type="text/javascript"></script>
</head>
<body>
<script src="sketch.js" type="text/javascript"></script>
</body>
</html>
I would like the rectangle to stop when it hits the edges of the canvas (ie: y=0 and y=570). I have tried to add
if (y=0) {
ymod = 0;
}
to the end of the draw function but, it breaks everything.
This can be done using the constrain function in p5.js, to constrain y between 0 and 570, like this:
y = constrain(y, 0, 570);
The reason why if (y = 0) breaks everything is because a single equals sign sets y to 0 instead of comparing. To test if y = 0, you'll need to use a triple equals sign instead (y === 0).

ant't 'putImageData' with 'imagedata' from other canvas

I have two canvases on the same page, with different ids. I use the first canvas to draw Images and the second is like an album where you can see all of your paintings...... When I use var Img = painter.getImageData(0, 0, 100, 100) and album.putImageData(Img, 0, 0) it doesn't work. Plz help!
Code : (there may be some errors, because this is hand written write now, my original code is too long)
HTML :
<html>
<body>
<canvas id="album" width="1000" height="1000"></canvas>
<canvas id="painter" width="100" height="100" onclick="draw(event)"></canvas>
<button onclick="sub()">Submit to album</button>
</body>
</html>
JS :
var album = document.getElementById("ambum").getContext("2d");
var painter = document.getElementById("painter").getContext("2d");
var SRC = "";
function draw(evt) {
var X = evt.clientX;
var Y = evt.clientY;
painter.beginpath();
painter.fillStyle = "red";
painter.fillRect(X - 1000, Y, 100, 100);
}
function sub() {
var SRC = painter.getImageData(1000, 0, 100, 100);
album.beginPath();
album.putImageData(SRC, 0, 0);
}

Moving image in a circular path purely using JavaScript

How can I make the imageObject to move in a circular path? Or more specific, what are the mathematical formulas needed to make it do so?
I am required to use setInterval with a function that caluclates the new coordinates of the picture. setInterval is supposed to call the function at least 20 times a second.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Graphics and animation using HTML5 Canvas</title>
<style>
#the-canvas { border: 1px dashed gray }
</style>
<script>
addEventListener('load', function() {
var x = document.getElementById("the-canvas");
var y = x.getContext("2d");
var imageObject = new Image();
imageObject.onload = function() {
y.drawImage(imageObject, 100, 200);
};
imageObject.src = "image.jpg";
});
</script>
</head>
<body>
<canvas id="the-canvas" width="500" height="400">
Your browser does not support the <canvas> element.
</canvas>
</body>
</html>
Mathematical formulas needed would be cosine in one dimension and sine in the other.
Something like this:
addEventListener('load', function() {
var x = document.getElementById("the-canvas");
var y = x.getContext("2d");
var imageObject = new Image();
var step = 0, radius = 50, speed = 0.05;
function spin() {
y.clearRect(0, 0, x.width, x.height);
y.drawImage(imageObject, 100 + radius * Math.cos(speed * step), 200 + radius * Math.sin(speed * step));
++step;
}
imageObject.onload = function() {
y.drawImage(imageObject, 100, 200);
setInterval(spin, 50); // 20 fps
};
imageObject.src = "image.jpg";
});

Javascript canvas animating

I want to make a loading bar for my web application and I want to use a html canvas for this. This is the script that I use to fill up the canvas:
<script>
var canvas = document.getElementById("bar");
var c = canvas.getContext("2d");
var xPos = 0;
draw = function() {
if(xPos < 300){
c.rect(0, 0, xPos, 30);
c.fill(255,0,0);
xPos += 0.5;
}
};
</script>
I tested this code on a online code converter (khan academy) and it worked (of course without the first 2 lines and c. in front of most things), and that is also my trouble I don't know where I have to put c. in front of?
I simplified the page a little bit:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<canvas id="bar"></canvas>
<script>
var canvas = document.getElementById("bar");
var c = canvas.getContext("2d");
c.fillStyle = "#ff0000"
draw = function(){
if(xPos < 300){
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
}
};
</script>
</body>
</html>
Whatever you are trying to draw... this:
draw = function(){
if(xPos < 300) {
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
}
};
... it is a definition of variable in global context (context of window object), then assigning a function to it. That's all - it only defines the behavior.
What you need also needs to execute that (a sidenote: to execute it after the canvas is actually created - when you put code in a script tag after canvas tag - it's sufficient and you did it already).
To execute the function use:
draw();
Or don't wrap code in function at all (unless it's to be called multiple times).
Or use a syntax construct to execute the function created in place like this:
(draw = function(){
if(xPos < 300) {
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
setTimeout(draw,15); // use this to achieve animation effect
}
})();
var xPos = 0;
var canvas = document.getElementById("bar");
var c = canvas.getContext("2d");
c.fillStyle = "#FF0000";
var draw;
(draw = function(){
if(xPos < 300) {
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
setTimeout(draw,15);
}
})();
#bar {
width: 300px;
height: 50px;
}
<canvas id="bar"></canvas>
Edit: I've been thinking of what you might need, as it's not entirely abvious what you want. I have created this jsfiddle. Maybe it'll be of any help.
Hmmm...
You got some things mixed up. Try this:
<html>
<canvas id = "cvs1" width = "300" height = "30"></canvas>
</html>
And for the script:
var c = document.getElementById("cvs1").getContext("2d");
c.fillStyle = "#ff0000" //Set Fill Color(Set to red)
if(xPos < 300){
c.fillRect(xPos, 0, 30, 30);
xPos += 0.5;
}
If not:
What you did was use fill and rect seperately. You need to set the color, and then use the fillRect() function to draw the rectangle.
EDIT: You got the x,y,width,height as width,height,x,y. Fixed answer.
Good luck!
You need to call draw for every animation step. You could do this using setTimeout, setInterval or requestAnimationFrame :
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="test.css">
</head>
<body>
<canvas id="bar"></canvas>
<script>
var canvas = document.getElementById("bar");
var c = canvas.getContext("2d");
c.fillStyle = "#ff0000";
xPos=0;
draw = function(){
if(xPos < 300){
c.fillRect(0, 0, xPos, 30);
xPos += 0.5;
requestAnimationFrame(draw);
}
};
requestAnimationFrame(draw);
</script>
</body>
</html>

canvas animation javascript functions and global variables

Please, may someone help me! I am new in javascript.
I want to make canvas animation using javascript. But I have the following error
SCRIPT5007: Unable to get value of the property 'getContext': object
is null or undefined drawing_script.js, line 31 character 5
Here is the code.
Javascript:
// JScript source code
/*
Because the canvas can hold only one context at time, we'll create two canvas. Each one with its context.
One canvas for the circle, and another one for the square.
*/
var canvasCircle;
var contextCircle;
var x = 400;
var y = 300;
var dx = 2;
var WIDTH = 800;
var HEIGHT = 600;
// the circle wont make any transsformation.
function draw_circle(x, y, r) {
contextCircle.beginPath();
contextCircle.arc(x, y, r, 0, 2 * Math.PI, true);
contextCircle.closePath();
contextCircle.stroke();
}
function clear_canvas() {
contextCircle.clearRect(0, 0, WIDTH, HEIGHT);
}
function init() {
//canvasCircle = document.getElementById("canvas_circle");
canvasCircle = document.getElementById("canvas_circle");
contextCircle = canvasCircle.getContext('2d');
return setInterval(draw, 10);
}
function draw() {
// clear_canvas();
draw_circle(x, y, 50);
// if (x + dx > WIDTH || x + dx < 0)
// dx = -dx;
// x += dx;
}
init();
HTML5:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="Scripts/drawing_script.js" language="javascript"></script>
<title>Blackberry</title>
</head>
<body>
<div class="drawing" style="background:Green">
<canvas id="canvas_circle" width="800" height="600"></canvas>
This is happening because your executing the script before you create the canvas.
Create the canvas element FIRST then embed the javascript.
IE: canvasCircle is undefined because you can't get an element by ID that does not exist yet!
I found the answer: the init() should be
function init() {
s_canvas = document.getElementById("canvas_square");
// Check if the canvas is supported and if the getContext is available
if (s_canvas && s_canvas.getContext) {
s_context = s_canvas.getContext("2d");
return setInterval(draw, 10);
}
else {
alert("Canvas is not supported!");
}
}
And the called of init() is replace with window.onload=init.
Since you said that you are new to javascript, I believe that the problem could be that the browser on which you are running the code may not be supporting canvas.

Categories

Resources