Same canvas arc different line width - javascript

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);
});
}

Related

How to optimize canvas or something else on site?

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();
}
}

Why is this text disappearing but not the shape?

How do I make the shape disappear like the text does? I've gone through the code and they're practically identical except that one is created when the user spins the mouse wheel and the other is created when the user clicks on the screen, but the text disappears after time and the triangle does not. I feel like there's something small I must be missing. Here's the code:
<html>
<head>
<script>
var canvas;
var context;
var triangles = [];
var texts = [];
var timer;
var textSayings = ['Cool!', 'Nice!', 'Awesome!', 'Wow!', 'Whoa!', 'Super!', 'Woohoo!', 'Yay!', 'Yeah!', ':)', ':D'];
function init() {
canvas = document.getElementById('canvas');
context = canvas.getContext("2d");
//resize canvas to fit the window
resizeCanvas();
window.addEventListener('resize', resizeCanvas, false);
window.addEventListener('orientationchange', resizeCanvas, false);
canvas.onwheel = function(event) {
handleWheel(event.clientX, event.clientY);
};
canvas.onclick = function(event) {
handleClick(event.clientX, event.clientY);
}
var timer = setInterval(resizeCanvas, 30);
}
function Triangle(x,y,triangleColor) {
this.x = x;
this.y = y;
this.triangleColor = triangleColor;
this.vx = Math.random() * 80 - 40;
this.vy = Math.random() * 80 - 40;
this.time = 250;
}
function Text(x,y,textColor,word) {
this.x = x;
this.y = y;
this.word = word;
this.textColor = textColor;
this.vx = Math.random() * 20 - 10;
this.vy = Math.random() * 20 - 10;
this.time = 300;
}
function handleWheel(x,y) {
var colors = [[255,0,0],[255,255,255],[0,0,255]];
var triangleColor = colors[Math.floor(Math.random()*colors.length)];
triangles.push(new Triangle(x,y,triangleColor));
for (var i=0; i<triangles.length; i++) {
drawTriangle(triangles[i]);
}
}
function handleClick(x,y) {
var colors = [[255,0,0],[255,255,0],[0,0,255]];
var textColor = colors[Math.floor(Math.random()*colors.length)];
texts.push(new Text(x,y,textColor,pickWord()));
for (var i=0; i<texts.length; i++) {
drawText(texts[i]);
}
}
function timeToFade(time) {
if(time > 100) {
return 1;
}
else {
return time / 100;
}
}
function pickWord() {
return textSayings[Math.floor(Math.random() * textSayings.length)];
}
function drawText(text) {
context.font = "bold 80px Verdana";
var gradient=context.createLinearGradient(0,0,canvas.width,0);
gradient.addColorStop("0","magenta");
gradient.addColorStop("0.25","yellow");
gradient.addColorStop("0.5","lime");
gradient.addColorStop("0.75","aqua");
gradient.addColorStop("1.0","magenta");
context.fillStyle = gradient;
context.fillText(text.word,text.x,text.y);
}
function drawTriangle(triangle) {
context.beginPath();
context.moveTo(triangle.x,triangle.y);
context.lineTo(triangle.x+25,triangle.y+25);
context.lineTo(triangle.x+25,triangle.y-25);
var gradient = context.createLinearGradient(0,0,canvas.width,0);
gradient.addColorStop("0","red");
gradient.addColorStop("0.25","salmon");
gradient.addColorStop("0.5","aqua");
gradient.addColorStop("0.75","lime");
gradient.addColorStop("1.0","orange");
context.fillStyle = gradient;
context.fill();
}
function resizeCanvas() {
canvas.width = window.innerWidth-20;
canvas.height = window.innerHeight-20;
fillBackgroundColor();
for (var i=0; i<triangles.length; i++) {
var t = triangles[i];
drawTriangle(t);
if (t.x + t.vx > canvas.width || t.x + t.vx < 0)
t.vx = -t.vx
if (t.y + t.vy > canvas.height || t.y + t.vy < 0)
t.vy = -t.vy
if (t.time === 0) {
triangles.splice(i,1);
}
t.time -= 3;
t.x += t.vx;
t.y += t.vy;
}
for (var i=0; i<texts.length; i++) {
var te = texts[i];
drawText(te);
if (te.x + te.vx > canvas.width || te.x + te.vx < 0)
te.vx = -te.vx
if (te.y + te.vy > canvas.height || te.y + te.vy < 0)
te.vy = -te.vy
if (te.time === 0) {
texts.splice(i,1);
}
te.time -= 3;
te.x += te.vx;
te.y += te.vy;
}
}
function fillBackgroundColor() {
context.globalCompositeOperation = 'source-over';
context.fillStyle = 'rgba(0, 0, 0, 1)';
context.fillRect(0,0,canvas.width,canvas.height);
context.globalCompositeOperation = 'lighter';
}
window.onload = init;
</script>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
</body>
</html>
It's because the triangle time isn't a multiple of 3, while the text time is so when you check this if statement:
if (t.time === 0) {
triangles.splice(i,1);
}
It's never true.
You can fix this by changing the if statement to:
if (t.time <= 0) {
triangles.splice(i,1);
}
This is actually my fault since it's a bug that was in my previous answer. Sorry about that.
jsfiddle:
https://jsfiddle.net/0rst8def/

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();
});

