How to optimize canvas or something else on site? - javascript

Here is a site, in it a canvas (airplane), which lags when scrolling, appear artifacts, and in different ways, depending on what you scroll - with the mouse wheel or scrollbar. If you comment out parallax or video at the beginning, nothing changes. During the scrolling of calls to the house does not happen. Lags either from behind the airplane script, or because of a clearRect. How can I optimize and get rid of artifacts? The code on the codepen (it works fine)
var scrolled;
var positionsArr = [];
var commonHeight = 0;
var canvas = document.querySelector('#canvas');
var canvasB = document.querySelector('#canvasback');
var ctx = canvas.getContext('2d');
var ctxB = canvasB.getContext('2d');
var centerX, centerY, radius, pointsOffset, radiusRatio, centerXRatio,
firstPoint, lastPoint, jet, blocksPosition, jetPositionY, jetTop, tabletOffset, headerHeight, canvasClearWidth;
var wWidth, mediaMobile, mediaTablet, mediaDesktop1, mediaDesktop2, mediaDesktop3;
jet = new Image();
jet.src = 'http://silencer.website/alkor/images/jet.png';
jet.onload = function () {
adaptive();
}
$(window).on('resize', function () {
adaptive();
});
function adaptive() {
mediaMobile = mediaTablet = mediaDesktop1 = mediaDesktop2 = mediaDesktop3 = false;
wWidth = $(window).width();
// Параметры для дуги по умолчанию
tabletOffset = 0;
radiusRatio = .95;
centerXRatio = 1.25;
// Параметры для дуги на разных разрешениях (перезаписывают параметры по умолчанию)
if (wWidth < 768) {
mediaMobile = true;
}
if (wWidth >= 768 && wWidth < 1024) {
mediaTablet = true;
tabletOffset = 120;
}
if (wWidth >= 1024 && wWidth < 1280) {
mediaDesktop1 = true;
tabletOffset = -40;
radiusRatio = 1.1;
centerXRatio = 1.03;
}
if (wWidth >= 1280 && wWidth < 1440) {
mediaDesktop2 = true;
tabletOffset = -20;
}
if (wWidth >= 1440) {
mediaDesktop3 = true;
tabletOffset = -20;
}
if (!mediaMobile) {
setTimeout(function () {
doCanvas();
}, 500);
} else {
ctx.clearRect(0, 0, canvas.width, canvas.height);
$(window).off('scroll', onScroll);
}
}
function doCanvas() {
$(window).on('scroll', onScroll);
var marginBottom = 120;
commonHeight = 0;
$('.history__item').each(function () {
commonHeight = commonHeight + $(this).height() + marginBottom;
});
commonHeight = commonHeight - marginBottom;
canvasWidth = $('.history').width() * .3;
canvasHeight = $('.history__blocks').height();
canvas.width = canvasWidth;
canvas.height = canvasHeight;
canvasB.width = canvas.width;
canvasB.height = canvas.height;
offsetLeft = $('.history__blocks')[0].offsetLeft;
$('#canvas, #canvasback').css('marginLeft', -offsetLeft);
radius = commonHeight * radiusRatio;
centerX = -commonHeight / centerXRatio + offsetLeft + tabletOffset;
centerY = commonHeight / 2;
pointsOffset = 100;
canvasClearWidth = centerX + radius + 110;
blocksPosition = $('.history__blocks')[0].offsetTop;
jetPositionY = $('.history')[0].offsetTop;
headerHeight = $('.history__title').height();
jetTop = $(window).height() / 2;
jetOnScroll = jetTop - headerHeight - jetPositionY;
positionsArr = [];
lastIndex = $('.history__item').length - 1;
darkened = $('.history__item');
for (var i = 0; i < $('.history__item').length; i++) {
var position = $('.history__item').eq(i)[0].offsetTop - blocksPosition + pointsOffset;
positionsArr.push(position);
if (i == 0) {
firstPoint = position;
}
if (i == $('.history__item').length - 1) {
lastPoint = position;
}
}
draw();
drawBackground();
setTimeout(function () {
if (mediaTablet) {
jetPositionLine(firstPoint);
} else {
jetPosition(firstPoint);
}
}, 100);
}
function drawBackground() {
if (mediaTablet) {
drawLine();
} else {
drawArc();
}
}
function draw(currentY) {
for (var i = 0; i < positionsArr.length; i++) {
addPoint(positionsArr[i], currentY, i);
}
}
function drawArc() {
var firstPointRad = Math.asin((centerY - firstPoint) / radius);
var lastPointRad = Math.asin((centerY - lastPoint) / radius);
ctxB.beginPath();
ctxB.lineWidth = 3;
ctxB.save();
ctxB.arc(centerX, centerY, radius, 1.5, lastPointRad, true);
ctxB.strokeStyle = '#99daf0';
ctxB.setLineDash([8, 5]);
ctxB.lineDashOffset = 1;
ctxB.globalCompositeOperation = 'destination-over';
ctxB.stroke();
ctxB.restore();
}
function drawLine() {
ctxB.beginPath();
ctxB.lineWidth = 3;
ctxB.save();
ctxB.lineTo(tabletOffset, firstPoint);
ctxB.lineTo(tabletOffset, lastPoint);
ctxB.strokeStyle = '#99daf0';
ctxB.setLineDash([8, 5]);
ctxB.lineDashOffset = 1;
ctxB.globalCompositeOperation = 'destination-over';
ctxB.stroke();
ctxB.restore();
}
function addPoint(y, currentY, i) {
if (mediaTablet) {
var currentX = tabletOffset;
} else {
var angle = Math.asin((centerY - y) / radius);
var currentX = centerX + radius * (Math.cos(angle));
}
ctx.beginPath();
ctx.arc(currentX, y, 8, 0, 2 * Math.PI, false);
ctx.lineWidth = 3;
ctx.fillStyle = '#00a3da';
ctx.globalCompositeOperation = 'source-over';
if (currentY + 10 >= y) {
ctx.strokeStyle = '#fff';
darkened.eq(i).removeClass('darkened');
} else {
ctx.strokeStyle = '#99daf0';
darkened.eq(i).addClass('darkened');
}
ctx.fill();
ctx.stroke();
}
function jetPosition(y) {
var angle = Math.asin((centerY - y) / radius);
var currentX = centerX + radius * (Math.cos(angle) - 1);
var firstPointRad = Math.asin((centerY - firstPoint) / radius);
// if (toUp) { // Самолетик вверх-вниз
var jetAngle = Math.acos((centerY - y) / radius);
// } else {
// var jetAngle = Math.acos((centerY - y) / radius) + Math.PI;
// }
ctx.beginPath();
ctx.arc(centerX, centerY, radius, -angle, -firstPointRad, true);
ctx.globalCompositeOperation = 'source-over';
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
ctx.stroke();
draw(y);
ctx.save();
ctx.translate(currentX + radius, y)
ctx.rotate(jetAngle - 1.6);
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(jet, -106, -80, 212, 160);
ctx.restore();
}
function jetPositionLine(y) {
ctx.beginPath();
ctx.lineTo(tabletOffset, firstPoint);
ctx.lineTo(tabletOffset, y);
ctx.lineWidth = 3;
ctx.strokeStyle = '#fff';
ctx.stroke();
draw(y);
ctx.beginPath();
ctx.save();
ctx.globalCompositeOperation = 'source-over';
ctx.drawImage(jet, tabletOffset - 106, y - 80, 212, 160);
ctx.restore();
}
function onScroll() {
requestAnimationFrame(scrollCanvas);
};
function scrollCanvas() {
var prevScroll = scrolled;
scrolled = window.pageYOffset;
toUp = prevScroll < scrolled;
var positionY = scrolled + jetOnScroll;
if (positionY >= firstPoint) {
if (positionY <= lastPoint) {
ctx.clearRect(0, 0, canvasClearWidth, canvasHeight);
if (mediaTablet) {
jetPositionLine(positionY);
} else {
jetPosition(positionY);
}
} else {
$('.history__item').eq(lastIndex).removeClass('darkened');
}
}
if (!mediaMobile && !mediaTablet) {
parallaxScroll();
}
}

