How to i can see canvas log? - javascript

I am developing agario. İ want make countdown for game round but countdown not visible in canvas.
function drawGameScene() {
if (!lastCalledTime) {
lastCalledTime = Date.now();
fps = 60;
displayfps = fps;
} else {
delta = (Date.now() - lastCalledTime) / 1000;
lastCalledTime = Date.now();
fps = 1 / delta;
}
var a, oldtime = Date.now();
++cb;
timestamp = oldtime;
if (0 < playerCells.length) {
calcViewZoom();
var c = a = 0;
for (var d = 0; d < playerCells.length; d++) {
playerCells[d].updatePos();
a += playerCells[d].x / playerCells.length;
c += playerCells[d].y / playerCells.length;
}
posX = a;
posY = c;
posSize = viewZoom;
nodeX = (nodeX + a) / 2;
nodeY = (nodeY + c) / 2
} else {
nodeX = (29 * nodeX + posX) / 30;
nodeY = (29 * nodeY + posY) / 30;
viewZoom = (9 * viewZoom + posSize * viewRange()) / 10;
}
buildQTree();
mouseCoordinateChange();
xa || ctx.clearRect(0, 0, canvasWidth, canvasHeight);
if (xa) {
if (showDarkTheme) {
ctx.fillStyle = '#111111';
ctx.globalAlpha = .05;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.globalAlpha = 1;
}
else if (pembetema) {
ctx.fillStyle = '#ff4081';
ctx.globalAlpha = .05;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.globalAlpha = 1;
}else if (yesiltema) {
ctx.fillStyle = '#40ff58';
ctx.globalAlpha = .05;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.globalAlpha = 1;
}else if (default_tema) {
ctx.fillStyle = '#F2FBFF';
ctx.globalAlpha = .05;
ctx.fillRect(0, 0, canvasWidth, canvasHeight);
ctx.globalAlpha = 1;
}
} else {
drawGrid();
}
nodelist.sort(function (a, b) {
return a.size == b.size ? a.id - b.id : a.size - b.size
});
ctx.save();
ctx.translate(canvasWidth / 2, canvasHeight / 2);
ctx.scale(viewZoom, viewZoom);
ctx.translate(-nodeX, -nodeY);
if (transparentRender == true) {
ctx.globalAlpha = 0.6;
} else {
ctx.globalAlpha = 1;
}
/*drawBorders(ctx);*/
for (d = 0; d < Cells.length; d++) Cells[d].drawOneCell(ctx);
for (d = 0; d < nodelist.length; d++) nodelist[d].drawOneCell(ctx);
//console.log(Cells.length);
if (drawLine) {
drawLineX = (3 * drawLineX + lineX) /
4;
drawLineY = (3 * drawLineY + lineY) / 4;
ctx.save();
ctx.strokeStyle = "#FFAAAA";
ctx.lineWidth = 10;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.globalAlpha = .5;
ctx.beginPath();
for (d = 0; d < playerCells.length; d++) {
ctx.moveTo(playerCells[d].x, playerCells[d].y);
ctx.lineTo(drawLineX, drawLineY);
}
ctx.stroke();
ctx.restore()
}
// border -->
ctx.strokeStyle = '#00D1DF';
ctx.lineWidth = 25;
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.beginPath();
ctx.moveTo(leftPos,topPos);
ctx.lineTo(rightPos,topPos);
ctx.lineTo(rightPos,bottomPos);
ctx.lineTo(leftPos,bottomPos);
ctx.closePath();
ctx.stroke();
// <--
ctx.restore();
///////////////////////////////////////// MY COUNTDOWN CODES ////////////////////////////////////////////////
ctx.globalAlpha = 1;
ctx.fillStyle = "#0000FF";
ctx.font = "30px Roboto";
if(this.countdown < 3600){
var countDownStr = "";
var min = Math.floor(this.countdown/60);
if ( min < 10 ){
countDownStr += "0";
}
countDownStr += min+":";
var sec = this.countdown%60;
if ( sec<10 ){
countDownStr += "0";
}
countDownStr += sec;
ctx.fillText(countDownStr, ((canvasWidth - ctx.measureText(countDownStr).width) * 0.5), 30);
}
///////////////////////////////////////// MY COUNTDOWN CODES ////////////////////////////////////////////////
lbCanvas && lbCanvas.width && ctx.drawImage(lbCanvas, canvasWidth - lbCanvas.width - 10, 10); // draw Leader Board
if (!hideChat)
{
if ((chatCanvas != null)&&(chatCanvas.width > 0)) ctx.drawImage(chatCanvas, 0, canvasHeight - chatCanvas.height - 50); // draw Chat Board
}
var mass = calcUserScore();
userScore = Math.max(userScore, mass);
if (0 != userScore) {
kb();
if (null == scoreText) {
scoreText = new UText(24, '#FFFFFF');
}
var boxOpacity = .25;
scoreText.setValue("Score: " + ~~(userScore / 100));
c = scoreText.render();
w = c.width;
ctx.globalAlpha = boxOpacity;
ctx.fillStyle = "#000000";
ctx.fillRect(10, 10, w + 10, 34);
ctx.globalAlpha = 1;
ctx.drawImage(c, 15, 15);
scoreText.setValue("Mass: " + ~~(mass / 100));
c = scoreText.render();
w = c.width;
ctx.fillStyle = "rgba(0,0,0, " + boxOpacity;
ctx.fillRect(10, 50, w + 10, 34);
ctx.drawImage(c, 15, 55);
}
drawSplitIcon(ctx);
drawTouch(ctx);
drawMap();
var deltatime = Date.now() - oldtime;
deltatime > 1E3 / 60 ? z -= .01 : deltatime < 1E3 / 65 && (z += .01);
.4 > z && (z = .4);
1 < z && (z = 1)
}
I added a comment line to where the countdown was. Where is the problem ? I am going crazy. I added a comment line to where the countdown was. Where is the problem ? I am going crazy. i need add "ctx.save()" or "ctx.restore()" codes ? What i need do ?

