I am working on a radial control similar to the HTML5 wheel of fortune example. I've modified the original here with an example of some additional functionality I require: http://jsfiddle.net/fEm9P/ When you click on the inner kinetic wedges they will shrink and expand within the larger wedges. Unfortunately when I rotate the wheel it lags behind the pointer. It's not too bad here but it's really noticeable on a mobile.
I know this is due to the fact that I'm not caching the wheel. When I do cache the wheel (uncomment lines 239-249) the inner wedges no longer respond to mouse/touch but the response on rotation is perfect. I have also tried adding the inner wedges to a separate layer and caching the main wheel only. I then rotate the inner wheel with the outer one. Doing it this way is a little better but still not viable on mobile.
Any suggestions would be greatly appreciated.
Stephen
//constants
var MAX_ANGULAR_VELOCITY = 360 * 5;
var NUM_WEDGES = 25;
var WHEEL_RADIUS = 410;
var ANGULAR_FRICTION = 0.2;
// globals
var angularVelocity = 360;
var lastRotation = 0;
var controlled = false;
var target, activeWedge, stage, layer, wheel,
pointer, pointerTween, startRotation, startX, startY;
var currentVolume, action;
function purifyColor(color) {
var randIndex = Math.round(Math.random() * 3);
color[randIndex] = 0;
return color;
}
function getRandomColor() {
var r = 100 + Math.round(Math.random() * 55);
var g = 100 + Math.round(Math.random() * 55);
var b = 100 + Math.round(Math.random() * 55);
var color = [r, g, b];
color = purifyColor(color);
color = purifyColor(color);
return color;
}
function bind() {
wheel.on('mousedown', function(evt) {
var mousePos = stage.getPointerPosition();
angularVelocity = 0;
controlled = true;
target = evt.targetNode;
startRotation = this.rotation();
startX = mousePos.x;
startY = mousePos.y;
});
// add listeners to container
document.body.addEventListener('mouseup', function() {
controlled = false;
action = null;
if(angularVelocity > MAX_ANGULAR_VELOCITY) {
angularVelocity = MAX_ANGULAR_VELOCITY;
}
else if(angularVelocity < -1 * MAX_ANGULAR_VELOCITY) {
angularVelocity = -1 * MAX_ANGULAR_VELOCITY;
}
angularVelocities = [];
}, false);
document.body.addEventListener('mousemove', function(evt) {
var mousePos = stage.getPointerPosition();
var x1, y1;
if(action == 'increase') {
x1 = (mousePos.x-(stage.getWidth() / 2));
y1 = (mousePos.y-WHEEL_RADIUS+20);
var r = Math.sqrt(x1 * x1 + y1 * y1);
if (r>500){
r=500;
} else if (r<100){
r=100;
};
currentVolume.setRadius(r);
layer.draw();
} else {
if(controlled && mousePos && target) {
x1 = mousePos.x - wheel.x();
y1 = mousePos.y - wheel.y();
var x2 = startX - wheel.x();
var y2 = startY - wheel.y();
var angle1 = Math.atan(y1 / x1) * 180 / Math.PI;
var angle2 = Math.atan(y2 / x2) * 180 / Math.PI;
var angleDiff = angle2 - angle1;
if ((x1 < 0 && x2 >=0) || (x2 < 0 && x1 >=0)) {
angleDiff += 180;
}
wheel.setRotation(startRotation - angleDiff);
}
};
}, false);
}
function getRandomReward() {
var mainDigit = Math.round(Math.random() * 9);
return mainDigit + '\n0\n0';
}
function addWedge(n) {
var s = getRandomColor();
var reward = getRandomReward();
var r = s[0];
var g = s[1];
var b = s[2];
var angle = 360 / NUM_WEDGES;
var endColor = 'rgb(' + r + ',' + g + ',' + b + ')';
r += 100;
g += 100;
b += 100;
var startColor = 'rgb(' + r + ',' + g + ',' + b + ')';
var wedge = new Kinetic.Group({
rotation: n * 360 / NUM_WEDGES,
});
var wedgeBackground = new Kinetic.Wedge({
radius: WHEEL_RADIUS,
angle: angle,
fillRadialGradientStartRadius: 0,
fillRadialGradientEndRadius: WHEEL_RADIUS,
fillRadialGradientColorStops: [0, startColor, 1, endColor],
fill: '#64e9f8',
fillPriority: 'radial-gradient',
stroke: '#ccc',
strokeWidth: 2,
rotation: (90 + angle/2) * -1
});
wedge.add(wedgeBackground);
var text = new Kinetic.Text({
text: reward,
fontFamily: 'Calibri',
fontSize: 50,
fill: 'white',
align: 'center',
stroke: 'yellow',
strokeWidth: 1,
listening: false
});
text.offsetX(text.width()/2);
text.offsetY(WHEEL_RADIUS - 15);
wedge.add(text);
volume = createVolumeControl(angle, endColor);
wedge.add(volume);
wheel.add(wedge);
}
var activeWedge;
function createVolumeControl(angle, colour){
var volume = new Kinetic.Wedge({
radius: 100,
angle: angle,
fill: colour,
stroke: '#000000',
rotation: (90 + angle/2) * -1
});
volume.on("mousedown touchstart", function() {
currentVolume = this;
action='increase';
});
return volume;
}
function animate(frame) {
// wheel
var angularVelocityChange = angularVelocity * frame.timeDiff * (1 - ANGULAR_FRICTION) / 1000;
angularVelocity -= angularVelocityChange;
if(controlled) {
angularVelocity = ((wheel.getRotation() - lastRotation) * 1000 / frame.timeDiff);
}
else {
wheel.rotate(frame.timeDiff * angularVelocity / 1000);
}
lastRotation = wheel.getRotation();
// pointer
var intersectedWedge = layer.getIntersection({x: stage.width()/2, y: 50});
if (intersectedWedge && (!activeWedge || activeWedge._id !== intersectedWedge._id)) {
pointerTween.reset();
pointerTween.play();
activeWedge = intersectedWedge;
}
}
function init() {
stage = new Kinetic.Stage({
container: 'container',
width: 578,
height: 500
});
layer = new Kinetic.Layer();
wheel = new Kinetic.Group({
x: stage.getWidth() / 2,
y: WHEEL_RADIUS + 20
});
for(var n = 0; n < NUM_WEDGES; n++) {
addWedge(n);
}
pointer = new Kinetic.Wedge({
fillRadialGradientStartPoint: 0,
fillRadialGradientStartRadius: 0,
fillRadialGradientEndPoint: 0,
fillRadialGradientEndRadius: 30,
fillRadialGradientColorStops: [0, 'white', 1, 'red'],
stroke: 'white',
strokeWidth: 2,
lineJoin: 'round',
angle: 30,
radius: 30,
x: stage.getWidth() / 2,
y: 20,
rotation: -105,
shadowColor: 'black',
shadowOffset: {x:3,y:3},
shadowBlur: 2,
shadowOpacity: 0.5
});
// add components to the stage
layer.add(wheel);
layer.add(pointer);
stage.add(layer);
pointerTween = new Kinetic.Tween({
node: pointer,
duration: 0.1,
easing: Kinetic.Easings.EaseInOut,
y: 30
});
pointerTween.finish();
var radiusPlus2 = WHEEL_RADIUS + 2;
wheel.cache({
x: -1* radiusPlus2,
y: -1* radiusPlus2,
width: radiusPlus2 * 2,
height: radiusPlus2 * 2
}).offset({
x: radiusPlus2,
y: radiusPlus2
});
layer.draw();
// bind events
bind();
var anim = new Kinetic.Animation(animate, layer);
//document.getElementById('debug').appendChild(layer.hitCanvas._canvas);
// wait one second and then spin the wheel
setTimeout(function() {
anim.start();
}, 1000);
}
init();
I made a couple of changes to the script which greatly improved the response time. The first was replacing layer.draw() with layer.batchDraw(). As the draw function was being called on each touchmove event it was making the interaction clunky. BatchDraw on the other hand will stack up draw requests internally "limit the number of redraws per second based on the maximum number of frames per second" (http://www.html5canvastutorials.com/kineticjs/html5-canvas-kineticjs-batch-draw).
The jumping around of the canvas I seeing originally when I cached/cleared the wheel was due to the fact that I wasn't resetting the offset on the wheel when I cleared the cache.
http://jsfiddle.net/leydar/a7tkA/5
wheel.clearCache().offset({
x: 0,
y: 0
});
I hope this is of benefit to someone else. It's still not perfectly responsive but it's at least going in the right direction.
Stephen
Related
I'm trying to reproduce something like this: http://carbure.co/.
After inspection the website uses matter.js, a physics engine. Below is a (failed) code attempt, and I'm having trouble getting it to work given the terrible docs.
Does anyone have any idea how else I can achieve this?
Many thanks
$(window).load(function() {
var w = $(window).innerWidth();
var h = $(window).innerHeight();
// Matter.js module aliases
var Engine = Matter.Engine;
var World = Matter.World;
var Bodies = Matter.Bodies;
var Body = Matter.Body;
var Constraint = Matter.Constraint;
var Composite = Matter.Composite;
var Composites = Matter.Composites;
var MouseConstraint = Matter.MouseConstraint;
// create a Matter.js engine
var engine = Engine.create({
render: {
element: document.body,
options: {
width: w,
height: h,
wireframes: false,
background: '#fff'
}
}
});
// add a mouse controlled constraint
var mouseConstraint = MouseConstraint.create(engine);
World.add(engine.world, mouseConstraint);
var addToWorld = [];
// create random poly's and a ground
var ranPolygons = Math.random() * 10 + 5 >> 0;
var prevPoly;
for (var i = 0; i < ranPolygons; i++) {
var polyRadius = Math.random() * 40 + 40 >> 0;
var polySides = 1;
var x = Math.random() * (w - polyRadius * 2) + polyRadius >> 0;
var y = Math.random() * (h / 2 - polyRadius * 2) + polyRadius >> 0;
var isStatic = Math.random() * 1 < 0.2;
var poly = Bodies.polygon(x, y, polySides, polyRadius, {
render: {
fillStyle: isStatic ? '#0134CB' : makePattern(),
strokeStyle: isStatic ? 'transparent' : '#0134CB',
lineWidth: Math.random() * 5 + 2 >> 0
},
density: Math.random() * 0.1,
isStatic: isStatic,
restitution: Math.random() * 1
});
addToWorld.push(poly);
// add borders
var border = 5;
var halfBorder = border / 2;
var borders = [
Bodies.rectangle(w / 2, halfBorder, w + border, border, {
isStatic: true,
render: {
fillStyle: 'transparent',
strokeStyle: 'transparent'
}
}),
Bodies.rectangle(w / 2, h - halfBorder, w + border, border, {
isStatic: true,
render: {
fillStyle: 'transparent',
strokeStyle: 'transparent'
}
}),
Bodies.rectangle(halfBorder, h / 2, border, h + border, {
isStatic: true,
render: {
fillStyle: 'transparent',
strokeStyle: 'transparent'
}
}),
Bodies.rectangle(w - halfBorder, h / 2, border, h + border, {
isStatic: true,
render: {
fillStyle: 'transparent',
strokeStyle: 'transparent'
}
}),
];
addToWorld = addToWorld.concat(borders);
// add all of the bodies to the world
World.add(engine.world, addToWorld);
// run the engine
runner = Engine.run(engine)
// setTimeout(ranGrav, 2000);
engine.world.gravity.y = 0;
engine.world.gravity.x = 0;
$(engine.render.canvas).css({
width: '100%',
height: '100vh'
})
});
I got your code running. It had a number of issues. First and foremost, the missing bracket belonged to the loop:
for (var i = 0; i < ranPolygons; i++) {
Besides that I also had to run the renderer:
Render.run(render);
And I got rid of this bit, because it was unnecessary and was throwing a warning:
$(engine.render.canvas).css({
width: '100%',
height: '100vh'
});
https://jsfiddle.net/jx3vn7da/
I am attempting to implement this mousefollow into my website:
http://codepen.io/hakimel/pen/KanIi
But I would like my own custom colors instead of what is default displayed. I changed the fillcolor value and was able to change to one specific color but I would like 4 different colors. So I have tried adding specific colors to this function next to fillColor: but no such luck. I also created a fillcolor2: property like:
for (var i = 0; i < QUANTITY; i++) {
var particle = {
size: 1,
position: { x: mouseX, y: mouseY },
offset: { x: 0, y: 0 },
shift: { x: mouseX, y: mouseY },
speed: 0.01+Math.random()*0.04,
targetSize: 1,
fillColor: '#bf3e27',
fillColor2: '#1c305c',
orbit: RADIUS*.1 + (RADIUS * .5 * Math.random())
};
and added:
context.fillStyle = particle.fillColor2;
context.strokeStyle = particle.fillColor2;
But that did not work either. I have also tried to copy and paste the same js code just to see if it would work, and just changed the fillcolor, but it would only display the last one pasted.
Can anyone show me how to get 4 separate colors the easiest way, I feel like I am vastly over-complicating this but obviously a beginner and getting rather frustrated with this?
Lastly, I would like the 4 different colors to span different radii and I messed around with the different RADIUS variables but it is pretty much impossible to figure out how to accomplish what I would like while only having one color. So there will be 4 of each color, I changed the QUANTITY to:
var QUANTITY = 16;
I need the first 4 colors radius of 10 so for the first one I set:
var RADIUS = 10;
Ideally I need the first 4 to be color (#AAAAAA) radius of 10 like it is, but need the second 4 to be color (#BBBBBBB) between radius 10 and 30, the third color (#CCCCCC) to be between radius of 30-50, and the last fourth color (#DDDDDD) to be between 50 and 70.
Any suggestions?
You could replace the definition of QUANTITY, COLOR and RADIUS with an array of these, and at the same time define ranges for RADIUS:
var GROUPS = [
{
QUANTITY: 4,
RADIUS: [ 5, 10],
COLOR: 0x888888
},
{
QUANTITY: 4,
RADIUS: [10, 30],
COLOR: 0xAA80AA
},
{
QUANTITY: 4,
RADIUS: [30, 50],
COLOR: 0xA0A0CC
},
{
QUANTITY: 4,
RADIUS: [50, 70],
COLOR: 0xFFE0E0
}
];
Then inside the createParticles function you would iterate over those GROUPS:
for (var g = 0; g < GROUPS.length; g++) {
var attribs = GROUPS[g];
for (var i = 0; i < attribs.QUANTITY; i++) {
var particle = {
size: 1,
position: { x: mouseX, y: mouseY },
offset: { x: 0, y: 0 },
shift: { x: mouseX, y: mouseY },
speed: 0.01+Math.random()*0.04,
targetSize: 1,
fillColor: '#' + attribs.COLOR.toString(16),
orbit: attribs.RADIUS[0] +
(attribs.RADIUS[1]-attribs.RADIUS[0]) * Math.random()
};
particles.push( particle );
}
}
Here is a snippet:
// One of my first <canvas> experiments, woop! :D
var SCREEN_WIDTH = window.innerWidth;
var SCREEN_HEIGHT = window.innerHeight;
var GROUPS = [
{
QUANTITY: 4,
RADIUS: [ 5, 10],
COLOR: 0x888888
},
{
QUANTITY: 4,
RADIUS: [10, 30],
COLOR: 0xAA80AA
},
{
QUANTITY: 4,
RADIUS: [30, 50],
COLOR: 0xA0A0CC
},
{
QUANTITY: 4,
RADIUS: [50, 70],
COLOR: 0xFFE0E0
}
];
var RADIUS_SCALE = 1;
var RADIUS_SCALE_MIN = 1;
var RADIUS_SCALE_MAX = 1.5;
var canvas;
var context;
var particles;
var mouseX = SCREEN_WIDTH * 0.5;
var mouseY = SCREEN_HEIGHT * 0.5;
var mouseIsDown = false;
function init() {
canvas = document.getElementById( 'world' );
if (canvas && canvas.getContext) {
context = canvas.getContext('2d');
// Register event listeners
window.addEventListener('mousemove', documentMouseMoveHandler, false);
window.addEventListener('mousedown', documentMouseDownHandler, false);
window.addEventListener('mouseup', documentMouseUpHandler, false);
document.addEventListener('touchstart', documentTouchStartHandler, false);
document.addEventListener('touchmove', documentTouchMoveHandler, false);
window.addEventListener('resize', windowResizeHandler, false);
createParticles();
windowResizeHandler();
setInterval( loop, 1000 / 60 );
}
}
function createParticles() {
particles = [];
for (var g = 0; g < GROUPS.length; g++) {
var attribs = GROUPS[g];
for (var i = 0; i < attribs.QUANTITY; i++) {
var particle = {
size: 1,
position: { x: mouseX, y: mouseY },
offset: { x: 0, y: 0 },
shift: { x: mouseX, y: mouseY },
speed: 0.01+Math.random()*0.04,
targetSize: 1,
fillColor: '#' + attribs.COLOR.toString(16),
orbit: attribs.RADIUS[0] +
(attribs.RADIUS[1]-attribs.RADIUS[0]) * Math.random()
};
particles.push( particle );
}
}
}
function documentMouseMoveHandler(event) {
mouseX = event.clientX - (window.innerWidth - SCREEN_WIDTH) * .5;
mouseY = event.clientY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}
function documentMouseDownHandler(event) {
mouseIsDown = true;
}
function documentMouseUpHandler(event) {
mouseIsDown = false;
}
function documentTouchStartHandler(event) {
if(event.touches.length == 1) {
event.preventDefault();
mouseX = event.touches[0].pageX - (window.innerWidth - SCREEN_WIDTH) * .5;;
mouseY = event.touches[0].pageY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}
}
function documentTouchMoveHandler(event) {
if(event.touches.length == 1) {
event.preventDefault();
mouseX = event.touches[0].pageX - (window.innerWidth - SCREEN_WIDTH) * .5;;
mouseY = event.touches[0].pageY - (window.innerHeight - SCREEN_HEIGHT) * .5;
}
}
function windowResizeHandler() {
SCREEN_WIDTH = window.innerWidth;
SCREEN_HEIGHT = window.innerHeight;
canvas.width = SCREEN_WIDTH;
canvas.height = SCREEN_HEIGHT;
}
function loop() {
if( mouseIsDown ) {
RADIUS_SCALE += ( RADIUS_SCALE_MAX - RADIUS_SCALE ) * (0.02);
}
else {
RADIUS_SCALE -= ( RADIUS_SCALE - RADIUS_SCALE_MIN ) * (0.02);
}
RADIUS_SCALE = Math.min( RADIUS_SCALE, RADIUS_SCALE_MAX );
context.fillStyle = 'rgba(0,0,0,0.05)';
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
for (i = 0, len = particles.length; i < len; i++) {
var particle = particles[i];
var lp = { x: particle.position.x, y: particle.position.y };
// Rotation
particle.offset.x += particle.speed;
particle.offset.y += particle.speed;
// Follow mouse with some lag
particle.shift.x += ( mouseX - particle.shift.x) * (particle.speed);
particle.shift.y += ( mouseY - particle.shift.y) * (particle.speed);
// Apply position
particle.position.x = particle.shift.x + Math.cos(i + particle.offset.x) * (particle.orbit*RADIUS_SCALE);
particle.position.y = particle.shift.y + Math.sin(i + particle.offset.y) * (particle.orbit*RADIUS_SCALE);
// Limit to screen bounds
particle.position.x = Math.max( Math.min( particle.position.x, SCREEN_WIDTH ), 0 );
particle.position.y = Math.max( Math.min( particle.position.y, SCREEN_HEIGHT ), 0 );
particle.size += ( particle.targetSize - particle.size ) * 0.05;
if( Math.round( particle.size ) == Math.round( particle.targetSize ) ) {
particle.targetSize = 1 + Math.random() * 7;
}
context.beginPath();
context.fillStyle = particle.fillColor;
context.strokeStyle = particle.fillColor;
context.lineWidth = particle.size;
context.moveTo(lp.x, lp.y);
context.lineTo(particle.position.x, particle.position.y);
context.stroke();
context.arc(particle.position.x, particle.position.y, particle.size/2, 0, Math.PI*2, true);
context.fill();
}
}
window.onload = init;
body {
background-color: #000000;
padding: 0;
margin: 0;
overflow: hidden;
}
<canvas id='world'></canvas>
Define the settings for the particles in an array
// I've changed the color for better visibility
var ParticleSettings = [
{color: "#f00", radiusMin: 10, radiusMax: 10},
{color: "#0f0", radiusMin: 10, radiusMax: 30},
{color: "#00f", radiusMin: 30, radiusMax: 50}
];
To get the correct settings for a particle (in this case its index) use this function
function getParticleSettings(particleIndex) {
var settingsIndex = Math.floor(particleIndex / 4) % ParticleSettings.length,
settings = ParticleSettings[settingsIndex];
return {
color: settings.color,
radius: getRandom(settings.radiusMin, settings.radiusMax)
};
}
getRandom is just a small helper function to get a random number between two boundaries
function getRandom(min, max) {
return Math.floor((Math.random() * (max - min)) + min)
}
In createParticle we then have to change the for loop to get the settings for the current particle
for (var i = 0; i < QUANTITY; i++) {
// get the settings for the current particle
var particleSettings = getParticleSettings(i);
var particle = {
size: 1,
position: { x: mouseX, y: mouseY },
offset: { x: 0, y: 0 },
shift: { x: mouseX, y: mouseY },
speed: 0.01+Math.random()*0.04,
targetSize: 1,
fillColor: particleSettings.color, // <--
orbit: particleSettings.radius // <--
};
particles.push( particle );
}
This would be the result of the changes above.
You could define the colors in an array since you are using a for loop you can index them like this:
var colors = ['#AAAAAA', '#BBBBBB', '#CCCCCC', '#DDDDDD'];
var particle = {
...
fillColor: colors[i],
...
}
This will now only work for the first four colors, but since you stated you have a quantity of 16, you could use 2 for loops to achieve this. Something like this:
//will run 16 times
for(var i = 0; i < QUANTITY; i++) {
for(var x = 0; x < 4; x++) {
var particle = {
//note that i'm using x here since the array has only 4 keys.
fillColor: colors[x];
}
}
}
I'm trying to create an arrow shape using fabricjs. Thus far my best approach has been to add a line and a triangle and combine them into a composite group. The problem however is, when I resize the arrow, the arrow head gets stretched and its not a nice effect.
What I'm asking is, how would you go about creating an arrow object on fabricjs that can be resized lengthwise only without stretching the arrow head.
http://jsfiddle.net/skela/j45czqge/
<html>
<head>
<script src='http://fabricjs.com/build/files/text,gestures,easing,parser,freedrawing,interaction,serialization,image_filters,gradient,pattern,shadow,node.js'></script> <meta charset="utf-8">
<style>
html,body
{
height: 100%; min-height:100%;
width: 100%; min-width:100%;
background-color:transparent;
margin:0;
}
button
{
height:44px;
margin:0;
}
</style>
</head>
<body>
<span id="dev">
<button id="draw_mode" onclick="toggleDraw()">Draw</button>
<button onclick="addRect()">Add Rect</button>
<button onclick="addCircle()">Add Circle</button>
<button onclick="addTriangle()">Add Triangle</button>
<button onclick="addLine()">Add Line</button>
<button onclick="addArrow()">Add Arrow</button>
<button onclick="clearCanvas()">Clear</button>
<button onclick="saveCanvas()">Save</button>
<button onclick="loadCanvas()">Load</button>
</span>
<span id="selected" style="visibility:hidden;">
<button onclick="removeSelected()">Remove</button>
</span>
<canvas id="c" style="border:1px solid #aaa;"></canvas>
<script>
fabric.Object.prototype.toObject = (function (toObject)
{
return function ()
{
return fabric.util.object.extend(toObject.call(this),
{
id:this.id,
});
};
})(fabric.Object.prototype.toObject);
fabric.LineArrow = fabric.util.createClass(fabric.Line, {
type: 'lineArrow',
initialize: function(element, options) {
options || (options = {});
this.callSuper('initialize', element, options);
},
toObject: function() {
return fabric.util.object.extend(this.callSuper('toObject'));
},
_render: function(ctx){
this.callSuper('_render', ctx);
// do not render if width/height are zeros or object is not visible
if (this.width === 0 || this.height === 0 || !this.visible) return;
ctx.save();
var xDiff = this.x2 - this.x1;
var yDiff = this.y2 - this.y1;
var angle = Math.atan2(yDiff, xDiff);
ctx.translate((this.x2 - this.x1) / 2, (this.y2 - this.y1) / 2);
ctx.rotate(angle);
ctx.beginPath();
//move 10px in front of line to start the arrow so it does not have the square line end showing in front (0,0)
ctx.moveTo(10,0);
ctx.lineTo(-20, 15);
ctx.lineTo(-20, -15);
ctx.closePath();
ctx.fillStyle = this.stroke;
ctx.fill();
ctx.restore();
}
});
fabric.LineArrow.fromObject = function (object, callback) {
callback && callback(new fabric.LineArrow([object.x1, object.y1, object.x2, object.y2],object));
};
fabric.LineArrow.async = true;
var canvas = new fabric.Canvas('c');
canvas.isDrawingMode = false;
canvas.freeDrawingBrush.width = 5;
setColor('red');
var sendToApp = function(_key, _val)
{
var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", _key + ":##drawings##" + _val);
document.documentElement.appendChild(iframe);
iframe.parentNode.removeChild(iframe);
iframe = null;
};
canvas.on('object:selected',function(options)
{
if (options.target)
{
//console.log('an object was selected! ', options.target.type);
var sel = document.getElementById("selected");
sel.style.visibility = "visible";
sendToApp("object:selected","");
}
});
canvas.on('selection:cleared',function(options)
{
//console.log('selection cleared');
var sel = document.getElementById("selected");
sel.style.visibility = "hidden";
sendToApp("selection:cleared","");
});
canvas.on('object:modified',function(options)
{
if (options.target)
{
//console.log('an object was modified! ', options.target.type);
sendToApp("object:modified","");
}
});
canvas.on('object:added',function(options)
{
if (options.target)
{
if (typeof options.target.id == 'undefined')
{
options.target.id = 1337;
}
//console.log('an object was added! ', options.target.type);
sendToApp("object:added","");
}
});
canvas.on('object:removed',function(options)
{
if (options.target)
{
//console.log('an object was removed! ', options.target.type);
sendToApp("object:removed","");
}
});
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas()
{
canvas.setHeight(window.innerHeight);
canvas.setWidth(window.innerWidth);
canvas.renderAll();
}
function color()
{
return canvas.freeDrawingBrush.color;
}
function setColor(color)
{
canvas.freeDrawingBrush.color = color;
}
function toggleDraw()
{
setDrawingMode(!canvas.isDrawingMode);
}
function setDrawingMode(isDrawingMode)
{
canvas.isDrawingMode = isDrawingMode;
var btn = document.getElementById("draw_mode");
btn.innerHTML = canvas.isDrawingMode ? "Drawing" : "Draw";
sendToApp("mode",canvas.isDrawingMode ? "drawing" : "draw");
}
function setLineControls(line)
{
line.setControlVisible("tr",false);
line.setControlVisible("tl",false);
line.setControlVisible("br",false);
line.setControlVisible("bl",false);
line.setControlVisible("ml",false);
line.setControlVisible("mr",false);
}
function createLine(points)
{
var line = new fabric.Line(points,
{
strokeWidth: 5,
stroke: color(),
originX: 'center',
originY: 'center',
lockScalingX:true,
//lockScalingY:false,
});
setLineControls(line);
return line;
}
function createArrowHead(points)
{
var headLength = 15,
x1 = points[0],
y1 = points[1],
x2 = points[2],
y2 = points[3],
dx = x2 - x1,
dy = y2 - y1,
angle = Math.atan2(dy, dx);
angle *= 180 / Math.PI;
angle += 90;
var triangle = new fabric.Triangle({
angle: angle,
fill: color(),
top: y2,
left: x2,
height: headLength,
width: headLength,
originX: 'center',
originY: 'center',
// lockScalingX:false,
// lockScalingY:true,
});
return triangle;
}
function addRect()
{
canvas.add(new fabric.Rect({left:100,top:100,fill:color(),width:50,height:50}));
}
function addCircle()
{
canvas.add(new fabric.Circle({left:150,top:150,fill:color(),radius:50/2}));
}
function addTriangle()
{
canvas.add(new fabric.Triangle({left:200,top:200,fill:color(),height:50,width:46}));
}
function addLine()
{
var line = createLine([100,100,100,200]);
canvas.add(line);
}
function addArrow()
{
var pts = [100,100,100,200];
var triangle = createArrowHead(pts);
var line = createLine(pts);
var grp = new fabric.Group([triangle,line]);
setLineControls(grp);
canvas.add(grp);
// var arrow = new fabric.LineArrow(pts,{left:100,top:100,fill:color()});
// setLineControls(arrow);
// canvas.add(arrow);
}
function removeSelected()
{
var grp = canvas.getActiveGroup();
var obj = canvas.getActiveObject();
if (obj!=null)
{
canvas.remove(obj);
}
if (grp!=null)
{
grp.forEachObject(function(o){ canvas.remove(o) });
canvas.discardActiveGroup().renderAll();
}
}
function clearCanvas()
{
canvas.clear();
}
function saveCanvas()
{
var js = JSON.stringify(canvas);
return js;
}
function loadCanvas()
{
var js = '{"objects":[{"type":"circle","originX":"left","originY":"top","left":150,"top":150,"width":50,"height":50,"fill":"red","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","id":1234,"radius":25,"startAngle":0,"endAngle":6.283185307179586}],"background":""}';
canvas.loadFromJSON(js);
}
resizeCanvas();
</script>
</body>
</html>
I had the same problem and ended up doing math to calculate the points that would make up an arrow shape around a line and using a polygon object instead.
The core of it looks like:
var angle = Math.atan2(toy - fromy, tox - fromx);
var headlen = 15; // arrow head size
// bring the line end back some to account for arrow head.
tox = tox - (headlen) * Math.cos(angle);
toy = toy - (headlen) * Math.sin(angle);
// calculate the points.
var points = [
{
x: fromx, // start point
y: fromy
}, {
x: fromx - (headlen / 4) * Math.cos(angle - Math.PI / 2),
y: fromy - (headlen / 4) * Math.sin(angle - Math.PI / 2)
},{
x: tox - (headlen / 4) * Math.cos(angle - Math.PI / 2),
y: toy - (headlen / 4) * Math.sin(angle - Math.PI / 2)
}, {
x: tox - (headlen) * Math.cos(angle - Math.PI / 2),
y: toy - (headlen) * Math.sin(angle - Math.PI / 2)
},{
x: tox + (headlen) * Math.cos(angle), // tip
y: toy + (headlen) * Math.sin(angle)
}, {
x: tox - (headlen) * Math.cos(angle + Math.PI / 2),
y: toy - (headlen) * Math.sin(angle + Math.PI / 2)
}, {
x: tox - (headlen / 4) * Math.cos(angle + Math.PI / 2),
y: toy - (headlen / 4) * Math.sin(angle + Math.PI / 2)
}, {
x: fromx - (headlen / 4) * Math.cos(angle + Math.PI / 2),
y: fromy - (headlen / 4) * Math.sin(angle + Math.PI / 2)
},{
x: fromx,
y: fromy
}
];
Then create a polygon from the points.
https://jsfiddle.net/6e17oxc3/
What you can do is calculate the new size after the object is stretched and draw another object on the same exact area and removing the previous one.
var obj = canvas.getActiveObject();
var width = obj.getWidth();
var height = obj.getHeight;
var top = obj.getTop();
Now if you have only one object that is stretched, you can simply use the data above to draw another nicely looking object on the canvas.
If you have multiples then you need to get the data for all of them and draw them one by one.
I have a sprite animation where I have set a stopping distance to it and want to calculate how much i have to slow the object down in that stopping distance to reach its new target speed. But at the moment I am not getting the correct result.
My code looks like this:
function updatePosition(obj,brake){
var delta = new Date().getTime() - obj.timer; //time since last frame
if(brake){
obj.velocity -= (Math.pow(obj.velocity,2) - Math.pow(obj.targetSpeed,2)) / (2 * obj.stopDist);
if(obj.velocity < obj.targetSpeed){
obj.velocity = obj.targetSpeed;
}
}
}
My problem is the sprite goes far past the stopping distance with a velocity well above the target speed.
I created a fiddle with a red dot travelling to a destination here: http://jsfiddle.net/4tLmz3ch/1/
When it travels the distance set by obj.stopDist it should be going the target speed which should be well before it reaches its destination. But i am obviously getting something incorrect with the math here.
Hope you can help explain my misunderstanding.
This problem is a lot simpler if you determine the desired acceleration ahead of time, and use that during each refresh. Then the entire code for each frame (excluding the drawing logic and assuming one dimension) just becomes:
function frame() {
var t = new Date().getTime();
var tDelta = t - obj.lastTime;
obj.lastTime = t;
obj.pos += obj.velocity * tDelta;
if (obj.velocity > obj.destVelocity) {
obj.velocity += obj.acceleration * tDelta;
}
draw();
setTimeout(frame, 1);
}
Given a starting and ending position and velocity, the formula for the acceleration required (assuming constant acceleration) is:
So initializing the object like this:
var obj = {
start: 10,
height: 200,
stopDist: 300,
dest: 500,
lastTime: new Date().getTime(),
velocity: 0.05,
destVelocity: 0.01,
pos: undefined,
acceleration: undefined
};
here is how we can kick this all off:
function start(){
var v0 = obj.velocity,
vf = obj.destVelocity,
x0 = obj.start,
xf = x0 + x.stopDist,
vDelta = vf - v0;
obj.pos = x0;
obj.acceleration = (2 * v0 * vDelta + vDelta * vDelta) / (2 * (xf - x0));
frame();
}
As I've done above, it's helpful to solve the 1d case first. Here is that, all put together.
var canvas = document.getElementById('canvas');
var test = document.getElementById('test');
var ctx = canvas.getContext('2d');
function drawDot(color, x, y) {
ctx.fillStyle = color;
ctx.fillRect(x - 2, y - 2, 4, 4);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawDot("red", obj.pos, obj.height);
drawDot("white", obj.start, obj.height);
drawDot("green", obj.dest, obj.height);
drawDot("yellow", obj.start + obj.stopDist, obj.height);
ctx.fillText("x = " + obj.pos.toFixed(5), 20, 400);
ctx.fillText("v = " + obj.velocity.toFixed(5), 20, 420);
ctx.fillText("distance traveled: " + (obj.pos - obj.start).toFixed(2), 20, 440);
}
var obj = {
start: 10,
height: 200,
stopDist: 300,
dest: 500,
lastTime: new Date().getTime(),
velocity: 0.05,
destVelocity: 0.01,
pos: undefined,
acceleration: undefined
};
function frame() {
var t = new Date().getTime(),
tDelta = t - obj.lastTime;
obj.lastTime = t;
obj.pos += obj.velocity * tDelta;
if (obj.velocity > obj.destVelocity) {
obj.velocity += obj.acceleration * tDelta;
}
draw();
setTimeout(frame, 1);
}
function start() {
var v0 = obj.velocity,
vf = obj.destVelocity,
x0 = obj.start,
xf = x0 + obj.stopDist,
vDelta = vf - v0;
obj.pos = x0;
obj.acceleration = (2 * v0 * vDelta + vDelta * vDelta) / (2 * (xf - x0));
frame();
}
start();
#canvas{
background-color:black;
}
<canvas id="canvas" width="700" height="700"></canvas>
http://jsfiddle.net/x7842xcb/3/
And here is the 2d version (brace yourself):
var canvas = document.getElementById('canvas');
var test = document.getElementById('test');
var ctx = canvas.getContext('2d');
function drawDot(color, x, y) {
ctx.fillStyle = color;
ctx.fillRect(x - 2, y - 2, 4, 4);
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawDot("red", obj.pos.x, obj.pos.y);
drawDot("white", obj.start.x, obj.start.y);
drawDot("green", obj.dest.x, obj.dest.y);
drawDot("yellow", obj.stopLocation.x, obj.stopLocation.y);
var dx = obj.pos.x - obj.start.x,
dy = obj.pos.y - obj.start.y,
dist = Math.sqrt(dx * dx + dy *dy),
v = obj.velocity,
speed = Math.sqrt(v.x * v.x + v.y * v.y);
ctx.fillText("distance traveled: " + dist.toFixed(5), 20, 400);
ctx.fillText("speed: " + speed.toFixed(5), 20, 420);
}
var obj = {
start: { x: 400, y: 230 },
stopDist: 350,
dest: { x: 50, y: 330 },
lastTime: new Date().getTime(),
startSpeed: 0.05,
destSpeed: 0.1,
pos: null,
velocity: null,
destVelocity: null,
acceleration: null
};
function sign(value) {
return value > 0 ? 1 : (value < 0 ? -1 : 0);
}
function reached(start, current, dest) {
return current === dest ||
sign(current - dest) === sign(dest - start);
}
function frame() {
var t = new Date().getTime(),
tDelta = t - obj.lastTime,
v = obj.velocity,
destv = obj.destVelocity,
startv = obj.startVelocity;
obj.lastTime = t;
obj.pos.x += v.x * tDelta;
obj.pos.y += v.y * tDelta;
if (!reached(startv.x, v.x, destv.x) ||
!reached(startv.y, v.y, destv.y)) {
v.x += obj.acceleration.x * tDelta;
v.y += obj.acceleration.y * tDelta;
}
draw();
setTimeout(frame, 1);
}
function calcAcceleration(p0, pf, v0, vf) {
var vDelta = vf - v0;
return pf === p0
? 0
: (2 * v0 * vDelta + vDelta * vDelta) / (2 * (pf - p0));
}
function start() {
// positions and deltas
var start = obj.start,
dest = obj.dest,
dx = dest.x - start.x,
dy = dest.y - start.y,
totalDistance = Math.sqrt(dx * dx + dy * dy);
// x and y component ratio
var cx = dx / totalDistance,
cy = dy / totalDistance;
var stopLocation = { x: cx * obj.stopDist + start.x,
y: cy * obj.stopDist + start.y };
// velocities
var startSpeed = obj.startSpeed,
destSpeed = obj.destSpeed,
startVelocity = { x: cx * startSpeed, y: cy * startSpeed },
endVelocity = { x: cx * destSpeed, y: cy * destSpeed };
console.log(startVelocity);
console.log(endVelocity);
// acceleration
var acceleration = {
x: calcAcceleration(start.x, stopLocation.x, startVelocity.x, endVelocity.x),
y: calcAcceleration(start.y, stopLocation.y, startVelocity.y, endVelocity.y)
};
obj.pos = Object.create(start);
obj.startVelocity = startVelocity;
obj.velocity = Object.create(startVelocity);
obj.stopLocation = stopLocation;
obj.destVelocity = endVelocity;
obj.acceleration = acceleration;
frame();
}
start();
#canvas{
background-color:black;
}
<canvas id="canvas" width="700" height="700"></canvas>
http://jsfiddle.net/1r3q4oob/3/
Edit Regarding the fix I made after the fact:
The problem with my original implementation was that it would only update the velocity if both the X and Y components of the current velocity were greater than the target velocity. This would prevent the correct behavior if:
The X or Y component of both the start and end velocity were 0 (i.e. if it were travelling perfectly horizontally or vertically)
The X or Y component of the start and end velocity were negative (i.e. if it were travelling up and to the left)
The velocity needed to increase rather than decrease (i.e. the dot were speeding up to a target velocity)
I resolved this with the addition of the reached() function, which basically returns true if (a) the destination velocity is between the current velocity and the start velocity (i.e. the current velocity has gone past the destination velocity), or (b) the current velocity is equal to the destination velocity.
EDIT:
For anybody who is curious, here is the finished result.
http://jsfiddle.net/Javalsu/vxP5q/743/embedded/result/
I'm building off of the code I found in this link
http://thecodeplayer.com/walkthrough/html5-canvas-snow-effect
I want to make this more of a confetti falling effect than a snow effect, and I would need to make each element a different color. But it seems that the fill color is set for entire canvas at once.
Is there a way to specify a different fill color for each element or am I going about this the entirely wrong way?
Thanks
Update: Here is the finished product if anybody has a need for confetti
http://jsfiddle.net/mj3SM/6/
window.onload = function () {
//canvas init
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//canvas dimensions
var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
//snowflake particles
var mp = 200; //max particles
var particles = [];
for (var i = 0; i < mp; i++) {
particles.push({
x: Math.random() * W, //x-coordinate
y: Math.random() * H, //y-coordinate
r: Math.random() * 15 + 1, //radius
d: Math.random() * mp, //density
color: "rgba(" + Math.floor((Math.random() * 255)) + ", " + Math.floor((Math.random() * 255)) + ", " + Math.floor((Math.random() * 255)) + ", 0.8)",
tilt: Math.floor(Math.random() * 5) - 5
});
}
//Lets draw the flakes
function draw() {
ctx.clearRect(0, 0, W, H);
for (var i = 0; i < mp; i++) {
var p = particles[i];
ctx.beginPath();
ctx.lineWidth = p.r;
ctx.strokeStyle = p.color; // Green path
ctx.moveTo(p.x, p.y);
ctx.lineTo(p.x + p.tilt + p.r / 2, p.y + p.tilt);
ctx.stroke(); // Draw it
}
update();
}
//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update() {
angle += 0.01;
for (var i = 0; i < mp; i++) {
var p = particles[i];
//Updating X and Y coordinates
//We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
//Every particle has its own density which can be used to make the downward movement different for each flake
//Lets make it more random by adding in the radius
p.y += Math.cos(angle + p.d) + 1 + p.r / 2;
p.x += Math.sin(angle) * 2;
//Sending flakes back from the top when it exits
//Lets make it a bit more organic and let flakes enter from the left and right also.
if (p.x > W + 5 || p.x < -5 || p.y > H) {
if (i % 3 > 0) //66.67% of the flakes
{
particles[i] = {
x: Math.random() * W,
y: -10,
r: p.r,
d: p.d,
color: p.color,
tilt: p.tilt
};
} else {
//If the flake is exitting from the right
if (Math.sin(angle) > 0) {
//Enter from the left
particles[i] = {
x: -5,
y: Math.random() * H,
r: p.r,
d: p.d,
color: p.color,
tilt: p.tilt
};
} else {
//Enter from the right
particles[i] = {
x: W + 5,
y: Math.random() * H,
r: p.r,
d: p.d,
color: p.color,
tilt: p.tilt
};
}
}
}
}
}
//animation loop
setInterval(draw, 20);
}
Try it like this: http://jsfiddle.net/vxP5q/
The JS:
window.onload = function(){
//canvas init
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
//canvas dimensions
var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
//snowflake particles
var mp = 25; //max particles
var particles = [];
for(var i = 0; i < mp; i++)
{
particles.push({
x: Math.random()*W, //x-coordinate
y: Math.random()*H, //y-coordinate
r: Math.random()*4+1, //radius
d: Math.random()*mp, //density
color: "rgba(" + Math.floor((Math.random() * 255)) +", " + Math.floor((Math.random() * 255)) +", " + Math.floor((Math.random() * 255)) + ", 0.8)"
})
}
//Lets draw the flakes
function draw()
{
ctx.clearRect(0, 0, W, H);
for(var i = 0; i < mp; i++)
{
var p = particles[i];
ctx.beginPath();
ctx.fillStyle = p.color;
ctx.moveTo(p.x, p.y);
ctx.arc(p.x, p.y, p.r, 0, Math.PI*2, true);
ctx.fill();
}
update();
}
//Function to move the snowflakes
//angle will be an ongoing incremental flag. Sin and Cos functions will be applied to it to create vertical and horizontal movements of the flakes
var angle = 0;
function update()
{
angle += 0.01;
for(var i = 0; i < mp; i++)
{
var p = particles[i];
//Updating X and Y coordinates
//We will add 1 to the cos function to prevent negative values which will lead flakes to move upwards
//Every particle has its own density which can be used to make the downward movement different for each flake
//Lets make it more random by adding in the radius
p.y += Math.cos(angle+p.d) + 1 + p.r/2;
p.x += Math.sin(angle) * 2;
//Sending flakes back from the top when it exits
//Lets make it a bit more organic and let flakes enter from the left and right also.
if(p.x > W+5 || p.x < -5 || p.y > H)
{
if(i%3 > 0) //66.67% of the flakes
{
particles[i] = {x: Math.random()*W, y: -10, r: p.r, d: p.d, color : p.color};
}
else
{
//If the flake is exitting from the right
if(Math.sin(angle) > 0)
{
//Enter from the left
particles[i] = {x: -5, y: Math.random()*H, r: p.r, d: p.d, color: p.color};
}
else
{
//Enter from the right
particles[i] = {x: W+5, y: Math.random()*H, r: p.r, d: p.d, color : p.color};
}
}
}
}
}
//animation loop
setInterval(draw, 33);
}
What I've done. Where the pixels are generated I've added an unique (random) color. Where the update is, I'm making sure the colors are changed and where its drawn I've changed it so that it will create an inuque path for each confetti item.
Great question. Consider the drawing loop for the sample:
ctx.fillStyle = "rgba(255, 255, 255, 0.8)";
ctx.beginPath();
for(var i = 0; i < mp; i++)
{
var p = particles[i];
ctx.moveTo(p.x, p.y);
ctx.arc(p.x, p.y, p.r, 0, Math.PI*2, true);
}
ctx.fill();
It is making one path, adding many arcs, and then filling it one time.
To change it you will need to fill it once per particle instead. You'll also want to give each particle a unique color:
for (var i = 0; i < mp; i++) {
var p = particles[i];
ctx.fillStyle = p.color;
ctx.beginPath();
ctx.moveTo(p.x, p.y);
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true);
ctx.fill();
}
Note how beginPath() and fill() are now inside the loop. This is important, because each arc needs its own path and fill. This is much slower than making them all with one path, but is necessary if you want different colored particles.
That p.color:
particles.push({
x: Math.random() * W, //x-coordinate
y: Math.random() * H, //y-coordinate
r: Math.random() * 4 + 1, //radius
d: Math.random() * mp, //density
// I'm new!
color: "rgba(" + Math.floor(Math.random()*255) +
", " + Math.floor(Math.random()*255) + ", 255, 0.8)"
})
Here's a working example:
http://jsfiddle.net/j4NZK/1/
Here is a version based on the post by Niels, I wanted a reusable object that I can call and add to any page.
Usage:
confetti.Init(#IdofContainer(div)#, 50,25,100)
Code:
var confetti = {
angle: 0,
ctx: 0,
H: 0,
W: 0,
mp: 0,
particles: [],
endFunction: '',
Init: function (parent, maxParticles, iCount, speed, endFunct) {
confetti.stopped = false;
confetti.runner = null;
confetti.endFunction = endFunct;
var canvas = document.getElementById("confettiCanvasId");
if (canvas) {
canvas.parentNode.removeChild(canvas);
}
canvas = document.createElement('canvas');
canvas.className = 'confettiCanvas';
canvas.id = 'confettiCanvasId'
$id(parent).appendChild(canvas);
var ctx = canvas.getContext("2d");
var W = $id(parent).clientHeight;
var H = $id(parent).clientWidth;
canvas.width = W;
canvas.height = H;
confetti.particles = [];
for (var i = 0; i < maxParticles; i++) {
confetti.particles.push({
x: Math.random() * W,
y: Math.random() * H,
r: Math.random() * 4 + 1, //radius
d: Math.random() * maxParticles, //density
color: "rgba(" + Math.floor((Math.random() * 255)) + ", " + Math.floor((Math.random() * 255)) + ", " + Math.floor((Math.random() * 255)) + ", 0.8)"
});
}
myCounter = new confetti.Counter({
seconds: iCount,
speed: speed,
onUpdateStatus: function (sec) {
$l(Math.random() * 255)
ctx.clearRect(0, 0, W, H);
for (var i = 0; i < maxParticles; i++) {
var p = confetti.particles[i];
ctx.beginPath();
ctx.fillStyle = p.color;
ctx.moveTo(p.x, p.y);
ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2, true);
ctx.fill();
}
confetti.angle += 0.01;
for (var i = 0; i < maxParticles; i++) {
var p = confetti.particles[i];
p.y += Math.cos(confetti.angle + p.d) + 1 + p.r / 2;
p.x += Math.sin(confetti.angle) * 2;
if (p.x > W + 5 || p.x < -5 || p.y > H) {
if (i % 3 > 0) //66.67% of the flakes
{
confetti.particles[i] = {x: Math.random() * W, y: -10, r: p.r, d: p.d, color: p.color};
}
else {
if (Math.sin(confetti.angle) > 0) {
confetti.particles[i] = {x: -5, y: Math.random() * H, r: p.r, d: p.d, color: p.color};
}
else {
confetti.particles[i] = {x: W + 5, y: Math.random() * H, r: p.r, d: p.d, color: p.color};
}
}
}
}
},
onCounterEnd: function () {
stopTimer();
myCounter.stop();
confetti.Stop();
}});
myCounter.start();
},
FadeOut:function fadeOut() {
var alpha = 1.0; // full opacity
for (var i = 0; i < confetti.particles.length; i++) {
var p = confetti.particles[i];
interval = setInterval(function () {
//confetti.canvas.width = confetti.canvas.width; // Clears the canvas
p.color = "rgba(255, 0, 0, " + alpha + ")";
alpha = alpha - 0.05; // decrease opacity (fade out)
if (alpha < 0) {
//confetti.canvas.width = confetti.canvas.width;
clearInterval(interval);
}
}, 50);
}
},
Counter: function Countdown(options) {
var timer,
instance = this,
seconds = options.seconds || 10,
updateStatus = options.onUpdateStatus || function () {
},
counterEnd = options.onCounterEnd || function () {
};
function decrementCounter() {
updateStatus(seconds);
if (seconds === 0) {
counterEnd();
instance.stop();
}
seconds--;
}
this.start = function () {
clearInterval(timer);
timer = 0;
seconds = options.seconds;
timer = setInterval(decrementCounter, options.speed);
};
this.stop = function () {
clearInterval(timer);
};
},
Stop: function stop() {
$('#confettiCanvasId').fadeOut();
setTimeout(function(){
var canvas = document.getElementById("confettiCanvasId");
if (canvas) {
canvas.parentNode.removeChild(canvas);
}
if (confetti.endFunction) {
confetti.endFunction();
}
},1000);
}
};
CSS:
.confettiCanvas{
overflow: hidden;
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
}
I think canvas-confetti is more realistic than any others here, and it has more feature: confetti, snow, fireworks, etc. Click here for demo!