Related

Javascript line and point angle collision

I want to move the balls in correct direction when bat collide with them, like in this example
It doesn't have to be this good though. Working correctly is the goal here.
So far, what I've got can be seen in the following url:
https://jsfiddle.net/qphqvntx/4/
The problem is with the collision, when bat hit the balls. It's behaving very weird.
//Canvas Variable
var mainCanvas = document.getElementById("mainCanvas");
var ctx = mainCanvas.getContext("2d");
var canvasHeight = mainCanvas.height;
var canvasWidth = mainCanvas.width;
var borderRadius = 10;
var bottomRadius = 120;
var gravity = 0.2;
var animate = false;
//Ball Object related variable
var balls = [];
var ballObj = {
x: 0,
y: 0,
velocity: {x: 0, y: 0},
};
var ball = '';
var debugBall = '';
var ballRadius = 10;
var dumping = 0.99;
var ballSpeed = 6;
var force = 1.8;
var setBallTimer = 150;
var updateBallTimer = 0;
var target;
var distanceX;
var distancey;
var j, balls2;
//Bat related variable
var batXPos = 200;
var batYPos = canvasHeight - bottomRadius - 120;
var batHeight = 100;
var batWidth = 10;
var mouse = [0, 0];
var point = [170, 175];
var dx, dy;
//run related variable
var oneRunLine = 60;
var twoRunLine = 90;
var fourRunLine = 100;
var outTopLine = 450;
var oneRunChain = canvasHeight - bottomRadius;
var twoRunChain = canvasHeight - bottomRadius - oneRunLine;
var fourRunChain = canvasHeight - bottomRadius - oneRunLine - twoRunLine;
var sixRunChain = canvasHeight - bottomRadius - oneRunLine - twoRunLine - fourRunLine;
var circleUnderMouse;
var mouse = {
x: 0,
y: 0,
down: false
}
var res;
var previousEvent = false;
function executeFrame() {
if (animate) {
requestAnimFrame(executeFrame);
}
ctx.lineWidth = "3";
ctx.strokeRect(0, 0, mainCanvas.width, mainCanvas.height);
ctx.strokeRect(0, 0, mainCanvas.width, mainCanvas.height - bottomRadius);
ctx.fillStyle = 'rgba(255,255,255,0.3)';
ctx.fillRect(0, 0, mainCanvas.width, mainCanvas.height);
update();
if (balls.length != '0') {
balls.forEach(function (ball, j, i) {
drawBall(ball);
createBat();
});
}
}
initializeGame();
function update() {
if (balls.length != '0') {
balls.forEach(function (ball, balli, ballj) {
ball.addGravity();
ball.velocity.y *= dumping;
ball.velocity.x *= dumping;
ball.y += ball.velocity.y;
ball.x += ball.velocity.x * force;
if (hitGround(ball) == true) {
ball.y = mainCanvas.height - bottomRadius;
ball.velocity.y = -Math.abs(ball.velocity.y);
}
if (hitLeft(ball) == true) {
ball.velocity.x = Math.abs(ball.velocity.x);
}
var hit = linePoint(point[0], point[1], mouse[0], mouse[1], ball.x, ball.y, ball);
if (hit == true) {
//console.log("hit");
} else {
//console.log("not yet");
}
for (j = balli + 1; j < balls.length; j++) {
balls2 = ballj[j];
var dx = balls2.x - ball.x;
var dy = balls2.y - ball.y;
var d = Math.sqrt(dx * dx + dy * dy);
if (d < 2 * ballRadius) {
if (d === 0) {
d = 0.1;
}
var unitX = dx / d;
var unitY = dy / d;
var newForce = -1;
var forceX = unitX * newForce;
var forceY = unitY * newForce;
ball.velocity.x += forceX;
ball.velocity.y += forceY;
balls2.velocity.x -= forceX;
balls2.velocity.y -= forceY;
}
}
});
}
updateBallTimer++;
if (updateBallTimer >= setBallTimer) {
createBall();
updateBallTimer = 0;
}
}
function initializeGame() {
createBall();
createBat();
}
function createBall() {
randomPoint(50, 150);
ball = instantiateBall(canvasWidth, target.y, ballObj);
ball.velocity.x -= getRandomNumber(4, 6);
}
function instantiateBall(xPos, yPos, ball) {
ball = {
x: xPos,
y: yPos,
velocity: {x: 0, y: 0},
addGravity: function () {
return this.velocity.y += gravity;
},
onCanvas: false
};
balls.push(ball);
drawBall(ball);
return ball;
}
function drawBall(ball) {
if (ball != '') {
ctx.beginPath();
ctx.arc(ball.x, ball.y, ballRadius, 0, 2 * Math.PI, false);
ctx.fillStyle = "#000";
ctx.fill();
}
}
function createBat() {
// ctx.clearRect(0, 0, width, height)
dx = mouse[0] - point[0],
dy = mouse[1] - point[1];
rot = Math.atan2(dy, dx);
ctx.fillStyle = 'red';
ctx.fillRect(point[0], point[1], 10, 10);
ctx.fillStyle = 'gray';
ctx.save();
ctx.translate(point[0], point[1]);
ctx.rotate(rot);
ctx.fillRect(0, 0, batHeight, batWidth);
ctx.moveTo(point[0], point[1]);
ctx.lineTo(point[0] + (mouse[0] - point[0]) + 0.5, point[1] + (mouse[1] - point[1]) * 0.5);
//ctx.stroke();
ctx.restore();
}
function linePoint(x1, y1, x2, y2, px, py, ball) {
var d1 = dist(px, py, x1, y1);
var d2 = dist(px, py, x2, y2);
var lineLen = dist(x1, y1, x2, y2);
var buffer = 3;
var batAngle = Math.atan2(d2, d1);
var batAngleX = Math.sin(batAngle);
var batAngleY = -Math.cos(batAngle);
if (d1 + d2 >= lineLen - buffer && d1 + d2 <= lineLen + buffer) {
var d = 2 * (ball.velocity.x * batAngleX + ball.velocity.y * batAngleY);
ball.x -= d * batAngleX;
ball.x -= d * batAngleY;
ball.velocity.x -= d * batAngleX + res;
ball.velocity.y -= d * batAngleY + res;
return true;
}
return false;
}
function dist(x1, y1, x2, y2) {
var xs = x2 - x1,
ys = y2 - y1;
xs *= xs;
ys *= ys;
return Math.sqrt(xs + ys);
}
function getRandomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function randomPoint(min, max) {
var rndNum = Math.random() * (max - min) + min;
target = {
x: canvasWidth,
y: rndNum
};
// ctx.beginPath();
// ctx.arc(rndNum, canvasHeight, ballRadius, 0, 2 * Math.PI, false);
// ctx.fillStyle = "#ff0";
// ctx.fill();
}
function isOnCanvas(obj) {
if (obj.x <= mainCanvas.width && obj.y <= mainCanvas.height - bottomRadius) {
return true;
}
return false;
}
function hitGround(obj) {
if (obj.y >= mainCanvas.height - bottomRadius) {
//console.log("hit the ground");
return true;
}
return false;
}
function hitTop(obj) {
if (obj.y <= borderRadius) {
//console.log("hit the top");
return true;
}
return false;
}
function hitLeft(obj) {
if (obj.x <= borderRadius) {
//console.log("hit the left");
return true;
}
return false;
}
function hitRight(obj) {
if (obj.x >= mainCanvas.width - borderRadius) {
//console.log("hit the left");
return true;
}
return false;
}
function drawLineRandomPoint(moveX, moveY, lineX, lineY, strColor) {
ctx.beginPath();
ctx.moveTo(moveX, moveY);
ctx.lineTo(lineX, lineY);
ctx.strokeStyle = strColor;
ctx.stroke();
}
mainCanvas.addEventListener('mousemove', function (e) {
e.time = Date.now();
res = makeVelocityCalculator(e, previousEvent);
previousEvent = e;
mouse[0] = e.clientX;
mouse[1] = e.clientY;
});
function makeVelocityCalculator(e_init, e) {
var x = e_init.clientX, new_x, new_y, new_t,
x_dist, y_dist, interval, velocity,
y = e_init.clientY,
t;
if (e === false) {
return 0;
}
t = e.time;
new_x = e.clientX;
new_y = e.clientY;
new_t = Date.now();
x_dist = new_x - x;
y_dist = new_y - y;
interval = new_t - t;
// update values:
x = new_x;
y = new_y;
velocity = Math.sqrt(x_dist * x_dist + y_dist * y_dist) / interval;
return velocity;
}
mainCanvas.addEventListener('mouseover', function (e) {
animate = true;
executeFrame();
});
mainCanvas.addEventListener("mouseout", function (e) {
animate = false;
});
executeFrame();
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
<body>
<canvas id="mainCanvas" height="400" width="600"></canvas>
<script src="main.js" type="text/javascript"></script>
</body>