Related

arrow with modification point

Hi I'm trying to reproduce a draw.io effect. When you draw an arrow it display a blue point in the middle of the arrow that allows you to create angle between the two lines and it display two blue point that allow you to do the same with the two new line. I have added image below. It'll be easier to understand.
I wonder how to code dynamically these blue points that allow to "break" the line
var ctx = tempcanvas.getContext('2d'),
mainctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
x1,
y1,
isDown = false;
ctx.translate(0.5, 0.5);
tempcanvas.onmousedown = function(e) {
var rect = canvas.getBoundingClientRect();
x1 = e.clientX - rect.left;
y1 = e.clientY - rect.top;
isDown = true;
}
tempcanvas.onmouseup = function() {
isDown = false;
mainctx.drawImage(tempcanvas, 0, 0);
ctx.clearRect(0, 0, w, h);
}
tempcanvas.onmousemove = function(e) {
if (!isDown) return;
var rect = canvas.getBoundingClientRect(),
x2 = e.clientX - rect.left,
y2 = e.clientY - rect.top;
var p0={x1,y1};
var p1={x2,y2};
ctx.clearRect(0, 0, w, h);
drawLineWithArrowhead(p0,p1,25);
}
function drawLineWithArrowhead(p0,p1,headLength){
var PI=Math.PI;
var degreesInRadians225=225*PI/180;
var degreesInRadians135=135*PI/180;
var dx=p1.x2-p0.x1;
var dy=p1.y2-p0.y1;
var angle=Math.atan2(dy,dx);
// calc arrowhead points
var x225=p1.x2+headLength*Math.cos(angle+degreesInRadians225);
var y225=p1.y2+headLength*Math.sin(angle+degreesInRadians225);
var x135=p1.x2+headLength*Math.cos(angle+degreesInRadians135);
var y135=p1.y2+headLength*Math.sin(angle+degreesInRadians135);
ctx.beginPath();
// draw the line from p0 to p1
ctx.moveTo(p0.x1,p0.y1);
ctx.lineTo(p1.x2,p1.y2);
// draw partial arrowhead at 225 degrees
ctx.moveTo(p1.x2,p1.y2);
ctx.lineTo(x225,y225);
// draw partial arrowhead at 135 degrees
ctx.moveTo(p1.x1,p1.y1);
ctx.lineTo(x135,y135);
// stroke the line and arrowhead
ctx.stroke();
}
canvas {position:absolute;left:0;top:0}
#canvas {background:#eef}
<canvas id="canvas" width=400 height=400></canvas>
<canvas id="tempcanvas" width=400 height=400></canvas>
Example snippet
Sorry out of time (Weekend and all) to write a detailed explanation and no point wasting the code, so hope it helps.
const ctx = canvas.getContext("2d");
ctx.bounds = canvas.getBoundingClientRect();
const P2 = (x = 0, y = 0) => ({x, y});
const points = [];
const lineStyle = "#000";
const nearLineStyle = "#0AF";
const lineWidth = 2;
const nearLineWidth = 3;
const pointStyle = "#000";
const nearPointStyle = "#0AF";
const pointLineWidth = 1;
const nearPointLineWidth = 2;
const arrowSize = 18;
const pointSize = 5;
const nearPointSize = 15;
const checkerSize = 256; // power of two
const checkerCol1 = "#CCC";
const checkerCol2 = "#EEE";
const MIN_SELECT_DIST = 20; // in pixels;
var w = canvas.width, h = canvas.height;
var cw = w / 2, ch = h / 2;
var cursor = "default";
var toolTip = "";
const mouse = { x: 0, y: 0, button: 0 };
const drag = {dragging: false};
requestAnimationFrame(update);
function mouseEvents(e) {
mouse.x = e.pageX - ctx.bounds.left - scrollX;
mouse.y = e.pageY - ctx.bounds.top - scrollY;
if (e.type === "mousedown") { mouse.button |= 1 << (e.which - 1) }
else if (e.type === "mouseup") { mouse.button &= ~(1 << (e.which - 1)) }
}
["down", "up", "move"].forEach(name => document.addEventListener("mouse" + name, mouseEvents));
const checkerboard = (()=> {
const s = checkerSize, s2 = s / 2;
const c = document.createElement("canvas");
c.height = c.width = checkerSize;
const ctx = c.getContext("2d", {alpha: false});
ctx.fillStyle = checkerCol1;
ctx.fillRect(0,0,s, s);
ctx.fillStyle = checkerCol2;
ctx.fillRect(0,0,s2,s2);
ctx.fillRect(s2,s2,s2,s2);
ctx.globalAlpha = 0.25;
var ss = s2;
while(ss > 8) {
ctx.fillStyle = ctx.createPattern(c, "repeat");
ctx.setTransform(1/8,0,0,1/8,0,0);
ctx.fillRect(0,0,s * 8,s * 8);
ss /= 2;
}
return ctx.createPattern(c, "repeat");
})();
function nearestPointLine(points, point, minDist){ // fills nearest object with nearest point and line to point if within minDist.
var i = 0, p1, dist;
nearest.reset(minDist);
const v1 = P2();
const v2 = P2();
const v3 = P2();
for (const p of points) {
v2.x = point.x - p.x;
v2.y = point.y - p.y;
dist = (v2.x * v2.x + v2.y * v2.y) ** 0.5;
if(dist < nearest.point.dist) {
nearest.point.dist = dist;
nearest.point.p = p;
nearest.point.idx = i;
}
if (p1) {
v1.x = p1.x - p.x;
v1.y = p1.y - p.y;
v2.x = point.x - p.x;
v2.y = point.y - p.y;
const u = (v2.x * v1.x + v2.y * v1.y) / (v1.y * v1.y + v1.x * v1.x);
if (u >= 0 && u <= 1) { // is closest poin on line segment
v3.x = p.x + v1.x * u;
v3.y = p.y + v1.y * u;
//ctx.fillRect(v3.x, v3.y, 5, 5)
dist = ((v3.y - point.y) ** 2 + (v3.x - point.x) ** 2) ** 0.5;
if(dist < nearest.line.dist) {
nearest.line.dist = dist;
nearest.line.p1 = p1;
nearest.line.p2 = p;
nearest.line.idx = i;
nearest.line.onLine.x = v3.x;
nearest.line.onLine.y = v3.y;
}
}
}
p1 = p;
i ++;
}
if (nearest.point.idx > -1 && nearest.point.dist / 2 <= nearest.line.dist) {
nearest.active = nearest.point;
nearest.near = true;
} else if (nearest.line.idx > -1) {
nearest.active = nearest.line;
nearest.near = true;
}
}
function drawLine(p1, p2) {
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
}
function drawLineArrow(p1, p2) {
var nx = p1.x - p2.x;
var ny = p1.y - p2.y;
const d =( nx * nx + ny * ny) ** 0.5;
if(d > arrowSize) {
nx /= d;
ny /= d;
ctx.setTransform(-nx, -ny, ny, -nx, p2.x, p2.y);
ctx.beginPath()
ctx.fillStyle = ctx.strokeStyle;
ctx.moveTo(0, 0);
ctx.lineTo(-arrowSize, arrowSize / 2);
ctx.lineTo(-arrowSize, -arrowSize / 2);
ctx.fill();
ctx.setTransform(1,0,0,1,0,0);
}
}
function drawPoint(p, size = pointSize) {
ctx.rect(p.x - size / 2, p.y - size / 2, size, size);
}
function drawLines(points) {
var p1;
ctx.strokeStyle = lineStyle;
ctx.lineWidth = lineWidth;
ctx.beginPath()
for(const p of points) {
if (p1) { drawLine(p1 ,p) }
p1 = p;
}
ctx.stroke();
if(points.length > 1) {
drawLineArrow(points[points.length - 2], p1);
}
}
function drawPoints(points) {
ctx.strokeStyle = pointStyle;
ctx.lineWidth = pointLineWidth;
ctx.beginPath()
for(const p of points) { drawPoint(p) }
ctx.stroke();
}
function sizeCanvas() {
if (w !== innerWidth || h !== innerHeight) {
cw = (w = canvas.width = innerWidth) / 2;
ch = (h = canvas.height = innerHeight) / 2;
ctx.bounds = canvas.getBoundingClientRect();
}
}
const nearest = {
point: { isPoint: true },
line: { onLine: P2() },
reset(minDist) {
nearest.point.dist = minDist;
nearest.point.idx = -1;
nearest.line.dist = minDist;
nearest.line.idx = -1;
nearest.active = null;
nearest.near = false;
},
draw() {
const a = nearest.active;
if (a) {
if (a.isPoint) {
ctx.strokeStyle = nearPointStyle;
ctx.lineWidth = nearPointLineWidth;
ctx.beginPath()
drawPoint(a.p, nearPointSize);
ctx.stroke();
} else {
ctx.strokeStyle = nearLineStyle;
ctx.lineWidth = nearLineWidth;
ctx.beginPath()
drawLine(a.p1, a.p2);
ctx.stroke();
ctx.strokeStyle = nearPointStyle;
ctx.lineWidth = nearPointLineWidth;
ctx.beginPath()
drawPoint(a.onLine, nearPointSize);
ctx.stroke();
}
}
}
}
function update() {
cursor = "crosshair";
toolTip = "";
ctx.setTransform(1, 0, 0, 1, 0, 0); // reset transform
ctx.globalAlpha = 1; // reset alpha
sizeCanvas();
ctx.fillStyle = checkerboard;
ctx.fillRect(0, 0, w, h);
if (!drag.dragging) {
nearestPointLine(points, mouse, MIN_SELECT_DIST);
if (nearest.near && nearest.active.isPoint) { cursor = "move"; toolTip = "Drag to move point"}
else if (nearest.near) { cursor = "crosshair"; toolTip = "Click/drag to cut and drag new point" }
else {
if (points.length < 2) {
cursor = "crosshair";
toolTip ="Click to add point";
} else {
cursor = "default";
toolTip = "";
}
}
}
drawLines(points);
drawPoints(points);
nearest.draw();
if((mouse.button & 1) === 1) {
if (!drag.dragging) {
if(points.length < 2 && !nearest.near) {
points.push(P2(mouse.x, mouse.y));
mouse.button = 0;
} else if (nearest.near) {
if (nearest.active.isPoint) {
drag.point = nearest.active.p;
} else {
drag.point = P2(nearest.active.onLine.x, nearest.active.onLine.y);
points.splice(nearest.active.idx, 0, drag.point);
nearestPointLine(points, drag.point, 20);
}
drag.offX = drag.point.x - mouse.x;
drag.offY = drag.point.y - mouse.y;
drag.dragging = true;
}
}
if(drag.dragging) {
drag.point.x = drag.offX + mouse.x;
drag.point.y = drag.offY + mouse.y;
drag.point.x = drag.point.x < 1 ? 1 : drag.point.x > w - 2 ? w - 2 : drag.point.x;
drag.point.y = drag.point.y < 1 ? 1 : drag.point.y > h - 2 ? h - 2 : drag.point.y;
cursor = "none";
}
} else if((mouse.button & 1) === 0) {
drag.dragging = false;
drag.point = null;
}
canvas.title = toolTip;
canvas.style.cursor = cursor;
requestAnimationFrame(update);
}
canvas {
position: absolute;
top: 0px;
left: 0px;
}
<canvas id="canvas"></canvas>

