backbone app not showing canvas animation - javascript

I am trying to convert my canvas code into backbone app...
can you guys tell me how to fix it...
providing my code below...
i referred a sample code but could not figure it out...
proving my fiddle and code below...
http://jsfiddle.net/JB9yg/191/
this is my working code without backbone http://jsfiddle.net/QhfVg/7/
var Box = Backbone.Model.extend({
defaults: {
var SIZE = 200;
var SPINNER_WIDTH = 20;
var STEP_PERCENT = 1;
var STEP_DELAY = 20;
var radius, centerX, centerY;
radius = centerX = centerY = SIZE / 2;
var deg360 = Math.PI * 2;
var deg60 = deg360 / 6;
var deg30 = deg360 / 12;
var deg1 = Math.PI / 360;
var deg2 = deg1 * 2;
var degStart = -Math.PI / 2;
var canvas = document.getElementById(id);
canvas.width = canvas.height = SIZE;
var ctx = canvas.getContext('2d');
var percent = 0;
}
});

Your sample code makes me confused :-D,the code below shows the canvas,I hope it works for you:
$(function () {
var SIZE = 200;
var SPINNER_WIDTH = 20;
var STEP_PERCENT = 1;
var STEP_DELAY = 20;
var radius, centerX, centerY;
radius = centerX = centerY = SIZE / 2;
var deg360 = Math.PI * 2;
var deg60 = deg360 / 6;
var deg30 = deg360 / 12;
var deg1 = Math.PI / 360;
var deg2 = deg1 * 2;
var degStart = -Math.PI / 2;
var Box = Backbone.Model.extend({
defaults: {
x: 0,
y: 0,
w: 1,
h: 1,
color: "#FF9000",
linewidth: 3
}});
var BoxSet = Backbone.Collection.extend({
model: Box
});
var BoxView = Backbone.View.extend({
tagName: "canvas",
attributes: {
id: _.uniqueId("canvas")
},
percent: 0,
render: function () {
console.log("Rendering ==> " + this.model.get("name"));
this.start(this.el);
return this;
},
start: function (canvas) {
canvas.width = canvas.height = SIZE;
this.ctx = canvas.getContext('2d');
this.animate();
},
animate: function () {
var self = this, deg, i, n, from, to;
this.ctx.width = this.ctx.height = SIZE;
this.percent += STEP_PERCENT;
deg = this.percent / 100 * deg360;
this.drawArc('#aaa', radius, deg360);
this.drawArc('#0e728e', radius, deg);
for (i = 0, n = Math.floor(deg / deg60); i < n; i++) {
from = i * deg30 + deg2;
to = from + deg30 - deg2 * 2
this.drawArc('#250696', radius, to, from);
}
this.drawArc('#fff', radius - SPINNER_WIDTH, deg360);
if (this.percent >= 100) {
document.getElementById('text').innerText = 'FINISHED';
} else {
setTimeout(function () {
self.animate();
}, STEP_DELAY);
}
},
drawArc: function (color, arcRadius, degTo, degFrom) {
if (!degFrom) {
degFrom = 0;
}
this.ctx.fillStyle = color;
this.ctx.beginPath();
this.ctx.moveTo(centerX, centerY);
this.ctx.arc(centerX, centerY, arcRadius, degStart + degFrom, degStart + degTo, false);
this.ctx.lineTo(centerX, centerY);
this.ctx.fill();
}
});
var BoxSetView = Backbone.View.extend({
className: "container",
render: function () {
this.collection.each(function (model) {
var boxView = new BoxView({model: model});
this.$el.append(boxView.render().$el)
}, this);
return this;
}
});
var c = new BoxSet([
{
name: "canvas1"
},
{
name: "canvas2"
},
{
name: "canvas3"
},
{
name: "canvas4"
}
]);
var v = new BoxSetView({
collection: c
});
$("body").append(v.render().$el);
});

Related

Can't repeat js function in same page

