Why I'm getting only one rectangle? - javascript

let canvas, ctx, W, H;
canvas = document.createElement('canvas');
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
let objArr = [];
const init = () => {
canvas.width = W = innerWidth;
canvas.height = H = innerHeight;
canvas.style.background = '#dedfda';
for (let i = 0; i <= 5; i++) {
let r = (i + 1) * 20;
objArr.push(new Rectangle(W / 2, H / 2, 10, 10, "red", innerWidth / 2, innerHeight / 2, r));
objArr[0].draw();
}
animate();
}
const random = (min = 0, max = 1) => Math.random() * (max - min) + min;
class Rectangle {
constructor(posX, posY, w, h, color, cx, cy, r) {
this.posX = posX;
this.posY = posY;
this.w = w;
this.h = h;
this.color = color;
this.cx = cx;
this.cy = cy;
this.r = r;
this.angle = 0;
}
draw() {
ctx.clearRect(0, 0, innerWidth, innerHeight);
ctx.fillStyle = this.color;
ctx.fillRect(this.posX, this.posY, this.w, this.h);
}
update() {
this.angle += 0.1;
this.posX = this.cx + this.r * Math.cos(this.angle);
this.posY = this.cy + this.r * Math.sin(this.angle);
this.draw();
}
}
const animate = () => {
objArr.forEach(e => {
e.update();
})
requestAnimationFrame(animate);
}
window.onload = init;
In this code, I'm expecting an output having 5 rectangles revolving around the center point of the window in different radius like the planets revolving around the Sun in solar system.
But I am getting only one rectangle and it's not even revolving.
Stucked and not getting why it's not working.

Your draw function is clearing every time and you are only referencing the first element of the array. Adjusting for both shows 6 objects revolving. Your loop runs from 0 to 5. If you want 5 objects, you'll need to set the upper bound to 4 instead.
let canvas, ctx, W, H;
canvas = document.createElement('canvas');
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
let objArr = [];
const init = () => {
canvas.width = W = innerWidth;
canvas.height = H = innerHeight;
canvas.style.background = '#dedfda';
// adjusted range
for (let i = 0; i <= 4; i++) {
let r = (i + 1) * 20;
objArr.push(new Rectangle(W / 2, H / 2, 10, 10, "red", innerWidth / 2, innerHeight / 2, r));
objArr[i].draw();
}
animate();
}
const random = (min = 0, max = 1) => Math.random() * (max - min) + min;
class Rectangle {
constructor(posX, posY, w, h, color, cx, cy, r) {
this.posX = posX;
this.posY = posY;
this.w = w;
this.h = h;
this.color = color;
this.cx = cx;
this.cy = cy;
this.r = r;
this.angle = 0;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.posX, this.posY, this.w, this.h);
}
update() {
this.angle += 0.1;
this.posX = this.cx + this.r * Math.cos(this.angle);
this.posY = this.cy + this.r * Math.sin(this.angle);
this.draw();
}
}
const animate = () => {
// moved clear here to happen just once on each animate
ctx.clearRect(0, 0, innerWidth, innerHeight);
objArr.forEach(e => {
e.update();
})
requestAnimationFrame(animate);
}
window.onload = init;

