mousemove event not working like expected in Javascript - javascript

I have some code below for the start of a snake game that I'm making using HTML5 canvas. For some reason, the red circle that I'm temporarily using to represent my snake is drawing constantly following the path the mouse moves in. and it uses the food as a starting point. Check it out in your browser, because it's really hard to describe. All I want is for the circle to follow the mouse and leave a small trail that ends and doesn't stay on the canvas. How would I go about doing this. Thanks in advance!
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Snake 2.0</title>
</head>
<style>
</style>
<body>
<div>
<canvas id="canvas" width=500 height=500></canvas>
</div>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
makeFood();
function makeFood() {
foods = [];
for (var i = 0; i < 1; i++){
foods.push(new Food());
}
}
function Food() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = 10;
}
function drawFood() {
for (var i = 0; i < 1; i++){
foods.push(new Food());
}
for (var i = 0; i < foods.length; i++){
var f = foods[i];
context.beginPath();
var grd = context.createRadialGradient(f.x, f.y, (f.radius - (f.radius - 1)), f.x + 1, f.y + 1, (f.radius));
grd.addColorStop(0, 'red');
grd.addColorStop(1, 'blue');
context.arc(f.x, f.y, f.radius, 0, 2 * Math.PI, true);
context.fillStyle = grd;
context.fill();
}
}
function makePower() {
powers = [];
for (var i = 0; i < 1; i++){
powers.push(new Power());
}
}
function Power() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = 8;
}
function drawPower() {
for (var i = 0; i < powers.length; i++){
var p = powers[i];
context.beginPath();
var grd = context.createRadialGradient(p.x, p.y, (p.radius - (p.radius - 1)), p.x + 1, p.y + 1, (p.radius));
grd.addColorStop(0, 'green');
grd.addColorStop(1, 'yellow');
context.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true);
context.fillStyle = grd;
context.fill();
}
}
canvas.addEventListener("mousemove", function(event) {
move(event);
});
function move(e) {
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
var a = e.clientX;
var b = e.clientY;
context.arc(a, b, 20, 0, 2 * Math.PI, true);
context.fillStyle = "red";
context.fill();
}
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
var functions = [drawFood];
var timer = setInterval(function(){
drawFood();
}, 5000);
function stop() {
clearInterval(timer);
}
canvas.addEventListener("click", stop);
//timer = setInterval(start, 1000);
//timer = setInterval(start, 5000);
</script>
</body>
</html>

You could start by adding "context.beginPath();" in your "move" function, before "context.arc(a, b, 20, 0, 2 * Math.PI, true);", line 102-103 in my editor.
function move(e) {
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
var a = e.clientX;
var b = e.clientY;
context.beginPath();
context.arc(a, b, 20, 0, 2 * Math.PI, true);
context.fillStyle = "red";
context.fill();
}
Here is the fiddle : http://jsfiddle.net/sd5hh57b/1/