Please be kind I'm a real beginner.
I'm trying to use this function twice on the same page (in different sections) but am unable to do this. I assume I somehow need to label it differently each time I use it, but can't figure out where.
Maybe the functions are not labeled correctly but I have tried trying this.
Here is the JS
(function () {
var lastTime = 0;
var vendors = ["ms", "moz", "webkit", "o"];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"];
window.cancelAnimationFrame =
window[vendors[x] + "CancelAnimationFrame"] ||
window[vendors[x] + "CancelRequestAnimationFrame"];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
})();
var Nodes = {
// Settings
density: 20,
reactionSensitivity: 10,
points: [],
lines: [[], [], [], []],
mouse: { x: 10, y: 10, down: false },
animation: null,
canvas: null,
context: null,
init: function () {
// Set up the visual canvas
this.canvas = document.getElementById("stripes2");
this.context = this.canvas.getContext("2d");
this.context.lineJoin = "bevel";
this.canvas.width = window.innerHeight*2;
this.canvas.height = window.innerHeight;
this.canvas.style.display = "block";
this.canvas.addEventListener("mousemove", this.mouseMove, false);
this.canvas.addEventListener("mousedown", this.mouseDown, false);
this.canvas.addEventListener("mouseup", this.mouseUp, false);
this.canvas.addEventListener("mouseout", this.mouseOut, false);
window.onresize = function (event) {
Nodes.canvas.width = (window.innerHeight*2);
Nodes.canvas.height = Math.max(window.innerHeight, 1000);
Nodes.onWindowResize();
};
this.preparePoints();
this.draw();
},
preparePoints: function () {
// Clear the current points
this.points = [];
this.lines = [[], [], [], [], []];
var width, height, i;
var center = window.innerHeight / 2;
for (i = -1000; i < this.canvas.width + 1000; i += this.density) {
var line1 = { y: center - 17, originalY: center - -100, color: "#249FA4" };
var line2 = { y: center - 17, originalY: center - -50, color: "#3DB8B5" };
var line3 = { y: center - 17, originalY: center - 0, color: "#F8DCAA" };
var line4 = { y: center - 17, originalY: center - 50, color: "#F1B30A" };
var line5 = { y: center - 17, originalY: center - 100, color: "#E77419" };
line1["x"] = i;
line1["originalX"] = i;
line2["x"] = i;
line2["originalX"] = i;
line3["x"] = i;
line3["originalX"] = i;
line4["x"] = i;
line4["originalX"] = i;
line5["x"] = i;
line5["originalX"] = i;
this.points.push(line1);
this.points.push(line2);
this.points.push(line3);
this.points.push(line4);
this.points.push(line5);
this.lines[0].push(line1);
this.lines[1].push(line2);
this.lines[2].push(line3);
this.lines[3].push(line4);
this.lines[4].push(line5);
}
},
updatePoints: function () {
var i, currentPoint, theta, distance;
for (i = 0; i < this.points.length; i++) {
currentPoint = this.points[i];
theta = Math.atan2(
currentPoint.y - this.mouse.y,
currentPoint.x - this.mouse.x
);
if (this.mouse.down) {
distance =
(this.reactionSensitivity * 300) /
Math.sqrt(
(this.mouse.x - currentPoint.x) * (this.mouse.x - currentPoint.x) +
(this.mouse.y - currentPoint.y) * (this.mouse.y - currentPoint.y)
);
} else {
distance =
(this.reactionSensitivity * 150) /
Math.sqrt(
(this.mouse.x - currentPoint.x) * (this.mouse.x - currentPoint.x) +
(this.mouse.y - currentPoint.y) * (this.mouse.y - currentPoint.y)
);
}
currentPoint.x +=
Math.cos(theta) * distance +
(currentPoint.originalX - currentPoint.x) * 0.07;
currentPoint.y +=
Math.sin(theta) * distance +
(currentPoint.originalY - currentPoint.y) * 0.07;
}
},
drawPoints: function () {
var i, currentPoint;
for (i = 0; i < 5; i++) {
var line = this.lines[i];
this.context.beginPath();
this.context.lineJoin = "round";
this.context.moveTo(line[0].x, line[0].y);
this.context.strokeStyle = line[0].color;
this.context.lineWidth = 50;
for (var j = 1; j < line.length - 2; j++) {
var point = line[j];
var xc = (point.x + line[j + 1].x) / 2;
var yc = (point.y + line[j + 1].y) / 2;
this.context.quadraticCurveTo(point.x, point.y, xc, yc);
}
this.context.stroke();
this.context.closePath();
}
},
draw: function () {
this.animation = requestAnimationFrame(function () {
Nodes.draw();
});
this.clear();
this.updatePoints();
this.drawPoints();
},
clear: function () {
this.canvas.width = this.canvas.width;
},
mouseDown: function (event) {
Nodes.mouse.down = true;
},
mouseUp: function (event) {
Nodes.mouse.down = false;
},
mouseMove: function (event) {
Nodes.mouse.x = event.pageY;
Nodes.mouse.y = event.pageY;
},
mouseOut: function (event) {
Nodes.mouse.x = -1000;
Nodes.mouse.y = -1000;
Nodes.mouse.down = false;
},
// Resize and redraw the canvas.
onWindowResize: function () {
cancelAnimationFrame(this.animation);
this.preparePoints();
this.draw();
}
};
// Start the app.
setTimeout(function () {
Nodes.init();
}, 10);
<canvas id="stripes2" class="container">
Many thanks