You are just drawing one rectangle. Pay attention to
objArr[0].draw()
Which should be
objArr[i].draw()
Also, I think everytime an Rectange object's draw method is called the whole canvas is cleared in this line
ctx.clearRect(0, 0, innerWidth, innerHeight);
Hence, only one rectangle appears at all times.
A solution would be to move the calls to clearRect and update from Rectangle to the animate function. This way it fits better with the program logic. A Rectangle being an object should only know how to draw itself not clearing the canvas and updating its position on the canvas.
Below is my solution.
let canvas, ctx, W, H;
canvas = document.createElement('canvas');
document.body.appendChild(canvas);
ctx = canvas.getContext('2d');
let objArr = [];
const init = () => {
canvas.width = W = innerWidth;
canvas.height = H = innerHeight;
canvas.style.background = '#dedfda';
for (let i = 0; i <= 5; i++) {
let r = (i + 1) * 20;
objArr.push(new Rectangle(W / 2, H / 2, 10, 10, "red", innerWidth / 2, innerHeight / 2, r));
objArr[i].draw();
}
animate();
}
const random = (min = 0, max = 1) => Math.random() * (max - min) + min;
class Rectangle {
constructor(posX, posY, w, h, color, cx, cy, r) {
this.posX = posX;
this.posY = posY;
this.w = w;
this.h = h;
this.color = color;
this.cx = cx;
this.cy = cy;
this.r = r;
this.angle = 0;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.posX, this.posY, this.w, this.h);
}
// Should be moved outside of this class.
update() {
this.angle += 0.1;
this.posX = this.cx + this.r * Math.cos(this.angle);
this.posY = this.cy + this.r * Math.sin(this.angle);
ctx.fillRect(this.posX, this.posY, this.w, this.h)
}
}
const animate = () => {
ctx.clearRect(0, 0, innerWidth, innerHeight);
objArr.forEach(e => {
e.update();
})
requestAnimationFrame(animate);
}
window.onload = init;

Related

Javascript Game: How to generate enemies (images) from an array

I was successful in generating enemies (out of one image) with an array, however, I'm stuck in trying to generate enemies out of more than one image (e. g. 5 different images, thus 5 different enemies)
Here is my code that works:
Enemies (enemyImg - one image) are generated
/** #type {HTMLCanvasElement} */
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const backgroundImg = document.getElementById("background");
const playerImg = document.getElementById("player");
const enemyImg = document.getElementById("enemy");
canvas.width = 800;
canvas.height = 500;
const enemies = [];
class Enemy {
constructor(x, y, w, h, speed) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speed = speed;
}
draw() {
ctx.drawImage(enemyImg, this.x, this.y, this.w, this.h);
}
update() {
this.x = this.x - this.speed;
}
}
function spawnEnemies() {
setInterval(() => {
let w = 100;
let h = 40;
let x = canvas.width;
let y = Math.random() * Math.abs(canvas.height - h);
let speed = 5;
enemies.push(new Enemy(x, y, w, h, speed));
}, 1000);
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
enemies.forEach((enemy) => {
enemy.draw();
enemy.update();
});
}
animate();
spawnEnemies();
Here is the code, that does not work. I do not get any error message at all:
I have 6 images in one folder, named enemy_1.png to enemy_6.png) and I want them to be generated;
/** #type {HTMLCanvasElement} */
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const backgroundImg = document.getElementById("background");
const playerImg = document.getElementById("player");
const enemyImg = document.getElementById("enemy");
canvas.width = 800;
canvas.height = 500;
let enemies = [];
class Enemy {
constructor(img, x, y, w, h, speed) {
this.img = img;
(this.x = x),
(this.y = y),
(this.w = w),
(this.h = h),
(this.speed = speed);
}
draw() {
ctx.drawImage(img, this.x, this.y, this.w, this.h);
}
move() {
this.x = this.x - this.speed;
}
}
function createEnemies() {
setInterval(() => {
let w = 40;
let h = 72;
let x = 300;
let y = Math.random() * Math.abs(canvas.height - h);
let speed = 5;
enemies.length = 6;
for (let i = 1; i < enemies.length; i++) {
enemies[i] = new Image();
enemies[i].src = "./images/enemy_" + i + ".png";
enemies.push(new Enemy(enemies[i], x, y, w, h, speed));
}
}, 2000);
}
function createGame() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
enemies.forEach((enemy) => {
enemy.draw();
enemy.move();
});
requestAnimationFrame(createGame);
}
createGame();
createEnemies();
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const backgroundImg = document.createElement('img');
const playerImg = document.createElement('img');
canvas.width = 500;
canvas.height = 200;
// load your images:
const imagesCount = 0; // I have not this images, so its zero for me
const enemyImages = [];
for (let i = 1; i < imagesCount; i++) {
const img = new Image();
img.src = "./images/enemy_" + i + ".png";
enemyImages.push(img);
}
// I have not your images so i take some random pictures:
const enemyImage1 = new Image();
enemyImage1.src = 'https://pngimg.com/uploads/birds/birds_PNG106.png';
const enemyImage2 = new Image();
enemyImage2.src = 'https://purepng.com/public/uploads/large/purepng.com-magpie-birdbirdsflyanimals-631522936729bqeju.png';
const enemyImage3 = new Image();
enemyImage3.src = 'https://www.nsbpictures.com/wp-content/uploads/2018/10/birds-png.png';
enemyImages.push(
enemyImage1,
enemyImage2,
enemyImage3,
);
const enemies = [];
class Enemy {
constructor(x, y, w, h, speed, img) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.speed = speed;
// Self image:
this.img = img;
}
draw() {
// Draw self image:
ctx.drawImage(this.img, this.x, this.y, this.w, this.h);
}
update() {
this.x = this.x - this.speed;
}
}
function spawnEnemies() {
setInterval(() => {
let w = 60;
let h = 50;
let x = canvas.width;
let y = Math.random() * Math.abs(canvas.height - h);
let speed = 5;
enemies.push(new Enemy(x, y, w, h, speed,
// Pick random image from array:
enemyImages[Math.floor(Math.random()*enemyImages.length)]
));
}, 1000);
}
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(0, 0, canvas.width, canvas.height);
enemies.forEach((enemy) => {
enemy.draw();
enemy.update();
});
}
animate();
spawnEnemies();
<canvas id=canvas></canvas>