You should store the positions you move along in an array. Then a new timer should revisit those discs and redraw them in a more faded color each time it ticks, until a disc becomes black. Then it should be removed from that array.
Here is fiddle that does that.
The change in the code starts at canvas.addEventListener("mousemove",... and goes like this:
canvas.addEventListener("mousemove", function(event) {
// Replaced move function by drawDisc function,
// which needs coordinates and color intensity
drawDisc(event.clientX, event.clientY, 0xF);
});
// Array to keep track of previous positions, i.e. the trail
var trail = [];
function drawDisc(x, y, red) {
context.beginPath();
context.arc(x, y, 20, 0, 2 * Math.PI, true);
context.fillStyle = '#' + red.toString(16) + '00000';
context.fill();
// If disc is not completely faded out, push it in the trail list
if (red) {
trail.push({x: x, y: y, red: red});
}
}
// New function to regularly redraw the trail
function fadeTrail() {
var discs = trail.length;
// If there is only one disc in the trail, leave it as-is,
// it represents the current position.
if (discs > 1) {
for (var i = discs; i; i--) {
// take "oldest" disc out of the array:
disc = trail.shift();
// and draw it with a more faded color, unless it is
// the current disc, which keeps its color
drawDisc(disc.x, disc.y, disc.red - (i === 1 ? 0 : 1));
}
}
}
// New timer to fade the trail
var timerFade = setInterval(function(){
fadeTrail();
}, 10);
I think the comments will make clear what this does. Note that the colors of the discs go from 0xF00000 to 0xE00000, 0xD00000, ... , 0x000000. Except the current disc, that one keeps its 0xF00000 color all the time.

The other answers are right :
Use beginPath() at each new arc() to create a new Path and avoid context.fill() considers the whole as a single Path.
Use a trail Array to store your last positions to draw the trail.
But, the use of setTimeout and setInterval should be avoided (and even further the use of multiple ones).
Modern browsers do support requestAnimationFrame timing method, and for olders (basically IE9), you can find polyfills quite easily. It has a lot of advantages that I won't enumerate here, read the docs.
Here is a modified version of your code, which uses a requestAnimationFrame loop.
I also created two offscreen canvases to update your foods and powers, this way they won't disappear at each draw. Both will be painted in the draw function.
I changed the mousemove handler so it only updates the trail array, leaving the drawing part in the draw loop. At each call, it will set a moving flag that will let our draw function know that we are moving the mouse. Otherwise, it will start to remove old trail arcs from the Array.
var canvas = document.getElementById("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var context = canvas.getContext("2d");
// create other contexts (layer like) for your food and powers
var foodContext = canvas.cloneNode(true).getContext('2d');
var pwrContext = canvas.cloneNode(true).getContext('2d');
// a global to tell weither we are moving or not
var moving;
// a global to store our animation requests and to allow us to pause it
var raf;
// an array to store our trail position
var trail = [];
// here we can determine how much of the last position we'll keep at max (can then be updated if we ate some food)
var trailLength = 10;
// your array for the foods
var foods = [];
// a global to store the last time we drawn the food, no more setInterval
var lastDrawnFood = 0;
// start the game
draw();
function makeFood() {
foods.push(new Food());
}
function Food() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = 10;
}
function drawFood() {
// clear the food Canvas (this could be done only if we ate some, avoiding the loop through all our foods at each call of this method)
foodContext.clearRect(0, 0, canvas.width, canvas.height);
foods.push(new Food());
for (var i = 0; i < foods.length; i++) {
var f = foods[i];
// draw on the food context
foodContext.beginPath();
foodContext.arc(f.x, f.y, f.radius, 0, 2 * Math.PI, true);
var foodGrd = foodContext.createRadialGradient(f.x, f.y, (f.radius - (f.radius - 1)), f.x + 1, f.y + 1, (f.radius));
foodGrd.addColorStop(0, 'red');
foodGrd.addColorStop(1, 'blue');
foodContext.fillStyle = foodGrd;
foodContext.fill();
}
}
// I'll let you update this one
function makePower() {
powers = [];
for (var i = 0; i < 1; i++) {
powers.push(new Power());
}
}
function Power() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.radius = 8;
}
function drawPower() {
pwrContext.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < powers.length; i++) {
var p = powers[i];
var pwrGrd = pwrContext.createRadialGradient(p.x, p.y, (p.radius - (p.radius - 1)), p.x + 1, p.y + 1, (p.radius));
pwrGrd.addColorStop(0, 'green');
pwrGrd.addColorStop(1, 'yellow');
pwrContext.beginPath();
pwrContext.arc(p.x, p.y, p.radius, 0, 2 * Math.PI, true);
pwrContext.fillStyle = pwrGrd;
pwrContext.fill();
}
}
// the event object is already passed, no need for an anonymous function here
canvas.addEventListener("mousemove", move);
function move(e) {
// we paused the game, don't update our position
if (!raf) return;
// update the snake
var a = e.clientX - canvas.offsetLeft;
var b = e.clientY - canvas.offsetTop;
trail.splice(0, 0, {
x: a,
y: b
});
// tell our draw function that we moved
moving = true;
}
function draw(time) {
// our food timer
if (time - lastDrawnFood > 5000) {
lastDrawnFood = time;
drawFood();
}
// clear the canvas
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
// draw the food
context.drawImage(foodContext.canvas, 0, 0);
// draw the power
context.drawImage(pwrContext.canvas, 0, 0);
//draw the snake
for (var i = 0; i < trail.length; i++) {
// decrease the opacity
opacity = 1 - (i / trail.length);
context.fillStyle = "rgba(255, 0,0," + opacity + ")";
// don't forget to create a new Path for each circle
context.beginPath();
context.arc(trail[i].x, trail[i].y, 20, 0, 2 * Math.PI, true);
context.fill();
}
// if we're not moving or if our trail is too long
if ((!moving || trail.length > trailLength) && trail.length > 1)
// remove the oldest trail circle
trail.pop();
// we're not moving anymore
moving = false;
// update the animation request
raf = requestAnimationFrame(draw);
}
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
function toggleStop() {
if (!raf) {
// restart the animation
raf = window.requestAnimationFrame(draw);
} else {
// cancel the next call
cancelAnimationFrame(raf);
raf = 0;
}
}
canvas.addEventListener("click", toggleStop);
html, body{margin:0;}
<canvas id="canvas" width=500 height=500></canvas>