Canvas Arc Issue - Arc Animation wiping out the Canvas default values

Canvas Arc Issue - Animation wiping out the Canvas default values - Chartjs new Gauge type.
I worked on overriding chart js Gauge by animating new the current value:
Initial view:
The issue with the view:
The arc is wiping out previously drawn gauge since I am replacing with white circles
Expected view:
Animates to the intended position without wiping out the previous canvas.
While animating the old bar color changes until the intended progress point.
The issue is with:
Wiping out canvas issue is with : GaugeChartHelper.prototype.clearValueCircle
Animation: I was not able to figure out a nice way to change gauge progress color
Note: I am very new to canvas drawing. So providing examples or any help is appreciated.
fiddle:
JSFIDDLE Link
var settings = {
type: "tsgauge",
data: {
datasets: [{
backgroundColor: ["#ccc", "#ccc", "#ccc"],
borderWidth: 0,
gaugeData: {
value: 500,
valueColor: "#ff7143"
},
gaugeLimits: [0, 100, 250, 550],
gaugeEarned: [0, 1200, 3000, 5000],
gaugeCurrency: "mi",
}]
},
options: {
events: [],
showMarkers: true
}
};
function initChart() {
var $indicatorElement = document.getElementById("mn_canvas");
var indicatorElementContext = $indicatorElement.getContext("2d");
new Chart(indicatorElementContext, settings);
};
function GaugeChartHelper() {}
GaugeChartHelper.prototype.setup = function(chart, config) {
this.chart = chart;
this.ctx = chart.ctx;
this.limits = config.data.datasets[0].gaugeLimits;
this.earning = config.data.datasets[0].gaugeEarned;
this.language = config.data.datasets[0].gaugeCurrency;
this.data = config.data.datasets[0].gaugeData;
var options = chart.options;
this.fontSize = options.defaultFontSize;
this.fontStyle = options.defaultFontFamily;
this.fontColor = options.defaultFontColor;
this.ctx.textBaseline = "alphabetic";
this.circleAngle = 25 * Math.PI / 180;
this.circleColor = config.options.indicatorColor || options.circleColor;
this.showMarkers = typeof(config.options.showMarkers) === 'undefined' ? true : config.options.showMarkers;
if (config.options.markerFormatFn) {
this.markerFormatFn = config.options.markerFormatFn;
} else {
this.markerFormatFn = function(value) {
return value;
}
}
};
GaugeChartHelper.prototype.applyGaugeConfig = function(chartConfig) {
this.calcLimits();
chartConfig.data.datasets[0].data = this.doughnutData;
var ctx = this.ctx;
var labelsWidth = this.limits.map(function(label) {
var text = this.markerFormatFn(label);
return ctx.measureText(text).width;
}.bind(this));
var padding = Math.max.apply(this, labelsWidth) + this.chart.width / 35 + 10;
var heightRatio = this.chart.height / 50;
chartConfig.options.layout.padding = {
top: this.fontSize + heightRatio + 10,
left: padding + 10,
right: padding + 10,
bottom: heightRatio * 2
};
};
GaugeChartHelper.prototype.calcLimits = function() {
var limits = this.limits;
var data = [];
var total = 0;
for (var i = 1, ln = limits.length; i < ln; i++) {
var dataValue = Math.abs(limits[i] - limits[i - 1]);
total += dataValue;
data.push(dataValue);
}
this.doughnutData = data;
var minValue = limits[0];
var maxValue = limits[limits.length - 1];
this.isRevers = minValue > maxValue;
this.minValue = this.isRevers ? maxValue : minValue;
this.totalValue = total;
};
GaugeChartHelper.prototype.updateGaugeDimensions = function() {
var chartArea = this.chart.chartArea;
this.gaugeRadius = this.chart.innerRadius;
this.gaugeCenterX = (chartArea.left + chartArea.right) / 2;
this.gaugeCenterY = (chartArea.top + chartArea.bottom + this.chart.outerRadius) / 2;
this.circleLength = this.chart.radiusLength * .8;
};
GaugeChartHelper.prototype.getCoordOnCircle = function(r, alpha) {
return {
x: r * Math.cos(alpha),
y: r * Math.sin(alpha)
};
};
GaugeChartHelper.prototype.getAngleOfValue = function(value) {
var result = 0;
var gaugeValue = value - this.minValue;
if (gaugeValue <= 0) {
result = 0;
} else if (gaugeValue >= this.totalValue) {
result = Math.PI;
} else {
result = Math.PI * gaugeValue / this.totalValue;
}
if (this.isRevers) {
return Math.PI - result;
} else {
return result;
}
};
GaugeChartHelper.prototype.renderLimitLabel = function(value, earningValue) {
var ctx = this.ctx;
var angle = this.getAngleOfValue(value);
var coord = this.getCoordOnCircle(this.chart.outerRadius + (this.chart.radiusLength / 2), angle);
var align;
var diff = angle - (Math.PI / 2);
if (diff > 0) {
align = "left";
} else if (diff < 0) {
align = "right";
} else {
align = "center";
}
/* ctx.textAlign = align;
ctx.font = this.fontSize + "px " + this.fontStyle;
ctx.fillStyle = this.fontColor;
var text = '$' + this.markerFormatFn(value);
ctx.beginPath();
ctx.fillStyle = "#ccc";
ctx.arc(this.gaugeCenterX - coord.x, this.gaugeCenterY - coord.y, this.circleLength, 0, 2 * Math.PI, false);
ctx.fill();
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.fillText(text, this.gaugeCenterX - coord.x, this.gaugeCenterY - coord.y);*/
if (value !== 0) {
this.renderCircle(this.gaugeRadius, angle, this.circleLength, this.circleAngle, '#ccc', value);
}
ctx.textAlign = align;
ctx.font = this.fontSize + "px " + this.fontStyle;
ctx.fillStyle = '#ccc';
ctx.fillText(earningValue + " mi", this.gaugeCenterX - coord.x, this.gaugeCenterY - coord.y);
};
GaugeChartHelper.prototype.renderCircle = function(radius, angle, circleLength, circleAngle, circleColor, value) {
var text = "$" + (typeof value === "number" ? value : this.data.value);
var coord = this.getCoordOnCircle(radius * 1.18, angle);
var circlePoint = {
x: this.gaugeCenterX - coord.x,
y: this.gaugeCenterY - coord.y
};
var ctx = this.ctx;
ctx.fillStyle = circleColor;
ctx.beginPath();
ctx.moveTo(circlePoint.x, circlePoint.y);
coord = this.getCoordOnCircle(circleLength * 1.18, angle - circleAngle);
ctx.arc((circlePoint.x + coord.x), (circlePoint.y + coord.y), circleLength, 0, 25 * Math.PI);
ctx.closePath();
ctx.fill();
ctx.fillStyle = '#fff';
ctx.textAlign = 'center';
ctx.font = "8px " + this.fontStyle;
ctx.fillText(text, (circlePoint.x + coord.x), (circlePoint.y + coord.y) + 3);
};
GaugeChartHelper.prototype.renderLimits = function() {
for (var i = 0, ln = this.limits.length; i < ln; i++) {
this.renderLimitLabel(this.limits[i], this.earning[i]);
}
};
GaugeChartHelper.prototype.renderValueLabel = function() {
var label = this.data.value.toString();
var ctx = this.ctx;
ctx.font = "30px " + this.fontStyle;
var stringWidth = ctx.measureText(label).width;
var elementWidth = 0.75 * this.gaugeRadius * 2;
var widthRatio = elementWidth / stringWidth;
var newFontSize = Math.floor(30 * widthRatio);
var fontSizeToUse = Math.min(newFontSize, this.gaugeRadius);
ctx.textAlign = "center";
ctx.font = "30px " + this.fontStyle;
ctx.fillStyle = this.data.valueColor || this.fontColor;
ctx.fillText(label, this.gaugeCenterX, this.gaugeCenterY);
};
GaugeChartHelper.prototype.renderValueCircle = function(value) {
var angle = this.getAngleOfValue(typeof value === "number" ? value : this.data.value);
this.ctx.globalCompositeOperation = "source-over";
this.renderCircle(this.gaugeRadius, angle, this.circleLength, this.circleAngle, this.circleColor, value);
};
GaugeChartHelper.prototype.renderSmallValueCircle = function(value) {
var angle = this.getAngleOfValue(value);
this.ctx.globalCompositeOperation = "source-over";
this.renderCircle(this.gaugeRadius - 1, angle, this.circleLength - 1, this.circleAngle, this.circleColor, value);
};
GaugeChartHelper.prototype.clearValueCircle = function(value) {
var angle = this.getAngleOfValue(value);
this.ctx.lineWidth = 0;
this.ctx.globalCompositeOperation = "destination-out";
this.renderCircle(this.gaugeRadius - 1, angle, this.circleLength + 1, this.circleAngle, "#fff", value);
this.ctx.stroke();
};
GaugeChartHelper.prototype.animateCircle = function() {
var stepCount = 30;
var animateTimeout = 300;
var gaugeValue = this.data.value - this.minValue;
var step = gaugeValue / stepCount;
var i = 0;
var currentValue = this.minValue;
var interval = setInterval(function() {
i++;
this.clearValueCircle(currentValue);
if (i > stepCount) {
clearInterval(interval);
this.renderValueCircle();
} else {
currentValue += step;
this.renderSmallValueCircle(currentValue);
}
}.bind(this), animateTimeout / stepCount);
};
Chart.defaults.tsgauge = {
animation: {
animateRotate: false,
animateScale: false
},
cutoutPercentage: 88,
rotation: Math.PI,
circumference: Math.PI,
legend: {
display: false
},
scales: {},
circleColor: "#444"
};
Chart.controllers.tsgauge = Chart.controllers.doughnut.extend({
initialize: function(chart) {
var gaugeHelper = this.gaugeHelper = new GaugeChartHelper();
gaugeHelper.setup(chart, chart.config);
gaugeHelper.applyGaugeConfig(chart.config);
chart.config.options.animation.onComplete = function(chartElement) {
gaugeHelper.updateGaugeDimensions();
gaugeHelper.animateCircle();
};
Chart.controllers.doughnut.prototype.initialize.apply(this, arguments);
},
draw: function() {
Chart.controllers.doughnut.prototype.draw.apply(this, arguments);
var gaugeHelper = this.gaugeHelper;
gaugeHelper.updateGaugeDimensions();
gaugeHelper.renderValueLabel();
if (gaugeHelper.showMarkers) {
gaugeHelper.renderLimits();
}
gaugeHelper.renderSmallValueCircle(gaugeHelper.minValue);
}
});
initChart();
.mn_indicatorCanvasContainer {
width: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<div class="mn_indicatorCanvasContainer">
<canvas id="mn_canvas" class="mn_canvas">
</canvas>
</div>

How to change thickness / height of lines

I found this codepen that I'd like to use but want the lines to appear 'thinner'. Which variable do I change?
Here is the link to the code and here is the code:
<canvas id="stripes">
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame =
window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
||
window[vendors[x]+'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};
if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());
var Nodes = {
// Settings
density: 6,
reactionSensitivity: 3,
points: [],
lines: [[], []],
mouse: { x: -1000, y: -1000, down: false },
animation: null,
canvas: null,
context: null,
init: function() {
// Set up the visual canvas
this.canvas = document.getElementById( 'stripes' );
this.context = this.canvas.getContext( '2d' );
this.context.lineJoin = 'bevel';
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.canvas.style.display = 'block'
this.canvas.addEventListener('mousemove', this.mouseMove, false);
this.canvas.addEventListener('mousedown', this.mouseDown, false);
this.canvas.addEventListener('mouseup', this.mouseUp, false);
this.canvas.addEventListener('mouseout', this.mouseOut, false);
window.onresize = function(event) {
Nodes.canvas.width = window.innerWidth;
Nodes.canvas.height = Math.max(window.innerHeight, 670);
Nodes.onWindowResize();
}
this.preparePoints();
this.draw();
},
preparePoints: function() {
// Clear the current points
this.points = [];
this.lines = [[],[]];
var width, height, i;
var center = window.innerHeight / 2;
for( i = -10; i < this.canvas.width + 10; i += this.density ) {
var line1 = {y: center - 17, originalY: center - 10, color: '#B1FB17'};
var line2 = {y: center - 17, originalY: center - 25, color: '#F52887'};
line1["x"] = i;
line1["originalX"] = i;
line2["x"] = i;
line2["originalX"] = i;
this.points.push(line1);
this.points.push(line2);
this.lines[0].push(line1);
this.lines[1].push(line2);
}
},
updatePoints: function() {
var i, currentPoint, theta, distance;
for (i = 0; i < this.points.length; i++ ){
currentPoint = this.points[i];
theta = Math.atan2( currentPoint.y - this.mouse.y, currentPoint.x - this.mouse.x);
if ( this.mouse.down ) {
distance = this.reactionSensitivity * 300 / Math.sqrt((this.mouse.x - currentPoint.x) * (this.mouse.x - currentPoint.x) +
(this.mouse.y - currentPoint.y) * (this.mouse.y - currentPoint.y));
} else {
distance = this.reactionSensitivity * 150 / Math.sqrt((this.mouse.x - currentPoint.x) * (this.mouse.x - currentPoint.x) +
(this.mouse.y - currentPoint.y) * (this.mouse.y - currentPoint.y));
}
currentPoint.x += Math.cos(theta) * distance + (currentPoint.originalX - currentPoint.x) * 0.07;
currentPoint.y += Math.sin(theta) * distance + (currentPoint.originalY - currentPoint.y) * 0.07;
}
},
drawPoints: function() {
var i, currentPoint;
for (i = 0; i < 2; i++) {
var line = this.lines[i];
this.context.beginPath();
this.context.lineJoin = 'round';
this.context.moveTo( line[0].x, line[0].y);
this.context.strokeStyle = line[0].color;
this.context.lineWidth = 10;
for (var j = 1; j < line.length - 2; j++) {
var point = line[j];
var xc = (point.x + line[j + 1].x) / 2;
var yc = (point.y + line[j + 1].y) / 2;
this.context.quadraticCurveTo(point.x, point.y, xc, yc);
}
this.context.stroke();
this.context.closePath();
}
},
draw: function() {
this.animation = requestAnimationFrame( function(){ Nodes.draw() } );
this.clear();
this.updatePoints();
this.drawPoints();
},
clear: function() {
this.canvas.width = this.canvas.width;
},
mouseDown: function( event ){
Nodes.mouse.down = true;
},
mouseUp: function( event ){
Nodes.mouse.down = false;
},
mouseMove: function(event){
Nodes.mouse.x = event.pageX;
Nodes.mouse.y = event.pageY;
},
mouseOut: function(event){
Nodes.mouse.x = -1000;
Nodes.mouse.y = -1000;
Nodes.mouse.down = false;
},
// Resize and redraw the canvas.
onWindowResize: function() {
cancelAnimationFrame( this.animation );
this.preparePoints();
this.draw();
}
}
// Start the app.
setTimeout( function() {
Nodes.init();
}, 10);
Look for linewidth - actually with a bit of reading you cold solve this yourself!

Create radial Timer

I Want to create an radial timer.
The Problem is, the arc are not painting correctly, when i try to set the start and end angle.
Thats, what i want:
Here is my code:
var Timer = function Timer(selector) {
var _width = 134;
var _height = 134;
var _x = _width / 2;
var _y = _height / 2;
var _canvas = null;
var _context = null;
var _percentage = 0;
var _background = '#000000';
var _foreground = '#FF0000';
this.init = function init(selector) {
var element = document.querySelector(selector);
_canvas = document.createElement('canvas');
_canvas.setAttribute('width', _width);
_canvas.setAttribute('height', _height);
element.parentNode.replaceChild(_canvas, element);
_context = _canvas.getContext('2d');
this.paint();
};
this.clear = function clear() {
_context.clearRect(0, 0, _width, _height);
};
this.start = function start(seconds) {
var current = seconds;
var _watcher = setInterval(function AnimationInterval() {
_percentage = 100 * current / seconds;
if(_percentage < 0) {
_percentage = 0;
clearInterval(_watcher);
} else if(_percentage > 100) {
_percentage = 100;
clearInterval(_watcher);
}
this.paint();
console.log(_percentage + '%');
--current;
}.bind(this), 1000);
};
this.paint = function paint() {
this.clear();
this.paintBackground();
this.paintForeground();
};
this.paintForeground = function paintForeground() {
_context.beginPath();
_context.arc(_x, _y, 134 / 2 - 5, -(Math.PI / 2), ((Math.PI * 2) * _percentage) - (Math.PI / 2), false);
_context.lineWidth = 8;
_context.strokeStyle = _foreground;
_context.stroke();
};
this.paintBackground = function paintBackground() {
_context.beginPath();
_context.arc(_x, _y, 134 / 2 - 5, 0, Math.PI * 2, false);
_context.lineWidth = 10;
_context.strokeStyle = _background;
_context.stroke();
};
this.init(selector);
};
var timer = new Timer('timer');
timer.start(10);
<timer></timer>
Can you tell me, what i make wrong?

(Three.js) Change color on particles forming image

I'm currently working on a particle system where the particles move around and create pictures with some seconds in between (almost like a slide). I know where to put the color code to change the color on the particles forming the pictures bur for some reason it doesn't work. I therefore suspect that the problem is somewhere else in the script but the question is where...
You can see the code below (tried to make a codepen but it didn't work):
var dispersed = false;
var firstDone = false;
var secondDone = false;
var thirdDone = false;
var fRgba = []; // first img rgba data
var sRgba = []; // second img rgba data
var tRgba = []; // third img rgba data
var WIDTH = window.innerWidth,
HEIGHT = window.innerHeight;
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.01,
FAR = 10000;
var $container = $("#container");
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera(
VIEW_ANGLE,
ASPECT,
NEAR,
FAR);
var scene = new THREE.Scene();
scene.add(camera);
camera.position.z = 900;
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
var particleCount = 5200,
particles = new THREE.Geometry();
var pMaterial = new THREE.PointsMaterial({
size: 6,
map: createCircleTexture('#CACACA', 256),
transparent: true,
depthWrite: false
});
function createCircleTexture(color, size) {
var matCanvas = document.createElement('canvas');
matCanvas.width = matCanvas.height = size;
var matContext = matCanvas.getContext('2d');
var texture = new THREE.Texture(matCanvas);
var center = size / 2;
matContext.beginPath();
matContext.arc(center, center, size/2, 0, 2 * Math.PI, false);
matContext.closePath();
matContext.fillStyle = color;
matContext.fill();
texture.needsUpdate = true;
return texture;
}
for (var i = 0; i < particleCount; i++) {
var x = Math.random() * 1600 - 800;
var y = getRandomInt(600, 1500)
var z = Math.random() * 30 - 15;
var particle = new THREE.Vector3(x, y, z);
particle.updated = 0;
particles.vertices.push(particle);
};
var particleSystem = new THREE.Points(particles, pMaterial);
particleSystem.sortParticles = true;
scene.add(particleSystem);
function drawImage(imageObj, array) {
var canvas = $("#canvas")[0];
var context = canvas.getContext("2d");
var imageX = 0;
var imageY = 0;
var imageWidth = imageObj.width;
var imageHeight = imageObj.height;
context.drawImage(imageObj, imageX, imageY);
var imageData = context.getImageData(imageX, imageY, imageWidth,
imageHeight);
var data = imageData.data;
for(var y = 0; y < imageHeight; y+= 4) {
for(var x = 0; x < imageWidth; x+= 4) {
var red = data[((imageWidth * y) + x) * 4];
var green = data[((imageWidth * y) + x) * 4 + 1];
var blue = data[((imageWidth * y) + x) * 4 + 2];
var alpha = data[((imageWidth * y) + x) * 4 + 3];
if (red < 100) {
var pX = (x % 500) - 249;
var pY = 249 - y;
array.push([pX, pY, red, green, blue, alpha]);
}
}
}
};
var addDestination = function(particle, x, y, z) {
var dest = new THREE.Vector3(x, y, z);
particle.destination = dest;
};
var addVelocity = function(particle) {
var xDiff = (particle.destination.x - particle.x) / 180;
var yDiff = (particle.destination.y - particle.y) / 180;
var zDiff = (particle.destination.z - particle.z) / 180;
var vel = new THREE.Vector3(xDiff, yDiff, zDiff);
particle.velocity = vel;
};
var move = function(particle) {
particle.x += particle.velocity.x;
particle.y += particle.velocity.y;
particle.z += particle.velocity.z;
particle.updated += 1;
};
var slowDown = function(particle) {
particle.velocity.x -= (particle.velocity.x / 300)
particle.velocity.y -= (particle.velocity.y / 300)
particle.velocity.z -= (particle.velocity.z / 160)
};
var resetProperties = function() {
var pCount = particleCount;
while (pCount--) {
var particle = particles.vertices[pCount];
particle.destination = null
particle.updated = 0;
};
};
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
};
var distributedZ = function(level) {
var z;
if (level === 1) {
z = getRandomInt(50, 100);
} else if (level === 2) {
z = getRandomInt(350, 400);
} else {
z = getRandomInt(650, 700);
}
return z;
};
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
var disperse = function() {
pCount = particleCount;
for (var i = 0; i < pCount; i++) {
var particle = particles.vertices[i];
if (typeof(particle.destination) === "undefined") {
var nums = [-1, 1];
var x = particle.x + nums[Math.round(Math.random())];
var y = particle.y - 1000;
var z = Math.random() * 30 - 15;
addDestination(particle, x, y, z);
particle.velocity = new THREE.Vector3(x - particle.x, -3, z -
particle.z);
}
if (particle.updated <= 300) {
move(particle);
} else {
particles.vertices = shuffle(particles.vertices);
resetProperties();
dispersed = true;
return;
}
}
}
var morphImageParticles = function(imageParticles, rgba) {
for (var i = 0; i < imageParticles.length; i++) {
var particle = imageParticles[i]
if (particle.destination === null) {
var pixelData = rgba[i];
var x = pixelData[0];
var y = pixelData[1];
var z = Math.random() * 15 - 7;
addDestination(particle, x, y, z);
addVelocity(particle);
}
if (particle.updated <= 180) {
move(particle);
}
}
};
var morphOuterParticles = function(outerParticles, ord) {
for (var i = 0; i < outerParticles.length; i++) {
var nums = [-1, 1];
var particle = outerParticles[i];
if (particle.destination === null) {
var x = Math.random() * 1000 - 500;
var y = Math.random() * 1000 - 500;
var z;
if (i <= Math.round(outerParticles.length * 0.6)) {
z = distributedZ(1)
} else if (i > Math.round(outerParticles.length * 0.6) && i <
Math.round(outerParticles.length * 0.9)) {
z = distributedZ(2)
} else {
z = distributedZ(3);
}
addDestination(particle, x, y, z);
addVelocity(particle);
}
if (particle.updated <= 600) {
move(particle);
slowDown(particle);
} else {
particles.vertices = shuffle(particles.vertices);
resetProperties();
if (ord === 1) {
firstDone = true;
} else if (ord === 2) {
secondDone = true;
} else {
thirdDone = true;
}
return;
}
}
};
var makeImg = function(rgba, ord) {
var pCount = particleCount;
var imagePs = particles.vertices.slice(0, rgba.length);
var outerPs = particles.vertices.slice(rgba.length, pCount);
morphImageParticles(imagePs, rgba);
morphOuterParticles(outerPs, ord);
};
var update = function() {
if (thirdDone) {
} else if (secondDone) {
makeImg(tRgba, 3);
} else if (firstDone) {
makeImg(sRgba, 2);
} else if (dispersed) {
makeImg(fRgba, 1);
} else {
disperse();
}
particleSystem.geometry.verticesNeedUpdate = true;
renderer.render(scene, camera);
requestAnimationFrame(update);
TWEEN.update();
};
var rotXScale = d3.scale.linear().domain([0, window.innerHeight]).range([15,
-15]);
var rotYScale = d3.scale.linear().domain([0, window.innerWidth]).range([25,
-25]);
d3.select("body").on("mousemove", function() {
var scaledX = rotXScale(d3.mouse(this)[1]) * Math.PI / 180;
var scaledY = rotYScale(d3.mouse(this)[0]) * Math.PI / 180;
var tween = new TWEEN.Tween(particleSystem.rotation).to({ x: scaledX, y:
scaledY, z: 0 });
tween.easing( TWEEN.Easing.Quartic.Out);
tween.start();
transparency: true
});
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
img1.onload = function() {
drawImage(this, fRgba);
img2.onload = function() {
drawImage(this, sRgba);
img3.onload = function() {
drawImage(this, tRgba);
}
img3.src = "images/p1.png";
}
img2.src = "images/p2.png";
update();
}
img1.src = "images/p3.png";
update();
I thought I only need to add the code below, for example ['0xffffff'], that's how it should work at least but it didn't. Therefore I guess the problem is somewhere else in the script.
var fRgba = []; // first img rgba data
var sRgba = []; // second img rgba data
var tRgba = []; // third img rgba data

Categories

Resources