Display incrementing values

I have succeeded in making an animation with multiple circular progress bars, but now there is a problem to display; each percent of that values incrementing in the middle of my circles. I don't know how to do this. If you have ideas which help me to do that. I would like to display all of these values.
Here is my code:
class GreyCircle {
constructor(x, y, radius) {
this.posX = x;
this.posY = y;
this.radius = radius;
}
drawing1(context, startAngle, endAngle) {
/*grey circle*/
context.beginPath();
context.arc(this.posX, this.posY, this.radius, startAngle, endAngle, false);
context.strokeStyle = '#f3f3f3';
context.lineWidth = '20';
context.stroke();
}
}
class BlueCircle {
constructor(x, y, r) {
this.posX = x;
this.posY = y;
this.radius = r;
}
drawing2(context, percent) {
let unitValue = (Math.PI - 0.5 * Math.PI) / 25;
let startAngle = 0;
let endAngle = startAngle + (percent * unitValue);
let arcInterval = setInterval(() => {
startAngle += .1;
percentText.textContent = startAngle + unitValue;
/*blue circle*/
context.beginPath();
context.arc(this.posX, this.posY, this.radius, startAngle, startAngle + unitValue, false);
context.strokeStyle = '#f39c12';
context.lineWidth = '20';
context.stroke();
context.lineCap = 'round';
if (startAngle >= endAngle) {
clearInterval(arcInterval);
}
}, 50);
}
}
function setup() {
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
/*draw the grey circles*/
let greyCircle1 = new GreyCircle(150, 200, 100);
greyCircle1.drawing1(context, 0, 2 * Math.PI);
let greyCircle2 = new GreyCircle(400, 200, 100);
greyCircle2.drawing1(context, 0, 2 * Math.PI);
let greyCircle3 = new GreyCircle(650, 200, 100);
greyCircle3.drawing1(context, 0, 2 * Math.PI);
/*draw the blue circles*/
let blueCircle1 = new BlueCircle(150, 200, 100);
blueCircle1.drawing2(context, 80);
let blueCircle2 = new BlueCircle(400, 200, 100);
blueCircle2.drawing2(context, 76)
let blueCircle3 = new BlueCircle(650, 200, 100);
blueCircle3.drawing2(context, 44);
}
window.onload = function() {
setup();
}
#canvas {
position: relative;
margin: auto;
display: block;
}
#percentText {
position: absolute;
top: 50%;
left: 50;
}
<section id="skills">
<div class="load-container">
<canvas id="canvas" width="800" height="800"></canvas>
<span id="percentText">%</span>
</div>
</section>
Not exactly sure, what are you trying to accomplish, but if you want to print the text with fixed percentage, you could do something like this:
class GreyCircle
{
constructor(x, y, radius) {
this.posX = x;
this.posY = y;
this.radius = radius;
}
drawing1(context, startAngle, endAngle)
{
/*grey circle*/
context.beginPath();
context.arc(this.posX, this.posY, this.radius, startAngle, endAngle, false);
context.strokeStyle = '#f3f3f3';
context.lineWidth = '20';
context.stroke();
}
}
class BlueCircle
{
constructor(x, y, r)
{
this.posX = x;
this.posY = y;
this.radius = r;
}
drawing2(context, percent)
{
let unitValue = (Math.PI - 0.5 * Math.PI) / 25;
let startAngle = 0;
let endAngle = startAngle + (percent * unitValue);
var m = context.measureText(percent + "%");
context.save();
context.font = "20px Verdana"
context.fillText(percent + "%", this.posX - this.radius + (this.radius - m.width), this.posY + 10);
context.restore();
let arcInterval = setInterval(() => {
startAngle += .1;
/*blue circle*/
context.beginPath();
context.arc(this.posX, this.posY, this.radius, startAngle, startAngle + unitValue, false);
context.strokeStyle = 'blue';
context.lineWidth = '20';
context.stroke();
context.lineCap = 'round';
if (startAngle >= endAngle) {
clearInterval(arcInterval);
}
}, 50);
}
}
function setup()
{
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let percentText = document.getElementById('percentText');
/*draw the grey circles*/
let greyCircle1 = new GreyCircle(150, 200, 100);
greyCircle1.drawing1(context, 0, 2 * Math.PI);
let greyCircle2 = new GreyCircle(400, 200, 100);
greyCircle2.drawing1(context, 0, 2 * Math.PI);
let greyCircle3 = new GreyCircle(650, 200, 100);
greyCircle3.drawing1(context, 0, 2 * Math.PI);
/*draw the blue circles*/
let blueCircle1 = new BlueCircle(150, 200, 100);
blueCircle1.drawing2(context, 80);
let blueCircle2 = new BlueCircle(400, 200, 100);
blueCircle2.drawing2(context, 76)
let blueCircle3 = new BlueCircle(650, 200, 100);
blueCircle3.drawing2(context, 44);
}
window.onload = function ()
{
setup();
}
<canvas id="canvas" width="1920" height="1080">
But if you wanted the percentage to update with the loading, you would have to put the printing of the text inside the loop. Something like this:
class GreyCircle
{
constructor(x, y, radius) {
this.posX = x;
this.posY = y;
this.radius = radius;
}
drawing1(context, startAngle, endAngle)
{
/*grey circle*/
context.beginPath();
context.arc(this.posX, this.posY, this.radius, startAngle, endAngle, false);
context.strokeStyle = '#f3f3f3';
context.lineWidth = '20';
context.stroke();
}
}
class BlueCircle
{
constructor(x, y, r)
{
this.posX = x;
this.posY = y;
this.radius = r;
}
drawing2(context, percent)
{
let unitValue = (Math.PI - 0.5 * Math.PI) / 25;
let startAngle = 0;
let endAngle = startAngle + (percent * unitValue);
let arcInterval = setInterval(() => {
startAngle += .1;
/*blue circle*/
context.beginPath();
context.arc(this.posX, this.posY, this.radius, startAngle, startAngle + unitValue, false);
context.strokeStyle = 'blue';
context.lineWidth = '20';
context.stroke();
context.lineCap = 'round';
var percentNow = Math.round(percent * startAngle/endAngle)
var m = context.measureText(percentNow + " %");
context.save();
context.clearRect(this.posX - this.radius + (this.radius - m.width), this.posY - 10, m.width * 3, 20)
context.font = "20px Verdana"
context.fillText(percentNow + " %", this.posX - this.radius + (this.radius - m.width), this.posY + 10);
context.restore();
if (startAngle >= endAngle) {
clearInterval(arcInterval);
}
}, 50);
}
}
function setup()
{
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
let percentText = document.getElementById('percentText');
/*draw the grey circles*/
let greyCircle1 = new GreyCircle(150, 200, 100);
greyCircle1.drawing1(context, 0, 2 * Math.PI);
let greyCircle2 = new GreyCircle(400, 200, 100);
greyCircle2.drawing1(context, 0, 2 * Math.PI);
let greyCircle3 = new GreyCircle(650, 200, 100);
greyCircle3.drawing1(context, 0, 2 * Math.PI);
/*draw the blue circles*/
let blueCircle1 = new BlueCircle(150, 200, 100);
blueCircle1.drawing2(context, 80);
let blueCircle2 = new BlueCircle(400, 200, 100);
blueCircle2.drawing2(context, 76)
let blueCircle3 = new BlueCircle(650, 200, 100);
blueCircle3.drawing2(context, 44);
}
window.onload = function ()
{
setup();
}
<canvas id="canvas" width="1920" height="1080">