Same canvas arc different line width

This is what I have at the moment: JsFiddle
But what I'm trying to achieve is something like this: image
I've tried some things but of which none worked out of course..
How would I be able to achieve this? Thanks!
Code:
$('.canvas').each(function(i, item) {
drawFigure($(this).children().attr('id'), $(this).children().attr('class'));
});
function drawFigure(id, className) {
$('#' + id).each(function(i, item) {
var canvas = document.getElementById(id);
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 100;
var endPercent = 210;
var curPerc = 0;
var circ = Math.PI * 1;
var startPoint = -80;
var rotate = false;
if (className == "circle") {
endPercent = 210;
startPoint = -80;
} else if (className == "halfCircle") {
endPercent = 105;
startPoint = 110;
} else if (className == "meter") {
endPercent = 50;
startPoint = 40;
} else if (className == "test") {
context.lineWidth = 40;
}
function animate(current) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.arc(x, y, radius, -(startPoint), ((circ) * current) - startPoint, rotate);
context.stroke();
context.lineCap = "round";
// context.beginPath();
// context.arc(60, 50, 20, -38, 2, true);
// context.stroke();
// context.lineWidth = 10;
curPerc++;
if (curPerc < 9) {
context.lineWidth = 10;
} else {
context.lineWidth = 1;
}
if (curPerc < endPercent) {
requestAnimationFrame(function() {
animate(curPerc / 100)
});
}
}
animate(50);
});
}

