restart html5 animation in a given interval - javascript

I have a html5 canvas in which something is animated within a given time. what i'd like to do is repeat this code ("reset and restart" the drawing) in a certain interval.
var canvas = $("#paper")[0];
var c = canvas.getContext("2d");
var startX = 50;
var startY = 50;
var endX = 100;
var endY = 100;
var amount = 0;
setInterval(function() {
amount += 0.05; // change to alter duration
if (amount > 1) amount = 1;
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "black";
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount,
startY + (endY - startY) * amount);
c.stroke();
}, 30);​

Assign the setInterval function to a variable. Then you can clear it
var interval = setInterval(function () {});
clearInterval(interval);
In you case (function calle setup) you could use:
var interval = setInterval(setup, 30);
And when you want to clear it call:
clearInterval(interval).

Related

How can I reverse the direction of this square after it reaches a certain value?

I'm trying to create an idle animation where the red rectangle moves back and forth slightly in a loop. For some reason once it reaches the specified threshhold instead of proceeding to move in the opposite direction, it just stops.
What did I do wrong?
<canvas id="myCanvas" width="1500" height="500" style="border:1px solid #c3c3c3;">
Your browser does not support the canvas element.
</canvas>
<script>
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// Spaceship structure
var shipWidth = 250;
var shipHeight = 100;
// Canvas parameters
var cWidth = canvas.width;
var cHeight = canvas.height;
// Positioning variables
var centerWidthPosition = (cWidth / 2) - (shipWidth / 2);
var centerHeightPosition = (cHeight / 2) - (shipHeight / 2);
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function drawShip(){
ctx.clearRect(0, 0, cWidth, cHeight);
ctx.fillStyle = "#FF0000";
ctx.fillRect(centerWidthPosition,centerHeightPosition,shipWidth,shipHeight);
centerWidthPosition--;
if (centerWidthPosition < 400){
++centerWidthPosition;
}
requestAnimationFrame(drawShip);
}
drawShip();
</script>
#TheAmberlamps explained why it's doing that. Here I offer you a solution to achieve what I believe you are trying to do.
Use a velocity variable that changes magnitude. X position always increases by velocity value. Velocity changes directions at screen edges.
// use a velocity variable
var xspeed = 1;
// always increase by velocity
centerWidthPosition += xspeed;
// screen edges are 0 and 400 in this example
if (centerWidthPosition > 400 || centerWidthPosition < 0){
xspeed *= -1; // change velocity direction
}
I added another condition in your if that causes the object to bounce back and forth. Remove the selection after || if you don't want it doing that.
Your function is caught in a loop; once centerWidthPosition reaches 399 your conditional makes it increment back up to 400, and then it decrements back to 399.
here is another one as a brain teaser - how would go by making this animation bounce in the loop - basically turn text into particles and then reverse back to text and reverse back to particles and back to text and so on and on and on infinitely:
var random = Math.random;
window.onresize = function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
};
window.onresize();
var ctx = canvas.getContext('2d');
ctx.font = 'bold 50px "somefont"';
ctx.textBaseline = 'center';
ctx.fillStyle = 'rgba(255,255,255,1)';
var _particles = [];
var particlesLength = 0;
var currentText = "SOMETEXT";
var createParticle = function createParticle(x, y) {_particles.push(new Particle(x, y));};
var checkAlpha = function checkAlpha(pixels, i) {return pixels[i * 4 + 3] > 0;};
var createParticles = function createParticles() {
var textSize = ctx.measureText(currentText);
ctx.fillText(currentText,Math.round((canvas.width / 2) - (textSize.width / 2)),Math.round(canvas.height / 2));
var imageData = ctx.getImageData(1, 1, canvas.width, canvas.height);
var pixels = imageData.data;
var dataLength = imageData.width * imageData.height;
for (var i = 0; i < dataLength; i++) {
var currentRow = Math.floor(i / imageData.width);
var currentColumn = i - Math.floor(i / imageData.height);
if (currentRow % 2 || currentColumn % 2) continue;
if (checkAlpha(pixels, i)) {
var cy = ~~(i / imageData.width);
var cx = ~~(i - (cy * imageData.width));
createParticle(cx, cy);
}}
particlesLength = _particles.length;
};
var Point = function Point(x, y) {
this.set(x, y);
};
Point.prototype = {
set: function (x, y) {
x = x || 0;
y = y || x || 0;
this._sX = x;
this._sY = y;
this.reset();
},
add: function (point) {
this.x += point.x;
this.y += point.y;
},
multiply: function (point) {
this.x *= point.x;
this.y *= point.y;
},
reset: function () {
this.x = this._sX;
this.y = this._sY;
return this;
},
};
var FRICT = new Point(0.98);//set to 0 if no flying needed
var Particle = function Particle(x, y) {
this.startPos = new Point(x, y);
this.v = new Point();
this.a = new Point();
this.reset();
};
Particle.prototype = {
reset: function () {
this.x = this.startPos.x;
this.y = this.startPos.y;
this.life = Math.round(random() * 300);
this.isActive = true;
this.v.reset();
this.a.reset();
},
tick: function () {
if (!this.isActive) return;
this.physics();
this.checkLife();
this.draw();
return this.isActive;
},
checkLife: function () {
this.life -= 1;
this.isActive = !(this.life < 1);
},
draw: function () {
ctx.fillRect(this.x, this.y, 1, 1);
},
physics: function () {
if (performance.now()<nextTime) return;
this.a.x = (random() - 0.5) * 0.8;
this.a.y = (random() - 0.5) * 0.8;
this.v.add(this.a);
this.v.multiply(FRICT);
this.x += this.v.x;
this.y += this.v.y;
this.x = Math.round(this.x * 10) / 10;
this.y = Math.round(this.y * 10) / 10;
}
};
var nextTime = performance.now()+3000;
createParticles();
function clearCanvas() {
ctx.fillStyle = 'rgba(0,0,0,1)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
(function clearLoop() {
clearCanvas();
requestAnimationFrame(clearLoop);
})();
(function animLoop(time) {
ctx.fillStyle = 'rgba(255,255,255,1)';
var isAlive = true;
for (var i = 0; i < particlesLength; i++) {
if (_particles[i].tick()) isAlive = true;
}
requestAnimationFrame(animLoop);
})();
function resetParticles() {
for (var i = 0; i < particlesLength; i++) {
_particles[i].reset();
}}

How can we stop this HTML5 Canvas wheel at exact points after spin?

In the Below code link HTML5 canvas spin wheel game. I want to stop this canvas at a user-defined position as if the user wants to stop always at 200 texts or 100 texts like that.
Currently, it is stopping at random points I want to control where to stop as in if I want to stop circle at 100 or 200 or 0 whenever I want.
How can we achieve that??? Can anyone Help!!!!!
Attached Codepen link also.
Html file
<div>
<canvas class="spin-wheel" id="canvas" width="300" height="300"></canvas>
</div>
JS file
var color = ['#ca7','#7ac','#77c','#aac','#a7c','#ac7', "#caa"];
var label = ['10', '200','50','100','5','500',"0"];
var slices = color.length;
var sliceDeg = 360/slices;
var deg = 270;
var speed = 5;
var slowDownRand = 0;
var ctx = canvas.getContext('2d');
var width = canvas.width; // size
var center = width/2; // center
var isStopped = false;
var lock = false;
function rand(min, max) {
return Math.random() * (max - min) + min;
}
function deg2rad(deg){ return deg * Math.PI/180; }
function drawSlice(deg, color){
ctx.beginPath();
ctx.fillStyle = color;
ctx.moveTo(center, center);
ctx.arc(center, center, width/2, deg2rad(deg), deg2rad(deg+sliceDeg));
console.log(center, center, width/2, deg2rad(deg), deg2rad(deg+sliceDeg))
ctx.lineTo(center, center);
ctx.fill();
}
function drawText(deg, text) {
ctx.save();
ctx.translate(center, center);
ctx.rotate(deg2rad(deg));
ctx.textAlign = "right";
ctx.fillStyle = "#fff";
ctx.font = 'bold 30px sans-serif';
ctx.fillText(text, 130, 10);
ctx.restore();
}
function drawImg() {
ctx.clearRect(0, 0, width, width);
for(var i=0; i<slices; i++){
drawSlice(deg, color[i]);
drawText(deg+sliceDeg/2, label[i]);
deg += sliceDeg;
}
}
// ctx.rotate(360);
function anim() {
isStopped = true;
deg += speed;
deg %= 360;
// Increment speed
if(!isStopped && speed<3){
speed = speed+1 * 0.1;
}
// Decrement Speed
if(isStopped){
if(!lock){
lock = true;
slowDownRand = rand(0.994, 0.998);
}
speed = speed>0.2 ? speed*=slowDownRand : 0;
}
// Stopped!
if(lock && !speed){
var ai = Math.floor(((360 - deg - 90) % 360) / sliceDeg); // deg 2 Array Index
console.log(slices)
ai = (slices+ai)%slices; // Fix negative index
return alert("You got:\n"+ label[ai] ); // Get Array Item from end Degree
// ctx.arc(150,150,150,8.302780584487312,9.200378485512967);
// ctx.fill();
}
drawImg();
window.requestAnimationFrame(anim);
}
function start() {
anim()
}
drawImg();
Spin wheel codepen
Ease curves
If you where to plot the wheel position over time as it slows to a stop you would see a curve, a curve that looks like half a parabola.
You can get the very same curve if you plot the value of x squared in the range 0 to 1 as in the next snippet, the red line shows the plot of f(x) => x * x where 0 <= x <= 1
Unfortunately the plot is the wrong way round and needs to be mirrored in x and y. That is simple by changing the function to f(x) => 1 - (1 - x) ** 2 (Click the canvas to get the yellow line)
const size = 200;
const ctx = Object.assign(document.createElement("canvas"),{width: size, height: size / 2}).getContext("2d");
document.body.appendChild(ctx.canvas);
ctx.canvas.style.border = "2px solid black";
plot(getData());
plot(unitCurve(x => x * x), "#F00");
ctx.canvas.addEventListener("click",()=>plot(unitCurve(x => 1 - (1 - x) ** 2), "#FF0"), {once: true});
function getData(chart = []) {
var pos = 0, speed = 9, deceleration = 0.1;
while(speed > 0) {
chart.push(pos);
pos += speed;
speed -= deceleration;
}
return chart;
}
function unitCurve(f,chart = []) {
const step = 1 / 100;
var x = 0;
while(x <= 1) {
chart.push(f(x));
x += step
}
return chart;
}
function plot(chart, col = "#000") {
const xScale = size / chart.length, yScale = size / 2 / Math.max(...chart);
ctx.setTransform(xScale, 0, 0, yScale, 0, 0);
ctx.strokeStyle = col;
ctx.beginPath();
chart.forEach((y,x) => ctx.lineTo(x,y));
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.stroke();
}
In animation this curve is an ease in.
We can create function that uses the ease function, takes the time and returns the position of the wheel. We can provide some additional values that controls how long the wheel will take to stop, the starting position and the all important stop position.
function wheelPos(currentTime, startTime, endTime, startPos, endPos) {
// first scale the current time to a value from 0 to 1
const x = (currentTime - startTime) / (endTime - startTime);
// rather than the square, we will use the square root (this flips the curve)
const xx = x ** (1 / 2);
// convert the value to a wheel position
return xx * (endPos - startPos) + startPos;
}
Demo
The demo puts it in action. Rather than using the square root the function in the demo defines the root as the constant slowDownRate = 2.6. The smaller this value the greater start speed and the slower the end speed. A value of 1 means it will move at a constant speed and then stop. The value must be > 0 and < 1
requestAnimationFrame(mainLoop);
Math.TAU = Math.PI * 2;
const size = 160;
const ctx = Object.assign(document.createElement("canvas"),{width: size, height: size}).getContext("2d");
document.body.appendChild(ctx.canvas);
const stopAt = document.createElement("div")
document.body.appendChild(stopAt);
ctx.canvas.style.border = "2px solid black";
var gTime; // global time
const colors = ["#F00","#F80","#FF0","#0C0","#08F","#00F","#F0F"];
const wheelSteps = 12;
const minSpins = 3 * Math.TAU; // min number of spins before stopping
const spinTime = 6000; // in ms
const slowDownRate = 1 / 1.8; // smaller this value the greater the ease in.
// Must be > 0
var startSpin = false;
var readyTime = 0;
ctx.canvas.addEventListener("click",() => { startSpin = !wheel.spinning });
stopAt.textContent = "Click wheel to spin";
const wheel = { // hold wheel related variables
img: createWheel(wheelSteps),
endTime: performance.now() - 2000,
startPos: 0,
endPos: 0,
speed: 0,
pos: 0,
spinning: false,
set currentPos(val) {
this.speed = (val - this.pos) / 2; // for the wobble at stop
this.pos = val;
},
set endAt(pos) {
this.endPos = (Math.TAU - (pos / wheelSteps) * Math.TAU) + minSpins;
this.endTime = gTime + spinTime;
this.startTime = gTime;
stopAt.textContent = "Spin to: "+(pos + 1);
}
};
function wheelPos(currentTime, startTime, endTime, startPos, endPos) {
const x = ((currentTime - startTime) / (endTime - startTime)) ** slowDownRate;
return x * (endPos - startPos) + startPos;
}
function mainLoop(time) {
gTime = time;
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0, 0, size, size);
if (startSpin && !wheel.spinning) {
startSpin = false;
wheel.spinning = true;
wheel.startPos = (wheel.pos % Math.TAU + Math.TAU) % Math.TAU;
wheel.endAt = Math.random() * wheelSteps | 0;
} else if (gTime <= wheel.endTime) { // wheel is spinning get pos
wheel.currentPos = wheelPos(gTime, wheel.startTime, wheel.endTime, wheel.startPos, wheel.endPos);
readyTime = gTime + 1500;
} else { // wobble at stop
wheel.speed += (wheel.endPos - wheel.pos) * 0.0125;
wheel.speed *= 0.95;
wheel.pos += wheel.speed;
if (wheel.spinning && gTime > readyTime) {
wheel.spinning = false;
stopAt.textContent = "Click wheel to spin";
}
}
// draw wheel
ctx.setTransform(1,0,0,1,size / 2, size / 2);
ctx.rotate(wheel.pos);
ctx.drawImage(wheel.img, -size / 2 , - size / 2);
// draw marker shadow
ctx.setTransform(1,0,0,1,1,4);
ctx.fillStyle = "#0004";
ctx.beginPath();
ctx.lineTo(size - 13, size / 2);
ctx.lineTo(size, size / 2 - 7);
ctx.lineTo(size, size / 2 + 7);
ctx.fill();
// draw marker
ctx.setTransform(1,0,0,1,0,0);
ctx.fillStyle = "#F00";
ctx.beginPath();
ctx.lineTo(size - 13, size / 2);
ctx.lineTo(size, size / 2 - 7);
ctx.lineTo(size, size / 2 + 7);
ctx.fill();
requestAnimationFrame(mainLoop);
}
function createWheel(steps) {
const ctx = Object.assign(document.createElement("canvas"),{width: size, height: size}).getContext("2d");
const s = size, s2 = s / 2, r = s2 - 4;
var colIdx = 0;
for (let a = 0; a < Math.TAU; a += Math.TAU / steps) {
const aa = a - Math.PI / steps;
ctx.fillStyle = colors[colIdx++ % colors.length];
ctx.beginPath();
ctx.moveTo(s2, s2);
ctx.arc(s2, s2, r, aa, aa + Math.TAU / steps);
ctx.fill();
}
ctx.fillStyle = "#FFF";
ctx.beginPath();
ctx.arc(s2, s2, 12, 0, Math.TAU);
ctx.fill();
ctx.beginPath();
ctx.lineWidth = 2;
ctx.arc(s2, s2, r, 0, Math.TAU);
ctx.moveTo(s2 + 12, s2);
ctx.arc(s2, s2, 12, 0, Math.TAU);
for (let a = 0; a < Math.TAU; a += Math.TAU / steps) {
const aa = a - Math.PI / steps;
ctx.moveTo(Math.cos(aa) * 12 + s2, Math.sin(aa) * 12 + s2);
ctx.lineTo(Math.cos(aa) * r + s2, Math.sin(aa) * r + s2);
}
//ctx.fill("evenodd");
ctx.stroke();
ctx.fillStyle = "#000";
ctx.font = "13px arial black";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
const tr = r - 8;
var idx = 1;
for (let a = 0; a < Math.TAU; a += Math.TAU / steps) {
const dx = Math.cos(a);
const dy = Math.sin(a);
ctx.setTransform(dy, -dx, dx, dy, dx * (tr - 4) + s2, dy * (tr - 4) + s2);
ctx.fillText(""+ (idx ++), 0, 0);
}
return ctx.canvas;
}
body { font-family: arial }