removing the js script from html page

<!DOCTYPE html5>
<html>
<head>
<title>disturbed</title>
<script>
window.onload = function() {
// create the canvas
var canvas = document.createElement("canvas"),
c = canvas.getContext("2d");
var particles = {};
var particleIndex = 0;
var particleNum = 15;
// set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// add canvas to body
document.body.appendChild(canvas);
// style the canvas
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.3;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;
this.maxLife = Math.random() * 30 + 60;
this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
}
Particle.prototype.draw = function() {
this.x += this.vx;
this.y += this.vy;
if (Math.random() < 0.1) {
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
}
this.life++;
if (this.life >= this.maxLife) {
delete particles[this.id];
}
c.fillStyle = this.color;
//c.fillRect(this.x, this.y, 5, 10);
c.beginPath();
c.arc(this.x, this.y, 2.5, 0, 2 * Math.PI);
c.fill();
};
setInterval(function() {
//normal setting before drawing over canvas w/ black background
c.globalCompositeOperation = "source-over";
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particleNum; i++) {
new Particle();
}
// c.globalCompositeOperation = "darken";
for (var i in particles) {
particles[i].draw();
}
}, 30);
};
</script>
</head>
<body>
</body>
</html>
The code below is all correct but its just two densed i want to make it easier and not to populated . what i want to do is make the script that i have into a separate file like "anything.js" so that i can load it into my html main file by just calling out the main functions like particle() in ,window.onload = function() which will be on the main page .
The reason is because i want to add this script to many html pages and i dont want to copy all of the lengthy script in to my code again and again .
Please answer this , it would be really helful.
HTML :
<!DOCTYPE html5>
<html>
<head>
<title>disturbed</title>
</head>
<body>
<script src="toto.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function() {
Particle();
};
</script>
</body>
</html>
toto.js :
//create the canvas
var canvas = document.createElement("canvas"),
c = canvas.getContext("2d");
var particles = {};
var particleIndex = 0;
var particleNum = 15;
// set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// add canvas to body
document.body.appendChild(canvas);
// style the canvas
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
function Particle() {
this.x = canvas.width / 2;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.3;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;
this.maxLife = Math.random() * 30 + 60;
this.color = "hsla(" + parseInt(Math.random() * 360, 10) + ",90%,60%,0.5";
}
Particle.prototype.draw = function() {
this.x += this.vx;
this.y += this.vy;
if (Math.random() < 0.1) {
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
}
this.life++;
if (this.life >= this.maxLife) {
delete particles[this.id];
}
c.fillStyle = this.color;
//c.fillRect(this.x, this.y, 5, 10);
c.beginPath();
c.arc(this.x, this.y, 2.5, 0, 2 * Math.PI);
c.fill();
};
setInterval(function() {
//normal setting before drawing over canvas w/ black background
c.globalCompositeOperation = "source-over";
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < particleNum; i++) {
new Particle();
}
// c.globalCompositeOperation = "darken";
for (var i in particles) {
particles[i].draw();
}
}, 30);
I see you have a scope issue.
Variables are passed from script to script. However, in your case, you declare Particle inside window.onload so it only gets defined inside it and you can't use it elsewhere.
The right way to export your script into a separate file would be to declare Particle in the scope of the whole script, as in:
// anything.js
function Particle() {
...
}
Note that you'd need a bit of rewriting, since I can see that you use variables like canvas (which are only defined in the scope of window.onload) inside Particle's code.