Related

Clear canvas on window resize

I am trying to reset my progress ring, which is drawn with canvas on resize.
Currently, when I resize my window the function is run again as expected, but instead of the canvas being reset another progress ring is being drawn within the same canvas, please see screenshot below:
I have found clearRect() found in an answer here: How to clear the canvas for redrawing and similar solutions but it doesn't seem to resolve my issue.
Please find my codepen with the code: https://codepen.io/MayhemBliz/pen/OJQyLbN
Javascript:
// Progress ring
function progressRing() {
const percentageRings = document.querySelectorAll('.percentage-ring');
for (const percentageRing of Array.from(percentageRings)) {
console.log(percentageRing.offsetWidth)
var percentageRingOptions = {
percent: percentageRing.dataset.percent,
size: percentageRing.offsetWidth,
lineWidth: 30,
rotate: 0
}
var canvas = document.querySelector('.percentage-ring canvas');
var span = document.querySelector('.percentage-ring span');
span.textContent = percentageRingOptions.percent + '%';
if (typeof (G_vmlCanvasManager) !== 'undefined') {
G_vmlCanvasManager.initElement(canvas);
}
var ctx = canvas.getContext('2d');
//clear canvas for resize
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.beginPath();
// end clear canvas
canvas.width = canvas.height = percentageRingOptions.size;
percentageRing.appendChild(span);
percentageRing.appendChild(canvas);
ctx.translate(percentageRingOptions.size / 2, percentageRingOptions.size / 2); // change center
ctx.rotate((-1 / 2 + percentageRingOptions.rotate / 180) * Math.PI); // rotate -90 deg
//imd = ctx.getImageData(0, 0, 240, 240);
var radius = (percentageRingOptions.size - percentageRingOptions.lineWidth) / 2;
var drawCircle = function (color, lineWidth, percent) {
percent = Math.min(Math.max(0, percent || 1), 1);
ctx.beginPath();
ctx.arc(0, 0, radius, 0, Math.PI * 2 * percent, false);
ctx.strokeStyle = color;
//ctx.lineCap = 'round'; // butt, round or square
ctx.lineWidth = lineWidth
ctx.stroke();
};
drawCircle('#efefef', percentageRingOptions.lineWidth, 100 / 100);
var i = 0; var int = setInterval(function () {
i++;
drawCircle('#555555', percentageRingOptions.lineWidth, i / 100);
span.textContent = i + "%";
if (i >= percentageRingOptions.percent) {
clearInterval(int);
}
}, 50);
}
}
window.addEventListener('load', progressRing);
window.addEventListener('resize', progressRing);
HTML:
<div class="percentage-ring" data-percent="88">
<span>88%</span>
<canvas></canvas>
</div>
Your help would be greatly appreciated.
Thanks in advance
1. Clear size problem
var canvas = document.querySelector('.percentage-ring canvas');
var ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
You have to specify canvas size with (canvas.width, canvas.height) instead of ctx.canvas.width, ctx.canvas.height
ctx.clearRect(0, 0, canvas.width, canvas.height);
2. Interval timer usage problem
If progressRing() is called again after setInterval() without clearInterval(), e.g., due to resizing, it will continue to run with the previous interval execution surviving. This will cause the ring to be drawn twice, thrice and more.
Place var int = 0; outside functions. This initializes the int to 0 first.
And modify var int = setInterval( to int = setInterval(
Then place the following code at the beginning of progressRing()
if (int) {
clearInterval(int);
int = 0;
}
And also place int = 0; immediately after the clearInterval() call that was already there.

How can I hover over a shape in canvas and change the color if I have multiple shapes?

I want to be able to hover my mouse over different rectangles and have the rectangle change color when hovered, what I have now works for the last rectangle but the others get cleared. The rectangles are created using a class/constructor, an array, and a loop. Code is below:
/*Variables*/
let canvas = document.querySelector('#canvas'),
ctx = canvas.getContext('2d'),
square;
/*Board Class*/
class Board {
constructor(startX, startY, height, width, angle) {
this.startX = startX;
this.startY = startY;
this.height = height;
this.width = width;
this.angle = angle;
}
drawBoard() {
let canvasWidth = window.innerWidth * .95,
drawWidth = canvasWidth * this.width,
drawHeight = canvasWidth * this.height,
drawStartX = canvasWidth * this.startX,
drawStartY = canvasWidth * this.startY;
square = new Path2D();
ctx.rotate(this.angle * Math.PI / 180);
square.rect(drawStartX, drawStartY, drawHeight, drawWidth);
ctx.fillStyle = 'red';
ctx.fill(square);
}
}
/*Event Listener for changing rectangle color and redrawing*/
canvas.addEventListener('mousemove', function(event) {
if (ctx.isPointInPath(square, event.offsetX, event.offsetY)) {
ctx.fillStyle = 'white';
}
else {
ctx.fillStyle = 'red';
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fill(square);
});
/*Instantiate Array*/
let b = [];
/*Loop to create boards and push to array*/
for(let i = 1; i < 11; i++){
b.push(new Board(.05 * i, .25, .04, .03, 0));
}
/*Function to loop through array and draw boards when page loads*/
function loadFunctions(){
background.draw();
b.forEach(function(board){
board.drawBoard();
})
}
This is my first project with the Canvas API and it's giving me a lot of trouble, normally I could identify the shape by class/id if it where made with a regular HTML element but I'm not sure where to go from here...
I've tried looping through the array that contains the board info but cannot get anything to work. Any help is appreciated!
Thanks
Let's step through your code, to get a better picture of what's going on.
As soon as you move your mouse over the canvas, the mousemove listener gets fired and executes it's associated callback function.
Inside this callback function we'll find this as the very first line:
if (ctx.isPointInPath(square, event.offsetX, event.offsetY))
So this if-statement checks it the current mouse position is inside of square. Well, the big question is: what is square actually?
If we look over your code a bit more, we'll find out that it's a global variable, which gets some value inside the Board class drawBoard() function as:
square = new Path2D();
square.rect(drawStartX, drawStartY, drawHeight, drawWidth);
Apparently it's a Path2D holding the rectangle of one of the bars - but which one actually?
Let's take a look at this function:
for (let i = 0; i < 10; i++) {
b.push(new Board(0.05 * i, 0.25, 0.04, 0.03, 0));
}
and
function loadFunctions() {
b.forEach(function(board) {
board.drawBoard();
})
}
In the first loop, you're populating the array b with ten instances of Board and in the forEach loop, you're calling each Board's drawBoard() function.
What does all this mean? Yes, square will always hold a reference to the bar, which's drawBoard() function has been called the last time - which will always be the last Board in your array.
To summarize: the only bar your checking in the mousemove callback is always the last one in the array.
So:
if (ctx.isPointInPath(square, event.offsetX, event.offsetY)) {
ctx.fillStyle = 'white';
}
else {
ctx.fillStyle = 'red';
}
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fill(square);
translated to plain english means: if the point is in square's bound, set the fillStyle to red, clear the whole screen and afterwards fill one bar with red.
What you need to do instead is checking the mouse position with every Board instance from the array. It ain't to hard though - just make the Path2D a class variable of Board and inside the callback function loop over the whole array and compare the mouse position with each Board's .square property.
Here's an example (just click on 'Run code snippet'):
let canvas = document.querySelector('#canvas'),
ctx = canvas.getContext('2d');
let b = [];
class Board {
constructor(startX, startY, height, width, angle) {
this.startX = startX;
this.startY = startY;
this.height = height;
this.width = width;
this.angle = angle;
this.square = new Path2D();
}
drawBoard() {
let canvasWidth = window.innerWidth * 0.95,
drawWidth = canvasWidth * this.width,
drawHeight = canvasWidth * this.height,
drawStartX = canvasWidth * this.startX,
drawStartY = canvasWidth * this.startY;
ctx.rotate(this.angle * Math.PI / 180);
this.square.rect(drawStartX, drawStartY, drawHeight, drawWidth);
ctx.fillStyle = 'red';
ctx.fill(this.square);
}
}
canvas.addEventListener('mousemove', function(event) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
let currentSquare;
for (let i = 0; i < b.length; i++) {
currentSquare = b[i].square;
if (ctx.isPointInPath(currentSquare, event.offsetX, event.offsetY)) {
ctx.fillStyle = 'white';
} else {
ctx.fillStyle = 'red';
}
ctx.fill(currentSquare);
}
});
for (let i = 0; i < 10; i++) {
b.push(new Board(0.05 * i, 0.25, 0.04, 0.03, 0));
}
function loadFunctions() {
b.forEach(function(board) {
board.drawBoard();
})
}
loadFunctions();
<canvas id="canvas" width=500 height=300></canvas>

creating a recurring animation that doesn't interrupt previous call

I'm trying to creating a recurring animation of vertical rows of circles. Each row begins at the bottom of the browser and goes to the top, occurring at random intervals between 0 and 2 seconds. The problem is that when the animations are too close together in timing, the new one discontinues the previous one, so sometimes the row of circles does not go all the way to the top of the browser. How can I prevent this and instead have multiple rows animating at once?
Here's the fiddle
var timer;
var newLine1 = function(){
clearInterval(timer);
var posX = Math.random() * canvas.width;
posY = canvas.height;
timer = setInterval(function() {
posY -= 20;
c.fillStyle = "rgba(23, 23, 23, 0.05)";
c.fillRect(0, 0, canvas.width, canvas.height);
c.fillStyle = "white";
c.beginPath();
c.arc(posX, posY, 10, 0, twoPi, false);
c.fill();
}, 30);
setTimeout(newLine1, Math.random() * 2000);
};
newLine1();
Here's one way using a rising image of your vertically fading circles and the preferred animation loop (requestAnimationFrame).
Annotated code and a Demo:
// canvas related variables
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
// cache PI*2 because it's used often
var PI2=Math.PI*2;
// variables related to the stream of circles
var radius=10;
var alpha=1.00;
var alphaFade=0.05;
// create an in-memory canvas containing
// a stream of vertical circles
// with alpha=1.00 at top and alpha=0.00 at bottom
// This canvas is drawImage'd on the on-screen canvas
// to simulate animating circles
var streamHeight=(1/alphaFade)*radius*2;
var columnCanvas=document.createElement('canvas');
var columnCtx=columnCanvas.getContext('2d');
columnCanvas.width=radius*2;
columnCanvas.height=streamHeight;
for(var y=radius;y<ch+radius*2;y+=radius*2){
columnCtx.fillStyle='rgba(255,255,255,'+alpha+')';
columnCtx.beginPath();
columnCtx.arc(radius,y,radius,0,PI2);
columnCtx.closePath();
columnCtx.fill();
alpha-=alphaFade;
}
// just testing, remove this
document.body.appendChild(columnCanvas);
// create an array of stream objects
// each stream-object is a column of circles
// at random X and with Y
// animating from bottom to top of canvas
var streams=[];
// add a new stream
function addStream(){
// reuse any existing stream that's already
// scrolled off the top of the canvas
var reuseStream=-1;
for(var i=0;i<streams.length;i++){
if(streams[i].y<-streamHeight){
reuseStream=i;
break;
}
}
// create a new stream object with random X
// and Y is off-the bottom of the canvas
var newStream={
x: Math.random()*(cw-radius),
y: ch+radius+1
}
if(reuseStream<0){
// add a new stream to the array if no stream was available
streams.push(newStream);
}else{
// otherwise reuse the stream object at streams[reuseStream]
streams[reuseStream]=newStream;
}
}
// move all streams upward if the
// elapsed time is greater than nextMoveTime
var nextMoveTime=0;
// move all streams every 16ms X 3 = 48ms
var moveInterval=16*3;
// add a new stream if the
// elapsed time is greater than nextAddStreamTime
var nextAddStreamTime=0;
// set the background color of the canvas to black
ctx.fillStyle='black';
// start the animation frame
requestAnimationFrame(animate);
// the animation frame
function animate(currentTime){
// request a new animate loop
requestAnimationFrame(animate);
// add a new stream if the
// current elapsed time is > nextAddStreamTime
if(currentTime>nextAddStreamTime){
nextAddStreamTime+=Math.random()*1000;
addStream();
}
// move all streams upward if the
// current elapsed time is > nextMoveTime
if(currentTime>nextMoveTime){
nextMoveTime+=moveInterval;
ctx.fillRect(0,0,cw,ch);
for(var i=0;i<streams.length;i++){
var s=streams[i];
if(s.y<-streamHeight){continue;}
ctx.drawImage(columnCanvas,s.x,s.y);
s.y-=radius*2;
}
}
}
body{ background-color: ivory; padding:10px; }
canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=400></canvas>
How about like this. I've only re-worked the newLine1() function. At the end of the line drawing (when posY is < 0), then you trigger the timeout to start another line.
var newLine1 = function(){
var posX = Math.random() * canvas.width;
posY = canvas.height;
timer = setInterval(function() {
posY -= 20;
... drawing code ...
if(posY < 0) {
clearInterval(timer);
setTimeout(newLine1, Math.random() * 2000);
}
}, 30);
};
newLine1();
It also means you don't need the clearInterval at the top, but you clear the timer interval only when the drawing is done (in the posY<0 case).
UPDATE:
Here is take two. I've factored out the line rendering stuff into it's own little class. renderLine then just manages the line intervals and the restarting a line (with timeout) when the first render is done. Finally, we just kick off a bunch of lines.
window.onload = function() {
function LineAnimator(canvas, startX, startY) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
this.startX = startX;
this.startY = startY;
this.interval = null;
this.reset();
}
LineAnimator.prototype.reset = function() {
this.posX = 0 + this.startX;
this.posY = 0 + this.startY;
}
/** return false when there's no more to draw */
LineAnimator.prototype.render = function() {
this.posY -= 20;
this.ctx.fillStyle = 'rgba(23,23,23,0.1)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
this.ctx.fillStyle = 'white';
this.ctx.beginPath();
this.ctx.arc(this.posX, this.posY, 10, 0, twoPi, false);
this.ctx.fill();
if (this.posY < 0) {
return false; /* done rendering */
}
else {
return true;
}
};
var canvas = document.getElementById("paper"),
c = canvas.getContext("2d"),
twoPi = Math.PI * 2;
canvas.width = 500;
canvas.height = 700;
c.fillStyle = "#232323";
c.fillRect(0, 0, canvas.width, canvas.height);
c.save();
var renderLine = function() {
console.log('render line');
var posX = Math.random() * canvas.width;
posY = canvas.height;
var animator = new LineAnimator(canvas, posX, posY);
var timer = setInterval(function() {
if(!animator.render()) {
console.log('done rendering');
clearInterval(timer);
setTimeout(renderLine, Math.random() * 2000)
}
}, 30);
};
var ii = 0,
nConcurrentLines = 8;
for (; ii < nConcurrentLines; ++ii ) {
renderLine();
}
};
This definitely looks a bit different than what I think you're going for, but I kind of like the effect. Though, i would take a close look at #MarkE's answer below. I think his approach is much better. There are no timeouts or intervals and it's using the requestAnimationFrame method which seems much cleaner.

JavaScript animation clingy circles

On my canvas animation, I have a problem where my circles are getting drawn "without the metaphorical pen" lifting from the canvas.
I need a way to stop the function and just draw one circle than another one.
Here is my JSFiddle (Warning: uses 100% of one logical processor core/thread).
JavaScript:
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var size = 19;
var size_two = 19;
function start(){
requestAnimationFrame(start);
size++;
context.arc(95, 85, size, 0, 2*Math.PI);
context.stroke();
}
function othercircle(){
requestAnimationFrame(othercircle);
size_two++;
context.arc(500, 300, size_two, 0, 3*Math.PI);
}
start();
othercircle();
The other answers are good, but I wanted to highlight why your unwanted line is appearing.
Your unwanted connecting line
The unwanted connecting line is created because you must call context.beginPath() before drawing each arc. If you don't call begainPath the browser assumes you want to connect the 2 circle paths.
context.beginPath()
context.arc(95, 85, size, 0, 2*Math.PI);
context.stroke();
context.beginPath();
context.arc(200, 200, size_two, 0, 3*Math.PI);
context.stroke();
Just a couple more notes
Your othercircle is drawing an arc that's 3 * PI. 2*PI is a complete circle and any value above 2*PI will not add to the circle.
If it was your intent to draw an expanding stroke-circle, then you should clear the canvas at the start of each animation loop (before drawing the expanded circles).
One requestAnimationFrame is enough. You can put both your circle and your othercircle code in one requestAnimationFrame.
Example code and a Demo: http://jsfiddle.net/m1erickson/62mFF/
var sizeCounter=19;
var maxSizeCounter=60;
var size = sizeCounter;
var maxSize=40;
var size_two = sizeCounter;
var maxSizeTwo=60;
function start(){
if(sizeCounter<maxSizeCounter){ requestAnimationFrame(start); }
// clear the canvas if you want strokes instead of filled circles
context.clearRect(0,0,canvas.width,canvas.height);
context.beginPath()
context.arc(95, 85, size, 0, 2*Math.PI);
context.stroke();
if(size<maxSize){ size++; }
context.beginPath();
context.arc(200, 200, size_two, 0, 3*Math.PI);
context.stroke();
if(size_two<maxSizeTwo){ size_two++; }
sizeCounter++;
}
start();
Then use a condition to stop the recursive call, or just omit size++ and size_two++ from your code.
Your functions don't have all the information for a complete circle, thus the line between the two circles. Below will make two circles without the line between them.
function start(){
requestAnimationFrame(start);
size++;
context.beginPath();
context.arc(95, 85, size, 0, 2*Math.PI);
context.closePath();
context.fill();
}
function othercircle(){
requestAnimationFrame(othercircle);
size_two++;
context.beginPath();
context.arc(500, 300, size_two, 0, 3*Math.PI);
context.closePath();
context.fill();
}
Here is an updated jsFiddle
http://jsfiddle.net/gamealchemist/4nQCa/5
I think it's simpler to go object in your case : define a Circle class that will update with time and draw itself :
/// Circle class.
// has update(dt) and draw as public method.
function Circle(x, y, initSize, endSize, duration, color) {
this.x = x;
this.y = y;
this.size = initSize;
this.endSize = endSize;
this.color = color;
this.speed = (endSize - initSize) / duration;
this.update = function (dt) {
if (this.speed == 0) return;
this.size += dt * this.speed;
if (this.size > this.endSize) {
this.size = this.endSize;
this.speed = 0;
}
}
this.draw = function () {
context.beginPath();
context.strokeStyle = this.color;
context.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
context.stroke();
}
}
then hold all your animated objects within an array
var scene=[];
And have the objects animated/drawn :
function animate() {
// keep alive
requestAnimationFrame(animate);
// handle time
var callTime = Date.now();
var dt = callTime - lastTime;
lastTime = callTime;
// clear screen
context.clearRect(0, 0, canvasWidth, canvasHeight);
context.fillText('Click anywhere !',40, 80);
// draw
for (var i = 0; i < scene.length; i++) {
var thisObject = scene[i];
thisObject.draw();
}
// update
for (var i = 0; i < scene.length; i++) {
var thisObject = scene[i];
thisObject.update(dt);
}
}
var lastTime = Date.now();
animate();
With this scheme it's easy to add/remove objects. For instance to add circles on mouse click :
addEventListener('mousedown', function (e) {
var x = e.clientX,
y = e.clientY;
var color = 'hsl(' + Math.floor(Math.random() * 360) + ',80%, 85%)';
var newCircle = new Circle(x, y, 20, 100, 1000, color);
scene.push(newCircle);
});

Animation loop and scaling

Well I've got a few question to ask! Firstly What this code is doing is creating and drawing snowflakes with unique density which will all fall at a different rate. My first question is how do i make this loop continuous?
Secondly, I've translated my origin point(0,0) to the middle of the canvas (it was part of the criteria). I've now got this issue in which that when the snowfall is called it will either be drawn on the left side of the screen or the right, not both. How do i solve this?
Finally i know when doing animations that you have to clear the canvas after each re-drawing, however i haven't added this in and yet it still works fine?
//Check to see if the browser supports
//the addEventListener function
if(window.addEventListener)
{
window.addEventListener
(
'load', //this is the load event
onLoad, //this is the evemnt handler we going to write
false //useCapture boolen value
);
}
//the window load event handler
function onLoad(Xi, Yy) {
var canvas, context,treeObj, H, W, mp;
Xi = 0;
Yy = 0;
mp = 100;
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
W = window.innerWidth;
H = window.innerHeight;
canvas.width = W;
canvas.height = H;
context.translate(W/2, H/2);
var particles = [];
for(var i = 0; i < mp; i++) {
particles.push({
x: Math.random()*-W, //x
y: Math.random()*-H, //y
r: Math.random()*6+2, //radius
d: Math.random()* mp // density
})
}
treeObj = new Array();
var tree = new TTree(Xi, Yy);
treeObj.push(tree);
function drawCenterPot(){
context.beginPath();
context.lineWidth = "1";
context.strokeStyle = "Red";
context.moveTo(0,0);
context.lineTo(0,-H);
context.lineTo(0, H);
context.lineTo(-W, 0);
context.lineTo(W,0);
context.stroke();
context.closePath();
}
function drawMountain() {
context.beginPath();
context.fillStyle = "#FFFAF0";
context.lineWidth = "10";
context.strokeStyle = "Black";
context.moveTo(H,W);
context.bezierCurveTo(-H*10,W,H,W,H,W);
context.stroke();
context.fill();
}
function drawSky() {
var linearGrad = context.createLinearGradient(-100,-300, W/2,H);
linearGrad.addColorStop(0, "#000000");
linearGrad.addColorStop(1, "#004CB3");
context.beginPath();
context.fillStyle = linearGrad;
context.fillRect(-W/2, -H/2, W, H);
context.stroke();
context.fill();
drawMountain();
drawCenterPot();
}
function drawSnow(){
context.fillStyle = "White";
context.beginPath();
for(i = 0; i<mp; i++)
{
var p = particles[i];
context.moveTo(p.x,p.y);
context.arc(p.x, p.y, p.r, Math.PI*2, false);
}
context.fill();
}
function update() {
var angle = 0;
angle+=0.1;
for(var i=0; i<mp; i++) {
var p = particles[i];
p.x += Math.sin(angle) * 2;
p.y += Math.cos(angle+p.d) + 1 * p.r;
}
drawSky();
drawSnow();
draw();
}
function draw() {
for(var i =0; i < treeObj.length; i++)
{
context.save();
context.translate(Xi-H,Yy-W);
context.scale(1, 1);
treeObj[0].draw(context);
context.restore();
}
}
setInterval(update, 33);
}
About your animation:
What's happening is your flakes are falling out of view below the bottom of the canvas.
So when any flake's p.y+p.r > canvas.height you could:
destroy that flake and (optionally) add another falling from above the canvas
or
"recycle" that flake by changing its p.y to above the canvas.
About your design working without context.clearRect:
In your design, when you fill the whole canvas with "sky", you are effectively clearing the canvas.
About your flakes only falling on half the screen:
Instead of translating to mid-screen:
Don't translate at all and let p.x be any Math.random()*canvas.width

Categories

Resources