JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<canvas></canvas>
</body>
JavaScript
//object to be part of a linked list. Source of error?
var particle = function(ctx, next){
this.next = next;
this.x = Math.random()*300;
this.y = 0;
this.ctx = ctx;
this.animate = function(){
//increments y position
this.y += 5;
this.ctx.rect(this.x, this.y, 8, 8);
this.ctx.stroke();
if(this.next != 0){
//removes objects too far down (higher y than canvas height)
if(this.next.y>=ctx.canvas.height)
this.next = this.next.next;
//calls next object's animate() function
if(this.next != 0){
this.next.animate();
}
}
}
}
var c = document.getElementsByTagName("canvas")[0];
c.width = 300;
c.height = 300;
var cc = c.getContext("2d");
var p = new particle(cc, 0);
//sets "anchor" of particles to -100 so it won't visibly render
p.x = -100;
//gets looped:
animate();
cc.fillStyle = "rgb(255, 255, 255)";
function animate(){
/*draws a rectangle to the canvas that DOES NOT overwrite the
rectangles drawn from within the
particle objects' animate() function'
BUG? Error? What am I missing.
*/
cc.fillStyle = "rgb(255, "+(156+Math.floor(Math.random()*100))+", 0)";
cc.fillRect(0, 0, c.width, c.height)
//calls the "anchor's" animate function
if(p.next !=0)
p.animate();
//loopy enough for this purpose
setTimeout(animate, 100);
}
//create a new object as the first after the anchor, copies (manually) the object currently pointed at into the new object's next, or, if non-existent, writes 0
document.addEventListener('mousedown', function(e){
if(p.next != 0){
var placeholder = new particle(p.next.ctx, p.next.next);
p.next = new particle(cc, new particle(placeholder.ctx, placeholder.next));
}else{
p.next = new particle(cc, 0);
}
}, false);