No animation, endless loop in Canvas

I am trying to create what I thought would be a simple Canvas to move a point from A to B using requestAnimationFrame.
http://jsfiddle.net/p1L81yk4/1/
Unfortunately it is not showing anything, and the animation loop seems to be headed towards infinity.
Can anyone explain what I am doing wrong? And is there a flag I can create to show when the animation should stop?
var startX = 10,
startY = 10;
var endX = 200,
endY = 350;
var speed = 1;
var dx = endX - startX;
var dy = endY - startY;
var distance = Math.sqrt(dx * dx + dy * dy);
var moves = distance / speed;
var xunits = (dx / moves);
var yunits = (dy / moves);
var posit = {
x: startX,
y: startY
};
var fps = 60;
var delay = 1000 / 30;
function draw() {
ctx.clearRect(0, 0, canv.width, canv.height);
ctx.save();
ctx.translate(startX, startY);
ctx.beginPath();
ctx.arc(0, 0, 5, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
function move() {
startX += dx;
startY += dy;
console.log(posit);
if (moves > 0) {
moves++;
posit.x += xunits;
posit.y += yunits;
}
}
var start = 0;
function animate() {
running = true;
var current = new Date().getTime(),
delta = current - start;
if (delta >= delay) {
move();
draw();
start = new Date().getTime();
}
anim = requestAnimationFrame(animate);
}
animate();
You should not use save and restore, these functions is for saving and restoring the images.
You should translate posit.x and posit.y instead of startX and startY.
You are changing startX and startY which is not reasonable.
You need a if to determinate if or if not to continue aniamtion.
Which ends up with a working code:
var canv = document.getElementById('canv'),
ctx = canv.getContext('2d');
var startX = 10,
startY = 10;
var endX = 200,
endY = 350;
var speed = 2;
var dx = endX - startX;
var dy = endY - startY;
var distance = Math.sqrt(dx * dx + dy * dy);
var moves = distance / speed;
var xunits = (dx / moves);
var yunits = (dy / moves);
var posit = {
x: startX,
y: startY
};
var fps = 60;
var delay = 1000 / 60;
function draw() {
ctx.clearRect(0, 0, canv.width, canv.height);
//ctx.save();
ctx.translate(posit.x, posit.y);
ctx.beginPath();
ctx.arc(0, 0, 5, 0, Math.PI * 2);
ctx.fill();
ctx.translate(-posit.x, -posit.y);
//ctx.restore();
}
function move() {
//startX += dx;
//startY += dy;
//console.log(posit);
if (moves > 0) {
moves++;
posit.x += xunits;
posit.y += yunits;
}
}
var start = 0;
function animate() {
running = true;
var current = new Date().getTime(),
delta = current - start;
if (delta >= delay) {
move();
draw();
start = new Date().getTime();
}
if(posit.y < endY)
anim = requestAnimationFrame(animate);
}
animate();
<canvas id="canv" width="500" height="500"></canvas>
Using basic trigonometry you can make the entire code look and read easier, with less up front variables. I still need to set quite a lot of variables here, but you would want to mostly calculate them on the fly (which means you would have to move things like angle, from and to value and distance into the myDraw() function).
var myCanvas = document.getElementById('myCanvas');
var myContext = myCanvas.getContext('2d');
myContext.fillStyle = '#000';
// Values expressed as x, y, positions
var fromValue = [300,20];
var toValue = [100,100];
// time expressed in Milliseconds
var time = 5000;
var start = Date.now();
// Get the angle with the arctangent function
// tan(angle) = opposite / adjacent => atan(opposite / adjacent) = angle
// atan2 is used because you can pass it the lengths and it takes care of
// some negative edge cases.
var angle = Math.atan2(toValue[0] - fromValue[0], toValue[1] - fromValue[1]);
// Basic distance because.. Pythagoras. (a^2 = sqrt(b^2 + c^2))
var distance = Math.sqrt(Math.pow(toValue[0] - fromValue[0], 2) + Math.pow(toValue[1] - fromValue[1], 2));
function myDraw(now){
// The max distance can be divided by the total time, multiplied by the time that has passed
var t = (distance / time * (now - start));
var x = fromValue[0] + Math.sin(angle) * t;
var y = fromValue[1] + Math.cos(angle) * t;
// Clear the canvas by resetting its width
myCanvas.width = myCanvas.width;
// Draw the arc at position x and y
myContext.arc(x, y, 3, 0, Math.PI * 2);
myContext.fill();
// Return false if the animation is done.
if(now < start + time) return true;
else return false;
}
function myAnimate(){
// Keep executing as long as myDraw() returns true
if(myDraw(Date.now())) window.requestAnimationFrame(myAnimate);
}
myAnimate();
<canvas width="500" height="500" id="myCanvas" />

How to make the canvas background transparent

I am a newbie on using html5 canvas.
And I'd like to use canvas generate a smoke animation and place it on top of a cigarette image.
The follow code is a sample code of a smoke generator but i don't know how to make the background of the canvas transparent.
I have try different globalCompositeOperation but it seem that i go into a wrong direction.(I don't know much about canvas
I need some help.
Sorry for my poor English.
The following is my code.
And the link is the sample code i used.
http://codepen.io/CucuIonel/pen/hFJlr
function start_smoke( smoke_id ) {
var canvas = document.getElementById(smoke_id);
var w = canvas.width = 200,
h = canvas.height = 150;
var c = canvas.getContext('2d');
var img = new Image();
img.src = 'http://oi41.tinypic.com/4i2aso.jpg';
var position = {x: w / 2, y: h};
var particles = [];
var random = function (min, max) {
return Math.random() * (max - min) * min;
};
function Particle(x, y) {
this.x = x;
this.y = y;
this.velY = -2;
this.velX = (random(1, 10) - 5) / 10;
this.size = random(3, 5) / 10;
this.alpha = 0.3;
this.update = function () {
this.y += this.velY;
this.x += this.velX;
this.velY *= 0.99;
if (this.alpha < 0)
this.alpha = 0;
c.globalAlpha = this.alpha;
c.save();
c.translate(this.x, this.y);
c.scale(this.size, this.size);
c.drawImage(img, -img.width / 2, -img.height / 2);
c.restore();
this.alpha *= 0.96;
this.size += 0.02;//
};
}
var draw = function () {
var p = new Particle(position.x, position.y);
particles.push(p);
while (particles.length > 500) particles.shift();
c.globalAlpha = 1;
c.fillRect(0, 0, w, h);
for (var i = 0; i < particles.length; i++) {
particles[i].update();
}
};
setInterval(draw, 1000 / 20);
}
$(function(){
start_smoke("main_censer_smoke");
});
Canvas transparent by default.
But anyway this question could have a pretty easy solution, which not using globalAlpha, and not using a rgba() color. The simple, effective answer is:
context.clearRect(0,0,width,height);

HTML5 - delay canvas drawing

I have a simple chunk of code to draw a line in a page. My problem is that I don't know much about HTML5 or JS and I need help to set a delay on the drawing of this line.
I want to be able to choose if I want to see it drawing instantly when opening the page or define it to have 5 seconds delay before being draw.
Here it is:
<canvas id="myCanvas" width="1250" height="120"></canvas>
<script>
var canvas = $("#myCanvas")[0];
var c = canvas.getContext("2d");
var amount = 0;
var startX = 164;
var startY = 120;
var endX = 1094;
var endY = 120;
setInterval(function() {
amount += 0.01; // change to alter duration
if (amount > 1) amount = 1;
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "black";
c.lineWidth=1;
c.strokeStyle="#707070";
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
c.stroke();
}, 0);
</script>
Thank you for the help!
Wrap it in a setTimeout:
var canvas = $("#myCanvas")[0];
var c = canvas.getContext("2d");
var amount = 0;
var startX = 164;
var startY = 120;
var endX = 1094;
var endY = 120;
setTimeout(function() {
var interval = setInterval(function() {
amount += 0.01; // change to alter duration
if (amount > 1) {
amount = 1;
clearInterval(interval);
}
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "black";
c.lineWidth=1;
c.strokeStyle="#707070";
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
c.stroke();
}, 0);
}, 3000);
The above waits 3 seconds (3000 milliseconds) before starting the drawing. Also, whenever you start an interval with setInterval you should store the return value so you can stop the interval later. The code above stops the interval when it's done drawing with clearInterval().
Wrap your setInterval call in a setTimeout call. setInterval invokes its function argument repeatedly, where the second argument specifies the delay between invocations. setTimeout invokes its function argument once, after the delay has passed.
function redraw() {
amount += 0.01; // change to alter duration
if (amount > 1) amount = 1;
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "black";
c.lineWidth=1;
c.strokeStyle="#707070";
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
c.stroke();
}
setTimeout(function () { setInterval(redraw, 0) }, 5000);
You need to use setTimeout:
setTimeout(function() {
setInterval(function() {
amount += 0.01; // change to alter duration
if (amount > 1) amount = 1;
c.clearRect(0, 0, canvas.width, canvas.height);
c.strokeStyle = "black";
c.lineWidth=1;
c.strokeStyle="#707070";
c.moveTo(startX, startY);
// lerp : a + (b - a) * f
c.lineTo(startX + (endX - startX) * amount, startY + (endY - startY) * amount);
c.stroke();
}, 0);
}, 5000);
You need to use setTimeout. setTimeout runs a call after a certain delay.
The function used in your script, setInterval, runs the same function over and over again at a certain interval. Strile's answer should help you
Short answer
Use setTimeout function to delay execution. What setTimeout does is set up a timer which will execute specified function after specified amount of time. E.g.
setTimeout(function() {
alert("Hello!");
}, 5000);
will show an alert after 5 seconds (note that time is specified in milliseconds).
Long answer
There are two functions that allow you to schedule a function execution.
setTimeout(func, delay) which will execute given function after given delay. This one is used for one-off execution of functions.
setInterval(func, delay) which will execute given function repeatedly after delay passes. After initial delay, specified function will be executed. Timer will then be reset and function will be executed again once delay passes once more, and so on.
Both functions can be canceled using their counterparts (clearTimeout and clearInterval).

Categories

Resources