Canvas line drawing animation

I am new learner of animation using HTML5 Canvas. I am struggling to create line drawing animation in a canvas with desired length of a line.
Here is the code
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
width = canvas.width = window.innerWidth,
height = canvas.height = window.innerHeight;
var x = 200;
var y = 200;
draw();
update();
function draw() {
context.beginPath();
context.moveTo(100, 100);
context.lineTo(x, y);
context.stroke();
}
function update() {
context.clearRect(0, 0, width, height);
x = x + 1;
y = y + 1;
draw();
requestAnimationFrame(update);
}
html,
body {
margin: 0px;
}
canvas {
display: block;
}
<canvas id="canvas"></canvas>
The line is growing on Canvas in the above code. But how to achieve that the 200px wide line and animate the movement in x and y direction. And the same animation with multiple lines using for loop and move them in different direction.
Check the reference image ....
Need to move each line in a different direction
Thanks in advance
Find a new reference image which i want to achieve
You need to either use transforms or a bit of trigonometry.
Transforms
For each frame:
Reset transforms and translate to center
Clear canvas
Draw line from center to the right
Rotate x angle
Repeat from step 2 until all lines are drawn
var ctx = c.getContext("2d");
var centerX = c.width>>1;
var centerY = c.height>>1;
var maxLength = Math.min(centerX, centerY); // use the shortest direction for demo
var currentLength = 0; // current length, for animation
var lenStep = 1; // "speed" of animation
function render() {
ctx.setTransform(1,0,0,1, centerX, centerY);
ctx.clearRect(-centerX, -centerY, c.width, c.height);
ctx.beginPath();
for(var angle = 0, step = 0.1; angle < Math.PI * 2; angle += step) {
ctx.moveTo(0, 0);
ctx.lineTo(currentLength, 0);
ctx.rotate(step);
}
ctx.stroke(); // stroke all at once
}
(function loop() {
render();
currentLength += lenStep;
if (currentLength < maxLength) requestAnimationFrame(loop);
})();
<canvas id=c></canvas>
You can use transformation different ways, but since you're learning I kept it simple in the above code.
Trigonometry
You can also calculate the line angles manually using trigonometry. Also here you can use different approaches, ie. if you want to use delta values, vectors or brute force using the math implicit.
For each frame:
Reset transforms and translate to center
Clear canvas
Calculate angle and direction for each line
Draw line
var ctx = c.getContext("2d");
var centerX = c.width>>1;
var centerY = c.height>>1;
var maxLength = Math.min(centerX, centerY); // use the shortest direction for demo
var currentLength = 0; // current length, for animation
var lenStep = 1; // "speed" of animation
ctx.setTransform(1,0,0,1, centerX, centerY);
function render() {
ctx.clearRect(-centerX, -centerY, c.width, c.height);
ctx.beginPath();
for(var angle = 0, step = 0.1; angle < Math.PI * 2; angle += step) {
ctx.moveTo(0, 0);
ctx.lineTo(currentLength * Math.cos(angle), currentLength * Math.sin(angle));
}
ctx.stroke(); // stroke all at once
}
(function loop() {
render();
currentLength += lenStep;
if (currentLength < maxLength) requestAnimationFrame(loop);
})();
<canvas id=c></canvas>
Bonus animation to play around with (using the same basis as above):
var ctx = c.getContext("2d", {alpha: false});
var centerX = c.width>>1;
var centerY = c.height>>1;
ctx.setTransform(1,0,0,1, centerX, centerY);
ctx.lineWidth = 2;
ctx.strokeStyle = "rgba(0,0,0,0.8)";
ctx.shadowBlur = 16;
function render(time) {
ctx.globalAlpha=0.77;
ctx.fillRect(-500, -500, 1000, 1000);
ctx.globalAlpha=1;
ctx.beginPath();
ctx.rotate(0.025);
ctx.shadowColor = "hsl(" + time*0.1 + ",100%,75%)";
ctx.shadowBlur = 16;
for(var angle = 0, step = Math.PI / ((time % 200) + 50); angle < Math.PI * 2; angle += step) {
ctx.moveTo(0, 0);
var len = 150 + 150 * Math.cos(time*0.0001618*angle*Math.tan(time*0.00025)) * Math.sin(time*0.01);
ctx.lineTo(len * Math.cos(angle), len * Math.sin(angle));
}
ctx.stroke();
ctx.globalCompositeOperation = "lighter";
ctx.shadowBlur = 0;
ctx.drawImage(ctx.canvas, -centerX, -centerY);
ctx.drawImage(ctx.canvas, -centerX, -centerY);
ctx.globalCompositeOperation = "source-over";
}
function loop(time) {
render(time);
requestAnimationFrame(loop);
};
requestAnimationFrame(loop);
body {margin:0;background:#222}
<canvas id=c width=640 height=640></canvas>
Here is what I think you are describing...
window.onload = function() {
var canvas = document.getElementById("canvas"),
context = canvas.getContext("2d"),
width = canvas.width = 400,
height = canvas.height = 220,
xcenter = 200,
ycenter = 110,
radius = 0,
radiusmax = 100,
start_angle1 = 0,
start_angle2 = 0;
function toRadians(angle) {
return angle * (Math.PI / 180);
}
function draw(x1, y1, x2, y2) {
context.beginPath();
context.moveTo(x1, y1);
context.lineTo(x2, y2);
context.stroke();
}
function drawWheel(xc, yc, start_angle, count, rad) {
var inc = 360 / count;
for (var angle = start_angle; angle < start_angle + 180; angle += inc) {
var x = Math.cos(toRadians(angle)) * rad;
var y = Math.sin(toRadians(angle)) * rad;
draw(xc - x, yc - y, xc + x, yc + y);
}
}
function update() {
start_angle1 += 0.1;
start_angle2 -= 0.1;
if(radius<radiusmax) radius++;
context.clearRect(0, 0, width, height);
drawWheel(xcenter, ycenter, start_angle1, 40, radius);
drawWheel(xcenter, ycenter, start_angle2, 40, radius);
requestAnimationFrame(update);
}
update();
};
html,
body {
margin: 0px;
}
canvas {
display: block;
}
<canvas id="canvas"></canvas>
This is one that is a variable length emerging pattern. It has a length array element for each spoke in the wheel that grows at a different rate. You can play with the settings to vary the results:
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
var width = canvas.width = window.innerWidth;
var height = canvas.height = window.innerHeight;
var xcenter = width/4;
var ycenter = height/2;
var radius;
var time;
if(width>height) {
radius = height*0.4;
}
else {
radius = width*0.4;
}
var start_angle1 = 0;
var start_angle2 = 0;
function toRadians (angle) {
return angle * (Math.PI / 180);
}
function draw(x1,y1,x2,y2) {
context.beginPath();
context.moveTo(x1,y1);
context.lineTo(x2,y2);
context.stroke();
}
var radmax=width;
var rads = [];
var radsinc = [];
function drawWheel(xc,yc,start_angle,count,rad) {
var inc = 360/count;
var i=0;
for(var angle=start_angle; angle < start_angle+180; angle +=inc) {
var x = Math.cos(toRadians(angle)) * rads[rad+i];
var y = Math.sin(toRadians(angle)) * rads[rad+i];
draw(xc-x,yc-y,xc+x,yc+y);
rads[rad+i] += radsinc[i];
if(rads[rad+i] > radmax) rads[rad+i] = 1;
i++;
}
}
function update() {
var now = new Date().getTime();
var dt = now - (time || now);
time = now;
start_angle1 += (dt/1000) * 10;
start_angle2 -= (dt/1000) * 10;
context.clearRect(0,0,width,height);
drawWheel(xcenter,ycenter,start_angle1,50,0);
drawWheel(xcenter,ycenter,start_angle2,50,50);
requestAnimationFrame(update);
}
function init() {
for(var i=0;i<100;i++) {
rads[i] = 0;
radsinc[i] = Math.random() * 10;
}
}
window.onload = function() {
init();
update();
};
html, body {
margin: 0px;
}
canvas {
width:100%;
height:200px;
display: block;
}
<canvas id="canvas"></canvas>

Constructor, loops and arrays practice in vanilla JS

I'm trying to make an animation where particles flow from one side the other like a flock of birds. You can see a live version on my semi-finished portfolio here: https://benjamingibbsportfolio.000webhostapp.com/
I'm in the process of learning constructor functions, so I've decided to redo the above project using that type of programming.
I've managed to basically complete it, apart from the fact it only displays one particle/flake - it should show 100?
for(var i = 0; i < 100; i++)
{
flakes[i] = new Flake();
}
Where have I gone wrong?
Are all the particles simply being drawn at the same place?
I've uploaded the code here: https://jsfiddle.net/q7ja8qxv/
A single flake is drawn with this function:
this.display = function() {
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "#ffff00";
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true);
ctx.fill();
}
The source of the problem is the first line of the function:
ctx.clearRect(0, 0, w, h);
This clears the whole canvas...
This means that every flake "erases" the previous flake(s).
As a fix you have to remove the ctx.clearRect() call from Flake.display() and instead call it in a place where it is only executed once, before you start drawing the flakes. For example in drawFlakes() right before the loop:
function drawFlakes() {
ctx.clearRect(0, 0, w, h);
for (i = 0; i < flakes.length; i++) {
flakes[i].display();
flakes[i].move();
flakes[i].update();
}
angle += 0.01;
}
Complete example:
var canvas = document.getElementById('stars');
var ctx = canvas.getContext('2d')
var w = window.innerWidth;
var h = window.innerHeight;
var flakes = [];
var angle = 0;
canvas.width = w;
canvas.height = h;
for (var i = 0; i < 20; i++) {
flakes[i] = new Flake();
}
function drawFlakes() {
ctx.clearRect(0, 0, w, h);
for (i = 0; i < flakes.length; i++) {
flakes[i].display();
flakes[i].move();
flakes[i].update();
}
angle += 0.01;
}
function Flake() {
this.x = Math.random() * w;
this.y = Math.random() * h;
this.r = Math.random() * 5 + 2;
this.d = Math.random() * 1;
this.display = function() {
ctx.fillStyle = "#ffff00";
ctx.beginPath();
ctx.moveTo(this.x, this.y);
ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, true);
ctx.fill();
}
this.move = function() {
this.y += Math.pow(this.d, 2) + 1;
this.x += Math.sin(angle) * 60;
};
this.update = function() {
if (this.y > h) {
this.x = Math.random() * w;
this.y = 0;
this.r = this.r;
this.d = this.d;
}
};
}
setInterval(drawFlakes, 25);
body {
background: black;
overflow: hidden;
}
<canvas id="stars"></canvas>

Categories

Resources