Animate image randomly size continously

The last topic about random moving is answered. But one of my question still not answered yet. About how to create random image size like this : http://ie.microsoft.com/testdrive/Performance/FishIETank/
So what i need? Math.random and for? Please suggest :)
Here's what i've work : http://jsfiddle.net/t9tvnvot/1/
function track(circle, horizontal,vertical,randomly) {
(....)
randomly[0] = Math.random * (circleX + Math.cos(length) * radius); //when i put this, the animation go crazy move
randomly[1] = Math.random * (circleX + Math.sin(length) * radius); //
}
Help & teach me please :)
I think it is prety simple....
Try changing Math.random to Math.random() and it should work...
function track(circle, horizontal,vertical,randomly) {
(....)
randomly[0] = Math.random() * (circleX + Math.cos(length) * radius);
randomly[1] = Math.random() * (circleX + Math.sin(length) * radius);
}
Here is the edited code from the fiddle (this code generate a new position for the butterfly every time, can be far away):
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var circleX = 200;
var circleY = 200;
var radius = 150;
var length = 0;
var setX = 0;
var setY = 0;
var speed = 0.1;
function track(circle, horizontal,vertical) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "red";
context.strokeRect(5, 5, 490, 490);
//circle track move
circle[0] = Math.random() * (circleX + Math.cos(length) * radius);
circle[1] = Math.random() * (circleY + Math.sin(length) * radius);
length += speed;
context.beginPath();
var img = new Image();
img.src = "http://es.fordesigner.com/imguploads/Image/cjbc/zcool/png20080526/1211766513.png";
context.drawImage(img, circle[0], circle[1], circle[2], circle[3]);
context.fill();
}
setInterval(function () {
track
([setX, setY, 50, 50], [setX, setY, 50, 50], [setX,setY, 50, 50]);}, 300);
See also that i increase the time of the interval funtion so it does look so messy...
This is another example but this code the butterfly only appears in the vecinity of the previous position so it doesn seem to desapear:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var length = 0;
var x = 250;
var y = 250;
var setX = 0;
var setY = 0;
var speed = 0.1;
function track(circle, horizontal, vertical) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "red";
context.strokeRect(5, 5, 490, 490);
//movement
if (x >= 0) {
if (x <= 450) {
if (y >= 0) {
if (y <= 450) {
if (Math.floor(Math.random() * 4) == 0) {
x = x + Math.random() + 15;
}
if (Math.floor(Math.random() * 4) == 2) {
y = y + Math.random() + 15;
}
if (Math.floor(Math.random() * 4) == 1) {
x = x - Math.random() - 15;
}
if (Math.floor(Math.random() * 4) == 3) {
y = y - Math.random() - 15;
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x > 450) {
x = 450;
}
if (y > 450) {
y = 450;
}
circle[0] = x;
circle[1] = y;
length += speed;
context.beginPath();
var img = new Image();
img.src = "http://es.fordesigner.com/imguploads/Image/cjbc/zcool/png20080526/1211766513.png";
context.drawImage(img, circle[0], circle[1], circle[2], circle[3]);
context.fill();
}
}
}
}
}
setInterval(function () {
track([setX, setY, 50, 50], [setX, setY, 500, 500], [setX, setY, 50, 50]);
}, 30);
According to your comment you want the butterfly to change also size,
here is the new code:
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var length = 0;
var x = 250;
var y = 250;
var z = 50;
var setX = 0;
var setY = 0;
var speed = 0.1;
function track(circle, horizontal, vertical) {
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);
context.strokeStyle = "red";
context.strokeRect(5, 5, 490, 490);
//movement
if (x >= 0) {
if (x <= 450) {
if (y >= 0) {
if (y <= 450) {
if (Math.floor(Math.random() * 4) == 0) {
x = x + Math.random() + 15;
z = z-15;
}
if (Math.floor(Math.random() * 4) == 2) {
y = y + Math.random() + 15;
z = z-15;
}
if (Math.floor(Math.random() * 4) == 1) {
x = x - Math.random() - 15;
z = z+15;
}
if (Math.floor(Math.random() * 4) == 3) {
y = y - Math.random() - 15;
z = z+10;
}
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
if (x > 450) {
x = 450;
}
if (y > 450) {
y = 450;
}
if (z<20){
z=20;
}
if (z>100){
z=100;
}
circle[0] = x;
circle[1] = y;
circle[3] = z;
circle[2] = z;
length += speed;
context.beginPath();
var img = new Image();
img.src = "http://es.fordesigner.com/imguploads/Image/cjbc/zcool/png20080526/1211766513.png";
context.drawImage(img, circle[0], circle[1], circle[2], circle[3]);
context.fill();
}
}
}
}
}
setInterval(function () {
track([setX, setY, 50, 50], [setX, setY, 500, 500], [setX, setY, 50, 50]);
}, 60);
I just added the math.random with upper(100) and lower limit(20) to the circle[3] and circle[2].
Hope it helps...

Categories