Javascript won't draw the animation taking value from HTML input element

I wanted to create physics simulation with dropping ball. To have more fun I wanted to give to user an access to input his values of dropping ball radius and count. If you would run this code on browser, you could click button 'CREATE' to display animation with default values and it would have worked. When I enter balls count in html input element, it recognises the count and executes the code and the animation appears. When I enter radius value in html input element, nothing appears on canvas. I find this as very strange problem. I've already tried renaming variables and element id names. When I I would appreciate if anyone could help.
The html file called index.html
const canvas = document.getElementById('ball-platform');
const createBtn = document.getElementById('createAnimation');
const W = canvas.width;
const H = canvas.height;
const ctx = canvas.getContext('2d');
const gravity = 0.15;
const friction = 0.9;
let balls = [];
function FillCircle(x0, y0, bRadius, theColor) {
let circle = {
x: x0,
y: y0,
color: theColor
};
let xVel = 5,
yVel = 1;
this.movement = () => {
if (Math.round(circle.x + bRadius + xVel) > W || Math.round(circle.x - bRadius + xVel) < 0) {
xVel = -xVel * friction;
yVel *= friction;
} else if (Math.round(circle.y + bRadius + yVel) > H) {
yVel = -yVel * friction;
xVel *= friction;
} else {
yVel += gravity;
}
circle.x += xVel;
circle.y += yVel;
}
this.draw = () => {
ctx.beginPath();
ctx.fillStyle = circle.color;
ctx.ellipse(circle.x, circle.y, bRadius, bRadius, -90 * Math.PI / 180, 360 * Math.PI / 180, false);
ctx.fill();
ctx.stroke();
}
}
createBtn.addEventListener('mousedown', () => {
balls = [];
let bRadius = document.getElementById('bRadius').value;
let count = document.getElementById('count').value;
if (bRadius == "" || bRadius <= 0) {
bRadius = 5;
}
if (count == "" || count < 0) {
count = 5;
}
initialize(count, bRadius);
});
function initialize(count, bRadius) {
for (let i = 0; i < count; i++) {
let xpos = (Math.random() * (W - bRadius - 10)) + bRadius;
let ypos = (Math.random() * (H - bRadius - 10)) + bRadius;
balls.push(new FillCircle(xpos, ypos, bRadius, 'red'));
}
}
function animation() {
requestAnimationFrame(animation);
ctx.clearRect(0, 0, W, H);
for (let a = 0; a < balls.length; a++) {
let circle = balls[a];
circle.movement();
circle.draw();
}
}
animation();
<nav style='display: block;'>
<button id='createAnimation'>CREATE</button>
<input placeholder='Radius' , id='bRadius'>
<input placeholder='Count' id='count'>
</nav>
<canvas id="ball-platform" width="500" height="500" style="border: 1px solid black"></canvas>
I think you need to convert the input values to numbers,
const canvas = document.getElementById('ball-platform');
const createBtn = document.getElementById('createAnimation');
const W = canvas.width;
const H = canvas.height;
const ctx = canvas.getContext('2d');
const gravity = 0.15;
const friction = 0.9;
let balls = [];
function FillCircle(x0, y0, bRadius, theColor) {
let circle = {
x: x0,
y: y0,
color: theColor
};
let xVel = 5,
yVel = 1;
this.movement = () => {
if (Math.round(circle.x + bRadius + xVel) > W || Math.round(circle.x - bRadius + xVel) < 0) {
xVel = -xVel * friction;
yVel *= friction;
} else if (Math.round(circle.y + bRadius + yVel) > H) {
yVel = -yVel * friction;
xVel *= friction;
} else {
yVel += gravity;
}
circle.x += xVel;
circle.y += yVel;
}
this.draw = () => {
ctx.beginPath();
ctx.fillStyle = circle.color;
ctx.ellipse(circle.x, circle.y, bRadius, bRadius, -90 * Math.PI / 180, 360 * Math.PI / 180, false);
ctx.fill();
ctx.stroke();
}
}
createBtn.addEventListener('mousedown', () => {
balls = [];
let bRadius = parseInt(document.getElementById('bRadius').value);
let count = parseInt(document.getElementById('count').value);
if (bRadius == "" || bRadius <= 0) {
bRadius = 5;
}
if (count == "" || count < 0) {
count = 5;
}
initialize(count, bRadius);
});
function initialize(count, bRadius) {
for (let i = 0; i < count; i++) {
let xpos = (Math.random() * (W - bRadius - 10)) + bRadius;
let ypos = (Math.random() * (H - bRadius - 10)) + bRadius;
balls.push(new FillCircle(xpos, ypos, bRadius, 'red'));
}
}
function animation() {
requestAnimationFrame(animation);
ctx.clearRect(0, 0, W, H);
for (let a = 0; a < balls.length; a++) {
let circle = balls[a];
circle.movement();
circle.draw();
}
}
animation();
<nav style='display: block;'>
<button id='createAnimation'>CREATE</button>
<input placeholder='Radius' , id='bRadius'>
<input placeholder='Count' id='count'>
</nav>
<canvas id="ball-platform" width="500" height="500" style="border: 1px solid black"></canvas>