How do I properly introduce a delay after a drawImage function in an html5 canvas game?

I'm making a simple memory game and I have put a short delay after 2 cards have been flipped face up and before they are checked for a match. If they are unmatched they will then flip back face down. The problem I'm having is that the delay comes before the second card is flipped face up even though it comes afterwards in the code, resulting in the second card not showing face up. I'm using the drawImage function with pre-loaded images so the call shouldn't have to wait for an image to load. I've added my code below and commented after the draw face up and delay functions.
An online version: http://dtc-wsuv.org/mscoggins/hiragana/seindex.html
var ROWS = 2;
var COLS = 3;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
canvas.width = COLS * 80 + (COLS - 1) * 10 + 40;
canvas.height = ROWS * 100 + (ROWS - 1) * 10 + 40;
var Card = function(x, y, img) {
this.x = x;
this.y = y;
this.w = 80;
this.h = 100;
this.r = 10;
this.img = img;
this.match = false;
};
Card.prototype.drawFaceDown = function() {
this.drawCardBG();
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(this.w / 2 + this.x, this.h / 2 + this.y, 15, 0, 2 * Math.PI);
ctx.fill();
ctx.closePath();
this.isFaceUp = false;
};
Card.prototype.drawFaceUp = function() {
this.drawCardBG();
var imgW = 57;
var imgH = 70;
var imgX = this.x + (this.w - imgW) / 2;
var imgY = this.y + (this.h - imgH) / 2;
ctx.drawImage(this.img, imgX, imgY, imgW, imgH);
this.isFaceUp = true;
};
Card.prototype.drawCardBG = function() {
ctx.beginPath();
ctx.fillStyle = "white";
ctx.fillRect(this.x, this.y, this.w, this.h);
ctx.closePath();
ctx.beginPath();
ctx.strokeStyle = "black";
ctx.lineWidth = 1;
ctx.moveTo(this.x + this.r, this.y);
ctx.lineTo(this.w + this.x - this.r * 2, this.y);
ctx.arcTo(this.w + this.x, this.y, this.w + this.x, this.y + this.r, this.r);
ctx.lineTo(this.w + this.x, this.h + this.y - this.r * 2);
ctx.arcTo(this.w + this.x, this.h + this.y, this.w + this.x - this.r, this.h + this.y, this.r);
ctx.lineTo(this.x + this.r, this.h + this.y);
ctx.arcTo(this.x, this.h + this.y, this.x, this.h + this.y - this.r, this.r);
ctx.lineTo(this.x, this.y + this.r);
ctx.arcTo(this.x, this.y, this.x + this.r, this.y, this.r);
ctx.stroke();
ctx.closePath();
};
Card.prototype.mouseOverCard = function(x, y) {
return x >= this.x && x <= this.x + this.w && y >= this.y && y <= this.y + this.h;
};
var imgLib = [
'img/a.png', 'img/ka.png', 'img/sa.png', 'img/ta.png', 'img/na.png', 'img/ha.png',
'img/ma.png', 'img/ya.png', 'img/ra.png', 'img/wa.png', 'img/i.png', 'img/ki.png',
'img/shi.png', 'img/chi.png', 'img/ni.png', 'img/hi.png', 'img/mi.png', 'img/ri.png',
'img/u.png', 'img/ku.png', 'img/su.png', 'img/tsu.png', 'img/nu.png', 'img/hu.png',
'img/mu.png', 'img/yu.png', 'img/ru.png', 'img/n.png', 'img/e.png', 'img/ke.png',
'img/se.png', 'img/te.png', 'img/ne.png', 'img/he.png', 'img/me.png', 'img/re.png',
'img/o.png', 'img/ko.png', 'img/so.png', 'img/to.png', 'img/no.png', 'img/ho.png',
'img/mo.png', 'img/yo.png', 'img/ro.png', 'img/wo.png'
];
var imgArray = [];
imgArray = imgLib.slice();
var flippedCards = [];
var numTries = 0;
var doneLoading = function() {};
canvas.addEventListener("click", function(e) {
for(var i = 0;i < cards.length;i++) {
var mouseX = e.clientX - e.currentTarget.offsetLeft;
var mouseY = e.clientY - e.currentTarget.offsetTop;
if(cards[i].mouseOverCard(mouseX, mouseY)) {
if(flippedCards.length < 2 && !this.isFaceUp) {
cards[i].drawFaceUp(); //draw card face up
flippedCards.push(cards[i]);
if(flippedCards.length === 2) {
numTries++;
if(flippedCards[0].img.src === flippedCards[1].img.src) {
flippedCards[0].match = true;
flippedCards[1].match = true;
}
delay(600); //delay after image has been drawn
checkMatches();
}
}
}
}
var foundAllMatches = true;
for(var i = 0;i < cards.length;i++) {
foundAllMatches = foundAllMatches && cards[i].match;
}
if(foundAllMatches) {
var winText = "You Win!";
var textWidth = ctx.measureText(winText).width;
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.font = "40px Arial";
ctx.fillText(winText, canvas.width / 2 - textWidth, canvas.height / 2);
}
}, false);
var gameImages = [];
for(var i = 0;i < ROWS * COLS / 2;i++) {
var imgId = Math.floor(Math.random() * imgArray.length);
var match = imgArray[imgId];
gameImages.push(match);
gameImages.push(match);
imgArray.splice(imgId, 1);
}
gameImages.sort(function() {
return 0.5 - Math.random();
});
var cards = [];
var loadedImages = [];
var index = 0;
var imgLoader = function(imgsToLoad, callback) {
for(var i = 0;i < imgsToLoad.length;i++) {
var img = new Image();
img.src = imgsToLoad[i];
loadedImages.push(img);
cards.push(new Card(0, 0, img));
img.onload = function() {
if(loadedImages.length >= imgsToLoad.length) {
callback();
}
};
}
for(var i = 0;i < COLS;i++) {
for(var j = 0;j < ROWS;j++) {
cards[index].x = i * 80 + i * 10 + 20;
cards[index].y = j * 100 + j * 10 + 20;
index++;
}
}
for(var i = 0;i < cards.length;i++) {
cards[i].drawFaceDown();
}
};
imgLoader(gameImages, doneLoading);
var checkMatches = function() {
for(var i = 0;i < cards.length;i++) {
if(!cards[i].match) {
cards[i].drawFaceDown();
}
}
flippedCards = [];
};
var delay = function(ms) {
var start = new Date().getTime();
var timer = false;
while(!timer) {
var now = new Date().getTime();
if(now - start > ms) {
timer = true;
}
}
};
The screen won't be refreshed until your function exits. The usual way to handle this is using setTimeout. Put the code that you want to run after the delay in a separate function and use setTimeout to call that function after the desired delay. Note that setTimeout will return immediately; the callback will be executed later.
I have implemented this below, just replace your click event listener code with the following:
canvas.addEventListener("click", function(e) {
for(var i = 0;i < cards.length;i++) {
var mouseX = e.clientX - e.currentTarget.offsetLeft;
var mouseY = e.clientY - e.currentTarget.offsetTop;
if(cards[i].mouseOverCard(mouseX, mouseY)) {
if(flippedCards.length < 2 && !this.isFaceUp) {
cards[i].drawFaceUp(); //draw card face up
flippedCards.push(cards[i]);
if(flippedCards.length === 2) {
numTries++;
if(flippedCards[0].img.src === flippedCards[1].img.src) {
flippedCards[0].match = true;
flippedCards[1].match = true;
}
//delay(600); //delay after image has been drawn
//checkMatches();
window.setTimeout(checkMatchesAndCompletion, 600);
}
}
}
}
function checkMatchesAndCompletion() {
checkMatches();
var foundAllMatches = true;
for(var i = 0;i < cards.length;i++) {
foundAllMatches = foundAllMatches && cards[i].match;
}
if(foundAllMatches) {
var winText = "You Win!";
var textWidth = ctx.measureText(winText).width;
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "red";
ctx.font = "40px Arial";
ctx.fillText(winText, canvas.width / 2 - textWidth, canvas.height / 2);
}
}
}, false);