Where to invoke cancelAnimationFrame upon completion?

I could not identify a line in step() function to indicate that the animation has completed. Therefore, I could not cancelAnimationFrame correctly.
Question: Is this the reason why cancelAnimationFrame() is not working? If yes, at which line of code do I indicate that animation has completed so I can cancelAnimationFrame?
var myRequestId;
function step() {
// ... see https://codepen.io/jek/pen/RwwXBpz
myRequestId = requestAnimationFrame(step);
console.log("myRequestId", myRequestId);
}
myRequestId = requestAnimationFrame(step);
// Ref https://developer.mozilla.org/en-US/docs/Web/API/Window/cancelAnimationFrame
// todo: How do we stop it onComplete?
// question: where do we put a flag to indicate that it has completed?
//cancelAnimationFrame(myRequestId); // todo: If we uncomment this line the animation won't work at all
See https://codepen.io/jek/pen/RwwXBpz
You don't need to run cancelAnimationFrame, you can just run requestAnimationFrame conditionally.
Like this:
function step() {
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.globalAlpha = 1;
ctx.fillStyle = "#622";
ctx.fillRect(0, (canvas.height - scale) / 2, canvas.width, scale);
let running = false;
for (var i = 0; i < text.length; i++) {
ctx.fillStyle = "#ccc";
ctx.textBaseline = "middle";
ctx.textAlign = "center";
ctx.setTransform(
1,
0,
0,
1,
Math.floor((canvas.width - scale * (text.length - 1)) / 2),
Math.floor(canvas.height / 2)
);
var o = offset[i];
while (o < 0) o++;
o %= 1;
var h = Math.ceil(canvas.height / 2 / scale);
for (var j = -h; j < h; j++) {
var c = charMap[text[i]] + j - Math.floor(offset[i]);
while (c < 0) c += chars.length;
c %= chars.length;
var s = 1 - Math.abs(j + o) / (canvas.height / 2 / scale + 1);
ctx.globalAlpha = s;
ctx.font = scale * s + "px Helvetica";
ctx.fillText(chars[c], scale * i, (j + o) * scale);
}
offset[i] += offsetV[i];
offsetV[i] -= breaks;
if (offsetV[i] < endSpeed) {
offset[i] = 0;
offsetV[i] = 0;
} else {
running = true;
}
}
if (running) {
requestAnimationFrame(step);
} else {
console.log('animation stopped');
}
}
Live demo