Circle animation random color

Hi I try to create an animation with a circle. The function drawRandom(drawFunctions) should pic one of the three drawcircle functions and should bring it on the canvas. Now the problem is that this function become executed every second (main loop) and the circle change his colour. How can I fix that?
window.onload = window.onresize = function() {
var C = 1; // canvas width to viewport width ratio
var el = document.getElementById("myCanvas");
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * C;
var canvasHeight = viewportHeight;
el.style.position = "fixed";
el.setAttribute("width", canvasWidth);
el.setAttribute("height", canvasHeight);
var x = canvasWidth / 100;
var y = canvasHeight / 100;
var ballx = canvasWidth / 100;
var n;
window.ctx = el.getContext("2d");
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
// draw triangles
function init() {
ballx;
return setInterval(main_loop, 1000);
}
function drawcircle1()
{
var radius = x * 5;
ctx.beginPath();
ctx.arc(ballx * 108, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'yellow';
ctx.fill();
}
function drawcircle2()
{
var radius = x * 5;
ctx.beginPath();
ctx.arc(ballx * 108, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'blue';
ctx.fill();
}
function drawcircle3()
{
var radius = x * 5;
ctx.beginPath();
ctx.arc(ballx * 105, canvasHeight / 2, radius, 0, 2 * Math.PI, false);
ctx.fillStyle = 'orange';
ctx.fill();
}
function draw() {
var counterClockwise = false;
ctx.clearRect(0, 0, canvasWidth, canvasHeight);
//first halfarc
ctx.beginPath();
ctx.arc(x * 80, y * 80, y * 10, 0 * Math.PI, 1 * Math.PI, counterClockwise);
ctx.lineWidth = y * 1;
ctx.strokeStyle = 'black';
ctx.stroke();
// draw stop button
ctx.beginPath();
ctx.moveTo(x * 87, y * 2);
ctx.lineTo(x * 87, y * 10);
ctx.lineWidth = x;
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x * 95, y * 2);
ctx.lineTo(x * 95, y * 10);
ctx.lineWidth = x;
ctx.stroke();
function drawRandom(drawFunctions){
//generate a random index
var randomIndex = Math.floor(Math.random() * drawFunctions.length);
//call the function
drawFunctions[randomIndex]();
}
drawRandom([drawcircle1, drawcircle2, drawcircle3]);
}
function update() {
ballx -= 0.1;
if (ballx < 0) {
ballx = -radius;
}
}
function main_loop() {
draw();
update();
collisiondetection();
}
init();
function initi() {
console.log('init');
// Get a reference to our touch-sensitive element
var touchzone = document.getElementById("myCanvas");
// Add an event handler for the touchstart event
touchzone.addEventListener("mousedown", touchHandler, false);
}
function touchHandler(event) {
// Get a reference to our coordinates div
var can = document.getElementById("myCanvas");
// Write the coordinates of the touch to the div
if (event.pageX < x * 50 && event.pageY > y * 10) {
ballx += 1;
} else if (event.pageX > x * 50 && event.pageY > y * 10 ) {
ballx -= 1;
}
console.log(event, x, ballx);
draw();
}
initi();
draw();
}
Take a look at my code that I wrote:
var lastTime = 0;
function requestMyAnimationFrame(callback, time)
{
var t = time || 16;
var currTime = new Date().getTime();
var timeToCall = Math.max(0, t - (currTime - lastTime));
var id = window.setTimeout(function(){ callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
}
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
canvas.width = window.innerWidth - 20;
canvas.height = window.innerHeight - 20;
canvas.style.width = canvas.width + "px";
canvas.style.height = canvas.height + "px";
var circles = [];
var mouse =
{
x: 0,
y: 0
}
function getCoordinates(x, y)
{
return "(" + x + ", " + y + ")";
}
function getRatio(n, d)
{
// prevent division by 0
if (d === 0 || n === 0)
{
return 0;
}
else
{
return n/d;
}
}
function Circle(x,y,d,b,s,c)
{
this.x = x;
this.y = y;
this.diameter = Math.round(d);
this.radius = Math.round(d/2);
this.bounciness = b;
this.speed = s;
this.color = c;
this.deltaX = 0;
this.deltaY = 0;
this.drawnPosition = "";
this.fill = function()
{
context.beginPath();
context.arc(this.x+this.radius,this.y+this.radius,this.radius,0,Math.PI*2,false);
context.closePath();
context.fill();
}
this.clear = function()
{
context.fillStyle = "#ffffff";
this.fill();
}
this.draw = function()
{
if (this.drawnPosition !== getCoordinates(this.x, this.y))
{
context.fillStyle = this.color;
// if commented, the circle will be drawn if it is in the same position
//this.drawnPosition = getCoordinates(this.x, this.y);
this.fill();
}
}
this.keepInBounds = function()
{
if (this.x < 0)
{
this.x = 0;
this.deltaX *= -1 * this.bounciness;
}
else if (this.x + this.diameter > canvas.width)
{
this.x = canvas.width - this.diameter;
this.deltaX *= -1 * this.bounciness;
}
if (this.y < 0)
{
this.y = 0;
this.deltaY *= -1 * this.bounciness;
}
else if (this.y+this.diameter > canvas.height)
{
this.y = canvas.height - this.diameter;
this.deltaY *= -1 * this.bounciness;
}
}
this.followMouse = function()
{
// deltaX/deltaY will currently cause the circles to "orbit" around the cursor forever unless it hits a wall
var centerX = Math.round(this.x + this.radius);
var centerY = Math.round(this.y + this.radius);
if (centerX < mouse.x)
{
// circle is to the left of the mouse, so move the circle to the right
this.deltaX += this.speed;
}
else if (centerX > mouse.x)
{
// circle is to the right of the mouse, so move the circle to the left
this.deltaX -= this.speed;
}
else
{
//this.deltaX = 0;
}
if (centerY < mouse.y)
{
// circle is above the mouse, so move the circle downwards
this.deltaY += this.speed;
}
else if (centerY > mouse.y)
{
// circle is under the mouse, so move the circle upwards
this.deltaY -= this.speed;
}
else
{
//this.deltaY = 0;
}
this.x += this.deltaX;
this.y += this.deltaY;
this.x = Math.round(this.x);
this.y = Math.round(this.y);
}
}
function getRandomDecimal(min, max)
{
return Math.random() * (max-min) + min;
}
function getRoundedNum(min, max)
{
return Math.round(getRandomDecimal(min, max));
}
function getRandomColor()
{
// array of three colors
var colors = [];
// go through loop and add three integers between 0 and 255 (min and max color values)
for (var i = 0; i < 3; i++)
{
colors[i] = getRoundedNum(0, 255);
}
// return rgb value (RED, GREEN, BLUE)
return "rgb(" + colors[0] + "," + colors[1] + ", " + colors[2] + ")";
}
function createCircle(i)
{
// diameter of circle
var minDiameter = 25;
var maxDiameter = 50;
// bounciness of circle (changes speed if it hits a wall)
var minBounciness = 0.2;
var maxBounciness = 0.65;
// speed of circle (how fast it moves)
var minSpeed = 0.3;
var maxSpeed = 0.45;
// getRoundedNum returns a random integer and getRandomDecimal returns a random decimal
var x = getRoundedNum(0, canvas.width);
var y = getRoundedNum(0, canvas.height);
var d = getRoundedNum(minDiameter, maxDiameter);
var c = getRandomColor();
var b = getRandomDecimal(minBounciness, maxBounciness);
var s = getRandomDecimal(minSpeed, maxSpeed);
// create the circle with x, y, diameter, bounciness, speed, and color
circles[i] = new Circle(x,y,d,b,s,c);
}
function makeCircles()
{
var maxCircles = getRoundedNum(2, 5);
for (var i = 0; i < maxCircles; i++)
{
createCircle(i);
}
}
function drawCircles()
{
var ii = 0;
for (var i = 0; ii < circles.length; i++)
{
if (circles[i])
{
circles[i].draw();
ii++;
}
}
}
function clearCircles()
{
var ii = 0;
for (var i = 0; ii < circles.length; i++)
{
if (circles[i])
{
circles[i].clear();
ii++;
}
}
}
function updateCircles()
{
var ii = 0;
for (var i = 0; ii < circles.length; i++)
{
if (circles[i])
{
circles[i].keepInBounds();
circles[i].followMouse();
ii++;
}
}
}
function update()
{
requestMyAnimationFrame(update,10);
updateCircles();
}
function draw()
{
requestMyAnimationFrame(draw,1000/60);
context.clearRect(0,0,canvas.width,canvas.height);
drawCircles();
}
window.addEventListener("load", function()
{
window.addEventListener("mousemove", function(e)
{
mouse.x = e.layerX || e.offsetX;
mouse.y = e.layerY || e.offsetY;
});
makeCircles();
update();
draw();
});

Why does my Javascript animation slowdown after a while

So I am in the process of making this rhythm game with canvas, all that it does up to this point is render the receivers (the point the blocks are going to collide with so the user can press the corresponding buttons and get points) and it renders the dancer animation. For some reason though after the page is open for a while the dancer slows down significantly and continues to gradually slow.
I can't figure out why or how to fix it. Anyone have any ideas?
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 600;
document.body.appendChild(canvas);
var spritesheet = null;
var dancer = {
time:0,
speed:0,
image:null,
x:0,
y:0,
currentFrame:0,
width:50,
height:100,
ready:false
}
function onload() {
spritesheet = new Image();
spritesheet.src = "danceSheet.png";
spritesheet.onload = initiate;
}
function initiate() {
game.startTime = new Date().getTime() / 1000;
dancer.x = (canvas.width / 2) - dancer.width;
dancer.y = 120;
game.initiateReceivers();
main();
}
var game = {
startTime:0,
currentTime:0,
receivers:[],
senders:[],
lanes:[],
drawDancer: function() {
ctx.drawImage(spritesheet, dancer.width * dancer.currentFrame, 0, dancer.width, dancer.height, dancer.x, dancer.y, dancer.width, dancer.height );
},
clearWindow: function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
initiateReceivers: function() {
var distanceRate = canvas.width / 4;
var position = 30;
for(initiates = 0; initiates < 4; initiates++) {
this.receivers[initiates] = new receivers;
this.receivers[initiates].x = position;
this.receivers[initiates].y = 300;
position += distanceRate;
}
}
}
var gameUpdates = {
updateMovement: function() {
game.currentTime = new Date().getTime() / 1000;
dancer.time = game.currentTime - game.startTime;
if(dancer.time >= 0.1) {
game.startTime = new Date().getTime() / 1000;
dancer.currentFrame += 1;
if(dancer.currentFrame == 12) dancer.currentFrame = 0;
}
},
collision: function(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2);
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
return true;
}
return false;
}
}
function receivers() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
}
function senders() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
this.lane = 0;
this.status = true;
}
function update() {
gameUpdates.updateMovement();
}
function render() {
game.clearWindow();
game.drawDancer();
game.receivers.forEach( function(receiver) {
ctx.rect(receiver.x,receiver.y,receiver.width,receiver.height);
ctx.fillStyle = "red";
ctx.fill();
}
)
}
function main() {
update();
render();
requestAnimationFrame(main);
}
I'm trying to get an idea of the slowness you're seeing so I adjusted your code to get a frames-per-second. Haven't found the cause yet for the drop.
Update
I found that the frames were dropping from drawing the rectangles. I've altered the code to use fillRect put the fill style outside of the loop. This seems to have fixed the frame drop.
var canvas = document.createElement("canvas");
var ctx = canvas.getContext("2d");
canvas.width = 500;
canvas.height = 600;
document.body.appendChild(canvas);
var spritesheet = null;
var dancer = {
time: 0,
speed: 0,
image: null,
x: 0,
y: 0,
currentFrame: 0,
width: 50,
height: 100,
ready: false
}
function onload() {
spritesheet = document.createElement('canvas');
spritesheet.width = (dancer.width * 12);
spritesheet.height = dancer.height;
var ctx = spritesheet.getContext('2d');
ctx.font = "30px Arial";
ctx.fillStyle = "black";
ctx.strokeStyle = "red";
for (var i = 0; i < 12; i++) {
var x = (i * dancer.width) + 10;
ctx.fillText(i,x,60);
ctx.beginPath();
ctx.rect(i*dancer.width,0,dancer.width,dancer.height);
ctx.stroke();
}
initiate();
}
function initiate() {
game.startTime = new Date().getTime() / 1000;
dancer.x = (canvas.width / 2) - dancer.width;
dancer.y = 120;
game.initiateReceivers();
main();
}
var game = {
startTime: 0,
currentTime: 0,
receivers: [],
senders: [],
lanes: [],
drawDancer: function() {
ctx.drawImage(spritesheet, dancer.width * dancer.currentFrame, 0, dancer.width, dancer.height, dancer.x, dancer.y, dancer.width, dancer.height);
//ctx.strokeStyle="red";
//ctx.beginPath();
//ctx.lineWidth = 3;
//ctx.rect(dancer.x,dancer.y,dancer.width,dancer.height);
//ctx.stroke();
},
clearWindow: function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
},
initiateReceivers: function() {
var distanceRate = canvas.width / 4;
var position = 30;
for (initiates = 0; initiates < 4; initiates++) {
this.receivers[initiates] = new receivers;
this.receivers[initiates].x = position;
this.receivers[initiates].y = 300;
position += distanceRate;
}
}
};
var gameUpdates = {
updateMovement: function() {
game.currentTime = new Date().getTime() / 1000;
dancer.time = game.currentTime - game.startTime;
if (dancer.time >= 0.1) {
game.startTime = new Date().getTime() / 1000;
dancer.currentFrame += 1;
if (dancer.currentFrame == 12) dancer.currentFrame = 0;
}
},
collision: function(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2);
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
return true;
}
return false;
}
}
function receivers() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
}
function senders() {
this.x = 0;
this.y = 0;
this.width = 60;
this.height = 10;
this.lane = 0;
this.status = true;
}
function update() {
gameUpdates.updateMovement();
}
function render() {
game.clearWindow();
game.drawDancer();
ctx.fillStyle = "red";
game.receivers.forEach(function(receiver) {
ctx.fillRect(receiver.x, receiver.y, receiver.width, receiver.height);
});
ctx.fillText(fps,10,10);
}
var fps = 0;
var frames = 0;
function getFps() {
fps = frames;
frames = 0;
setTimeout(getFps,1000);
}
getFps();
function main() {
update();
render();
frames++;
requestAnimationFrame(main);
}
onload();
canvas {
border:1px solid blue;
}

Categories