Clickable Canvas Button with Link

I have the following canvas. I want it so that when the user clicks the canvas, I will go to google.com, and I want to keep the button element. This is my code:
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d'),
a.style.width = '200px';
a.style.height = '50px';
area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = .01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - .05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if(this.r <= .05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0,0,w,h);
for(var i = 0; i < particles.length; i++) {
if(particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if(particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for(var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max)?max:1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
#canvas{
width: 200;
height: 50;
}
<div class="wrapper">
<a href="index.html">
<button align=center onclick="handleClick()">
<canvas width="200" height="50" id="canvas" align=center></canvas>
<span class="text">SUBMIT</span>
</button>
</a>
</div>
Although, I only see the button, and no the canvas. How can I fix this?
You got a lot of errors actually buddy (variable declaration is the biggest problem) but by following the errors will give you a way to fix it, I don't know if this is the fix you want.
//set the variables
var a = document.getElementById('canvas'),
c = a.getContext('2d');
a.style.width = '200px';
a.style.height = '50px';
var w, h;
var area = w * h,
particleNum = 300,
ANIMATION;
var particles = [];
//create the particles
function Particle(i) {
this.id = i;
this.hue = rand(50, 0, 1);
this.active = false;
}
Particle.prototype.build = function() {
this.x = w / 2;
this.y = h / 2;
this.r = rand(7, 2, 1);
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = 0.01;
this.opacity = Math.random() + .5;
this.active = true;
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
};
Particle.prototype.draw = function() {
this.active = true;
this.x += this.vx;
this.y += this.vy;
this.vy += this.gravity;
this.hue -= 0.5;
this.r = Math.abs(this.r - 0.05);
c.beginPath();
c.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
c.fillStyle = "hsla(" + this.hue + ",100%,50%,1)";
c.fill();
// reset particle
if (this.r <= 0.05) {
this.active = false;
}
};
//functionality
function drawScene() {
c.fillStyle = "black";
c.fillRect(0, 0, w, h);
for (var i = 0; i < particles.length; i++) {
if (particles[i].active === true) {
particles[i].draw();
} else {
particles[i].build();
}
}
ANIMATION = requestAnimationFrame(drawScene);
}
function initCanvas() {
var s = getComputedStyle(a);
if (particles.length) {
particles = [];
cancelAnimationFrame(ANIMATION);
ANIMATION;
console.log(ANIMATION);
}
w = a.width = window.innerWidth;
h = a.height = window.innerHeight;
for (var i = 0; i < particleNum; i++) {
particles.push(new Particle(i));
}
drawScene();
console.log(ANIMATION);
}
//init
(function() {
initCanvas();
addEventListener('resize', initCanvas, false);
})();
//helper functions
function rand(max, min, _int) {
var max = (max === 0 || max) ? max : 1,
min = min || 0,
gen = min + (max - min) * Math.random();
return (_int) ? Math.round(gen) : gen;
};
#canvas {
width: 200px;
height: 50px;
}
<div class="wrapper">
<a href="index.html">
<button align=center onclick="handleClick()">
<canvas width="200" height="50" id="canvas" align=center> </canvas>
<span class="text">SUBMIT</span>
</button>
</a>
</div>

How to make canvas particles follow mouse with JS?

I want to make the particles follow the mouse and I am not sure on how to do that.
I figured I can replace the x and y with the mouses position but I can figure that out either.
I would appreciate an almost exact answer and not examples please.
window.onload = function() {
var canvas = document.createElement("canvas"),
c = canvas.getContext("2d"),
particles = {}
particleIndex = 0,
particleNum = Math.random() * 2;
canvas.width = 400;
canvas.height = 400;
document.body.appendChild(canvas);
c.fillStyle = "black";
c.fillRect(0, 0, canvas.width, canvas.height);
function Particle() {
this.x = canvas.width / 10;
this.y = canvas.height / 2;
this.vx = Math.random() * 10 - 5;
this.vy = Math.random() * 10 - 5;
this.gravity = .2;
particleIndex++;
particles[particleIndex] = this;
this.id = particleIndex;
this.life = 0;
this.maxLife = Math.random() * 30 + 10;
this.color = "rgb(" + parseInt(Math.random() * 255, 10) + ",0,0)";
this.color2 = "hsl(" + parseInt(Math.random() * 255, 10) + ",50%,50%)";
}
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.vy += this.gravity;
this.life++;
if (this.Life >= this.maxLife) {
delete particles[this.id];
}
c.fillStyle = this.color2;
c.fillRect(this.x, this.y, 10, 10);
};
//var p = new Particle();
setInterval(function() {
c.fillStyle = "rgba(0,0,0,0.5)";
c.fillRect(0, 0, canvas.width, canvas.height);
for (var i in particles) {
particles[i].draw();
}
for (var i = 0; i < particleNum; i++) {
new Particle();
}
}, 30);
};

Categories

Resources