Positioning divs in a circle using JavaScript - javascript

I am trying to position 15 div elements evenly in a circle with a radius of 150px. I'm using the following code, which seems to give an oddly eccentric ellipse that overlaps.
Fiddle
// Hold a global reference to the div#main element. Initially assign it ... somewhere useful :)
var main = document.getElementById('main');
var circleArray = [];
// Move a circle based on the distance of the approaching mouse
var moveCircle = function(circle, dx, dy) {
};
// Look at all the circle elements, and figure out if any of them have to move.
var checkMove = function() {
};
var setup = function() {
for (var i = 0; i < 15; i++) {
//create element, add it to the array, and assign it's coordinates trigonometrically.
//Then add it to the "main" div
var circle = document.createElement('div');
circle.className = 'circle number' + i;
circleArray.push(circle);
circleArray[i].posx = Math.round((150 * Math.cos(i * (2 * Math.PI / 15)))) + 'px';
circleArray[i].posy = Math.round((150 * Math.sin(i * (2 * Math.PI / 15)))) + 'px';
circleArray[i].style.position = "relative";
circleArray[i].style.top = circleArray[i].posy;
circleArray[i].style.left = circleArray[i].posx;
main.appendChild(circleArray[i]);
}
};
setup();
window.addEventListener('load', function() {
});
div {
box-sizing: border-box;
}
div#main {
position: absolute;
left: 50%;
top: 50%;
}
div.circle {
position: absolute;
width: 20px;
height: 20px;
border: 2px solid black;
border-radius: 10px;
-webkit-border-radius: 10px;
-moz-border-radius: 10px;
}
<div id="main"></div>
Any suggestions as to what I might be doing wrong?

First of all, the equation for a co-ordinate on a circle is simply:
(x, y) = (r * cos(θ), r * sin(θ))
where, r is the radius of a circle and θ is the angle in radians.
The reason why your code is creating an eccentric ellipse is because when you assign the .top and .left CSS values, you are not considering that it will actually take the top-left corner as its reference. I've fixed your code and now it creates a perfect circle.
Changes made to your code:
Added an array theta that holds all the angles.
var theta = [0, Math.PI / 6, Math.PI / 4, Math.PI / 3, Math.PI / 2, 2 * (Math.PI / 3), 3 * (Math.PI / 4), 5 * (Math.PI / 6), Math.PI, 7 * (Math.PI / 6), 5 * (Math.PI / 4), 4 * (Math.PI / 3), 3 * (Math.PI / 2), 5 * (Math.PI / 3), 7 * (Math.PI / 4), 11 * (Math.PI / 6)];
The image below shows all the angles I've used.
Added an array colors that holds different colors.
var colors = ['red', 'green', 'purple', 'black', 'orange', 'yellow', 'maroon', 'grey', 'lightblue', 'tomato', 'pink', 'maroon', 'cyan', 'magenta', 'blue', 'chocolate', 'DarkSlateBlue'];
Made changes to your trigonometric equations.
circleArray[i].posx = Math.round(radius * (Math.cos(theta[i]))) + 'px';
circleArray[i].posy = Math.round(radius * (Math.sin(theta[i]))) + 'px';
Changed the way .top and .left are assigned.
circleArray[i].style.top = ((mainHeight / 2) - parseInt(circleArray[i].posy.slice(0, -2))) + 'px';
circleArray[i].style.left = ((mainHeight / 2) + parseInt(circleArray[i].posx.slice(0, -2))) + 'px';
where mainHeight is the height of the #main div.
[1] 16 divs
Demo on Fiddle
var setup = function() {
var radius = 150;
var main = document.getElementById('main');
var mainHeight = parseInt(window.getComputedStyle(main).height.slice(0, -2));
var theta = [0, Math.PI / 6, Math.PI / 4, Math.PI / 3, Math.PI / 2, 2 * (Math.PI / 3), 3 * (Math.PI / 4), 5 * (Math.PI / 6), Math.PI, 7 * (Math.PI / 6), 5 * (Math.PI / 4), 4 * (Math.PI / 3), 3 * (Math.PI / 2), 5 * (Math.PI / 3), 7 * (Math.PI / 4), 11 * (Math.PI / 6)];
var circleArray = [];
var colors = ['red', 'green', 'purple', 'black', 'orange', 'yellow', 'maroon', 'grey', 'lightblue', 'tomato', 'pink', 'maroon', 'cyan', 'magenta', 'blue', 'chocolate', 'DarkSlateBlue'];
for (var i = 0; i < 16; i++) {
var circle = document.createElement('div');
circle.className = 'circle number' + i;
circleArray.push(circle);
circleArray[i].posx = Math.round(radius * (Math.cos(theta[i]))) + 'px';
circleArray[i].posy = Math.round(radius * (Math.sin(theta[i]))) + 'px';
circleArray[i].style.position = "absolute";
circleArray[i].style.backgroundColor = colors[i];
circleArray[i].style.top = ((mainHeight / 2) - parseInt(circleArray[i].posy.slice(0, -2))) + 'px';
circleArray[i].style.left = ((mainHeight / 2) + parseInt(circleArray[i].posx.slice(0, -2))) + 'px';
main.appendChild(circleArray[i]);
}
};
setup();
div#main {
height: 300px;
width: 300px;
position: absolute;
margin: 0 auto;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}
div.circle {
position: absolute;
width: 20px;
height: 20px;
border: 2px solid black;
border-radius: 50%;
}
body {
margin: 0 auto;
background: papayawhip;
}
<div id="main"></div>
[2] 15 divs Positioned Evenly
Demo on Fiddle
var setup = function() {
var radius = 150;
var main = document.getElementById('main');
var mainHeight = parseInt(window.getComputedStyle(main).height.slice(0, -2));
var theta = [0, (2 * (Math.PI / 15)), (4 * (Math.PI / 15)), (2 * (Math.PI / 5)), (8 * (Math.PI / 15)), (2 * (Math.PI / 3)), (4 * (Math.PI / 5)), (14 * (Math.PI / 15)), (16 * (Math.PI / 15)), (6 * (Math.PI / 5)), (4 * (Math.PI / 3)), (22 * (Math.PI / 15)), (8 * (Math.PI / 5)), (26 * (Math.PI / 15)), (28 * (Math.PI / 15))];
var circleArray = [];
var colors = ['red', 'green', 'purple', 'black', 'orange', 'yellow', 'maroon', 'grey', 'lightblue', 'tomato', 'pink', 'maroon', 'cyan', 'magenta', 'blue', 'chocolate', 'DarkSlateBlue'];
for (var i = 0; i < 15; i++) {
var circle = document.createElement('div');
circle.className = 'circle number' + i;
circleArray.push(circle);
circleArray[i].posx = Math.round(radius * (Math.cos(theta[i]))) + 'px';
circleArray[i].posy = Math.round(radius * (Math.sin(theta[i]))) + 'px';
circleArray[i].style.position = "absolute";
circleArray[i].style.backgroundColor = colors[i];
circleArray[i].style.top = ((mainHeight / 2) - parseInt(circleArray[i].posy.slice(0, -2))) + 'px';
circleArray[i].style.left = ((mainHeight / 2) + parseInt(circleArray[i].posx.slice(0, -2))) + 'px';
main.appendChild(circleArray[i]);
}
};
setup();
div#main {
height: 300px;
width: 300px;
position: absolute;
margin: 0 auto;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}
div.circle {
position: absolute;
width: 20px;
height: 20px;
border: 2px solid black;
border-radius: 50%;
}
body {
margin: 0 auto;
background: papayawhip;
}
<div id="main"></div>
[3] Dynamically Position any number of divs on an Ellipse/Circle
The equation for a co-ordinate on an ellipse is:
(x, y) = (rx * cos(θ), ry * sin(θ))
where, rx is the radius along X-axis and ry is the radius along Y-axis.
In this case, the function generate(n, rx, ry, id) takes four arguments, where n is the number of divs, rx and ry are the radii along the X and Y-axis respectively and finally id is the id of the div that you want to append your elliptically arranged divs in.
Demo on Fiddle
var theta = [];
var setup = function(n, rx, ry, id) {
var main = document.getElementById(id);
var mainHeight = parseInt(window.getComputedStyle(main).height.slice(0, -2));
var circleArray = [];
var colors = ['red', 'green', 'purple', 'black', 'orange', 'yellow', 'maroon', 'grey', 'lightblue', 'tomato', 'pink', 'maroon', 'cyan', 'magenta', 'blue', 'chocolate', 'darkslateblue', 'coral', 'blueviolet', 'burlywood', 'cornflowerblue', 'crimson', 'darkgoldenrod', 'olive', 'sienna', 'red', 'green', 'purple', 'black', 'orange', 'yellow', 'maroon', 'grey', 'lightblue', 'tomato', 'pink', 'maroon', 'cyan', 'magenta', 'blue', 'chocolate', 'darkslateblue', 'coral', 'blueviolet', 'burlywood', 'cornflowerblue', 'crimson', 'darkgoldenrod', 'olive', 'sienna'];
for (var i = 0; i < n; i++) {
var circle = document.createElement('div');
circle.className = 'circle number' + i;
circleArray.push(circle);
circleArray[i].posx = Math.round(rx * (Math.cos(theta[i]))) + 'px';
circleArray[i].posy = Math.round(ry * (Math.sin(theta[i]))) + 'px';
circleArray[i].style.position = "absolute";
circleArray[i].style.backgroundColor = colors[i];
circleArray[i].style.top = ((mainHeight / 2) - parseInt(circleArray[i].posy.slice(0, -2))) + 'px';
circleArray[i].style.left = ((mainHeight / 2) + parseInt(circleArray[i].posx.slice(0, -2))) + 'px';
main.appendChild(circleArray[i]);
}
};
var generate = function(n, rx, ry, id) {
var frags = 360 / n;
for (var i = 0; i <= n; i++) {
theta.push((frags / 180) * i * Math.PI);
}
setup(n, rx, ry, id)
}
generate(16, 150, 75, 'main');
div#main {
height: 300px;
width: 300px;
position: absolute;
margin: 0 auto;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
}
div.circle {
position: absolute;
width: 20px;
height: 20px;
border: 2px solid black;
border-radius: 50%;
}
body {
margin: 0 auto;
background: papayawhip;
}
<div id="main"></div>
Edit[9th December 2015]:
Here's a more flexible version with start offset, clock wise and anti-clock wise functionality.
/*
Usage: Position.ellipse(n, rx, ry, so, wh, idd, cls, cw);
where n = number of divs,
rx = radius along X-axis,
ry = radius along Y-axis,
so = startOffset,
wh = width/height of divs,
idd = id of main div(ellipse),
cls = className of divs;
cw = clockwise(true/false)
*/
var Position = {
ellipse: function(n, rx, ry, so, wh, idd, cls, cw) {
var m = document.createElement('div'),
ss = document.styleSheets;
ss[0].insertRule('#' + idd + ' { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); border-radius: 50%; box-shadow: inset 0 0 ' + wh + 'px ' + wh / 4 + 'px black; background: rgba(0, 0, 0, 0.2); width: ' + String((rx * 2) + wh) + 'px; height: ' + String((ry * 2) + wh) + 'px; }', 1);
ss[0].insertRule('.' + cls + '{ position: absolute; background: black; color: papayawhip; text-align: center; font-family: "Open Sans Condensed", sans-serif; border-radius: 50%; transition: transform 0.2s ease; width: ' + wh + 'px; height: ' + wh + 'px; line-height: ' + wh + 'px;}', 1);
ss[0].insertRule('.' + cls + ':hover { transform: scale(1.2); cursor: pointer; background: rgba(0, 0, 0, 0.8); }', 1);
m.id = idd;
for (var i = 0; i < n; i++) {
var c = document.createElement('div');
c.className = cls;
c.innerHTML = i + 1;
c.style.top = String(ry + -ry * Math.cos((360 / n / 180) * (i + so) * Math.PI)) + 'px';
c.style.left = String(rx + rx * (cw ? Math.sin((360 / n / 180) * (i + so) * Math.PI) : -Math.sin((360 / n / 180) * (i + so) * Math.PI))) + 'px';
m.appendChild(c);
}
document.body.appendChild(m);
}
}
Position.ellipse(20, 150, 150, 0, 42, 'main', 'circle', true);
#import url(http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300);
body {
margin: 0 auto;
background: rgb(198, 193, 173);
}

Other approach without JS
chipChocolate.py's anser is pretty complete but there is an other way to achieve your aim. It is simpler and doesn't require JS.
The point is to think "circle" and rotation rather than rely on [x,y] coordinates :
You need to nest all the elements and apply a rotation to them. As they are nested the n + 1 element will rotate according to it's direct parent's rotation. Here is a DEMO :
.circle, .circle div {
width:24px; height:300px;
position:absolute;
left:50%; top:50px;
}
.circle:before, .circle div:before {
content:'';
display:block;
width:20px; height:20px;
border: 2px solid black;
border-radius: 100%;
}
.circle div {
top:0; left:0;
-webkit-transform : rotate(24deg);
-ms-transform : rotate(24deg);
transform : rotate(24deg);
}
<div class="circle">
<div><div><div><div><div><div><div><div><div><div><div><div><div><div><div>
</div></div></div></div></div></div></div></div></div></div></div></div></div></div></div>
</div>
The diameter of the circle is controled by the height of the elements (in the demo height:300px) you can make that a percentage to make the circle responsive (see below).
The rotation must be set according to the number of elements you want around the circle. In the demo 15 elements so rotation = 360 / 15 = 24deg.
If you have a dynamic number of elements, you may use JS to add them and to calculate the rotation angle needed.
Responsive example
DEMO
.circle{
position:relative;
width:5%;padding-bottom:50%;
margin-left:47.5%;
}
.circle div {
position:absolute;
top:0; left:0;
width:100%; height:100%;
-webkit-transform : rotate(24deg);
-ms-transform : rotate(24deg);
transform : rotate(24deg);
}
.circle:before, .circle div:before {
content:'';
position:absolute;
top:0; left:0;
width:100%; padding-bottom:100%;
border-radius: 100%;
border: 2px solid teal;
background:gold;
}
<div class="circle">
<div><div><div><div><div><div><div><div><div><div><div><div><div><div><div>
</div></div></div></div></div></div></div></div></div></div></div></div></div></div></div>
</div>

Yet another solution, based on ideas from other solutions I've seen
http://jsfiddle.net/0hr1n7a2/6/
(function() {
var radians, radius;
radius = 150;
var totalItems = 48
var item = 0;
function positionTarget()
{
var x, y, angle = 0, step = (2*Math.PI) / totalItems;
var width = $('#container').width()/2;
var height = $('#container').height()/2;
var itemW = 20, itemH = 2;
var deg = 0;
while(item <= totalItems)
{
x = Math.round(width + radius * Math.cos(angle) - itemW/2);
y = Math.round(height + radius * Math.sin(angle) - itemH/2);
//console.log(x + "," + y);
$('#container').append('<div id="'+ item +'"/>')
$('div#'+item).css('position', 'absolute')
.css('width', itemW+'px').css('height', itemH+'px')
.css('left', x+'px').css('top', y+'px')
.css('background-color', 'blue')
.css('transform-origin', x+'px' -y+'px')
.css('transform', 'rotate('+ deg +'deg)')
.css('border', 'solid 1px #000');
angle += step;
++item;
deg += 360/totalItems;
//console.log(deg)
}
}
$('#theButton').on('click', function()
{
positionTarget();
})
})();
#container { width: 600px; height: 600px; border: 1px solid #000; position: relative; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="theButton" value="Draw">
<div id="container">
</div>

Set the position to "absolute". This will allow "top" and "left" to position the divs from (0, 0). Using "relative" will position the divs from where they would normally be laid out.
Change the center point of your circle from (0, 0) to something else, like (250, 250).
circleArray[i].posx = 250 + Math.round((150*Math.cos(i*(2*Math.PI/15)))) + 'px';
circleArray[i].posy = 250 + Math.round((150*Math.sin(i*(2*Math.PI/15)))) + 'px';
circleArray[i].style.position = "absolute";

Related

Detect circle overlap

I'm trying to trigger a hover function when ANY part of a fake cursor hovers over a circle.
I have played around with the X and Y positions of the fake cursor, but that only works well for one direction. Is there a smarter way to go about this?
Here's a pen showing what I'm trying to do: trigger a hover function when any part of the pink circle (fake cursor) touches the green circle.
https://codepen.io/Jessels/pen/LYPxmqx
$('.cursor')
.eq(0)
.css({
left: e.pageX - 20,
top: e.pageY - 5
});
You can add this to your mousemove event.
Here we are finding the intersections and if the "cursor" is within the circle.
Here is where I found this code: Fiddle
Here is my CodePen Demo
$(document).mousemove(function(e) {
$('.cursor').eq(0).css({
left: e.pageX - 25,
top: e.pageY - 20
});
// circles
var c1 = $('.cursor');
var c2 = $('.circle');
// radius
var d1 = c1.outerWidth(true) / 2;
var d2 = c2.outerWidth(true) / 2;
// center of first circle
var x1 = c1.offset().left + c1.width() / 2;
var y1 = c1.offset().top + c1.height() / 2;
// center of second circle
var x2 = c2.offset().left + c2.width() / 2;
var y2 = c2.offset().top + c2.height() / 2;
function calc() {
var a = d2;
var b = d1;
var c = Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
var d = (b * b + c * c - a * a) / (2 * c);
var h = Math.sqrt((b * b) - (d * d));
if (d < 0 || $.isNumeric(h)) {
c2.css('background', 'blue');
} else {
c2.css('background', 'green');
}
}
calc();
});
.cursor {
height: 50px;
width: 50px;
border-radius: 50%;
position: absolute;
pointer-events: none;
z-index: 999;
background: hotpink;
}
.circle {
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cursor"></div>
<div class="circle">
<div class="inter1 inter"></div>
<div class="inter2 inter"></div>
<div>

How to change radius of circles but keep pattern?

I found some code online to draw circles around a center circle. How do I change the radius of the smaller circles without affecting the layout (currently all the circles shift and are not centered around the large circle anymore).
This happens when I change the radius(width & height) in the css file. Changing the large circle radius also causes the whole group of circles to shift right or left (although they maintain their symmetry).
Here is my code:
var div = 360 / 6;
var radius = 150;
var parentdiv = document.getElementById('parentdiv');
var offsetToParentCenter = parseInt(parentdiv.offsetWidth / 2); //assumes parent is square
var offsetToChildCenter = 20;
var totalOffset = offsetToParentCenter - offsetToChildCenter;
for (var i = 1; i <= 6; ++i) {
var childdiv = document.createElement('div');
childdiv.className = 'div2';
childdiv.style.position = 'absolute';
var y = Math.sin((div * i) * (Math.PI / 180)) * radius;
var x = Math.cos((div * i) * (Math.PI / 180)) * radius;
childdiv.style.top = (y + totalOffset).toString() + "px";
childdiv.style.left = (x + totalOffset).toString() + "px";
parentdiv.appendChild(childdiv);
}
#parentdiv {
position: relative;
width: 150px;
height: 150px;
background-color: red;
border-radius: 150px;
margin: 150px;
}
.div2 {
position: absolute;
width: 40px;
height: 40px;
background-color: red;
border-radius: 100px;
}
<div id="parentdiv"></div>
I would also like to move the circles to the center of the screen but I am not sure how.
I am very new to html/css/js and any help would be greatly appreciated!
To illustrate my comment. border-radius is a CSS rule to round boxe's corners.
https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius
The border-radius CSS property rounds the corners of an element's outer border edge. You can set a single radius to make circular corners, or two radii to make elliptical corners.
to modify the size , you can do it from the css file too, about the position , there is two vars to update : radius and offsetToChildCenter
Demo
var div = 360 / 6;
var radius = 180;
var parentdiv = document.getElementById('parentdiv');
var offsetToParentCenter = parseInt(parentdiv.offsetWidth / 2); //assumes parent is square
var offsetToChildCenter = 40;
var totalOffset = offsetToParentCenter - offsetToChildCenter;
for (var i = 1; i <= 6; ++i) {
var childdiv = document.createElement('div');
childdiv.className = 'div2';
childdiv.style.position = 'absolute';
var y = Math.sin((div * i) * (Math.PI / 180)) * radius;
var x = Math.cos((div * i) * (Math.PI / 180)) * radius;
childdiv.style.top = (y + totalOffset).toString() + "px";
childdiv.style.left = (x + totalOffset).toString() + "px";
parentdiv.appendChild(childdiv);
}
html {
display: flex;
height: 100%;
}
body {
margin: auto;
}
#parentdiv {
position: relative;
width: 150px;
height: 150px;
background-color: red;
border-radius: 150px;
margin: 150px;
}
.div2 {
position: absolute;
width: 80px;
height: 80px;
background-color: red;
border-radius: 10px;
}
<div id="parentdiv"></div>
You can center the circles by applying Flexbox to the parent circle's parent element. In my case, the parent element is <body>.
/* Apply Flexbox and use justify-content to
center parent circle horizontally. */
body {
width: 100vw;
display: flex;
justify-content: center;
}
To adjust the diameter of the smaller circles, you would have to remove the width and height properties in your .div2 selector and let Javascript calculate and set the width and height.
var parentdiv = document.getElementById('parentdiv');
var div = 360 / 6;
var radius = 150;
var offsetToChildCenter = 50; // Change me!
var offsetToParentCenter = parseInt(parentdiv.offsetWidth / 2); //assumes parent is square
var totalOffset = offsetToParentCenter - offsetToChildCenter;
for (var i = 1; i <= 6; ++i) {
var childdiv = document.createElement('div');
childdiv.className = 'div2';
childdiv.style.position = 'absolute';
var y = Math.sin((div * i) * (Math.PI / 180)) * radius;
var x = Math.cos((div * i) * (Math.PI / 180)) * radius;
childdiv.style.top = (y + totalOffset).toString() + "px";
childdiv.style.left = (x + totalOffset).toString() + "px";
// Let your JS code calculate the width and height
childdiv.style.width = `${offsetToChildCenter * 2}px`
childdiv.style.height = `${offsetToChildCenter * 2}px`
parentdiv.appendChild(childdiv);
}
body {
width: 100vw;
display: flex;
justify-content: center;
}
#parentdiv {
position: relative;
width: 150px;
height: 150px;
background-color: red;
margin: 150px;
/* Use 50% to ensure the element will always be a circle. */
border-radius: 50%;
}
.div2 {
position: absolute;
/* Remove width and height from CSS */
/* width: 40px; */
/* height: 40px; */
background-color: red;
/* Use 50% to ensure the element will always be a circle. */
border-radius: 50%;
}
<div id="parentdiv"></div>

Error: <tspan> attribute dy: Expected length, "NaN" - Raphael.js

I've got a lot of errors when hiding/showing object made in raphael.
I have a house made with raphael - when button clicked a gauge is shown and animating, if you click again the house is showing and animating again (function running over and over again when clicking)
This function is showing on phone, on normal desktop the function isn't used. So therefor I can't just put the function on the button.
BUT! I got a lot of errors when doing it.
Made a fiddle showing it. See it here.
Full js code here:
pv = 80;
pointerv = Math.round(pv);
onload = function() {
$(function dogauge() {
var Needle, arc, arcEndRad, arcStartRad, barWidth, chart, chartInset, degToRad, el, endPadRad, height, i, margin, needle, numSections, padRad, percToDeg, percToRad, percent, radius, ref, sectionIndx, sectionPerc, startPadRad, svg, totalPercent, width;
percent = pointerv/100;
barWidth = 40;
numSections = 3;
// / 2 for HALF circle
sectionPerc = 1 / numSections / 2;
padRad = 0.05;
chartInset = 10;
// start at 270deg
totalPercent = .75;
el = d3.select('.chart-gauge');
margin = {
top: 20,
right: 20,
bottom: 30,
left: 20
};
width = el[0][0].offsetWidth - margin.left - margin.right;
height = width;
radius = Math.min(width, height) / 2;
percToDeg = function(perc) {
return perc * 360;
};
percToRad = function(perc) {
return degToRad(percToDeg(perc));
};
degToRad = function(deg) {
return deg * Math.PI / 180;
};
svg = el.append('svg').attr('width', width + margin.left + margin.right).attr('height', height + margin.top + margin.bottom);
chart = svg.append('g').attr('transform', `translate(${(width + margin.left) / 2}, ${(height + margin.top) / 2})`);
// build gauge bg
for (sectionIndx = i = 1, ref = numSections; (1 <= ref ? i <= ref : i >= ref); sectionIndx = 1 <= ref ? ++i : --i) {
arcStartRad = percToRad(totalPercent);
arcEndRad = arcStartRad + percToRad(sectionPerc);
totalPercent += sectionPerc;
startPadRad = sectionIndx === 0 ? 0 : padRad / 2;
endPadRad = sectionIndx === numSections ? 0 : padRad / 2;
arc = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth).startAngle(arcStartRad + startPadRad).endAngle(arcEndRad - endPadRad);
chart.append('path').attr('class', `arc chart-color${sectionIndx}`).attr('d', arc);
}
Needle = class Needle {
constructor(len, radius1) {
this.len = len;
this.radius = radius1;
}
drawOn(el, perc) {
el.append('circle').attr('class', 'needle-center').attr('cx', 0).attr('cy', 0).attr('r', this.radius);
return el.append('path').attr('class', 'needle').attr('d', this.mkCmd(perc));
}
animateOn(el, perc) {
var self;
self = this;
return el.transition().delay(500).ease('elastic').duration(3000).selectAll('.needle').tween('progress', function() {
return function(percentOfPercent) {
var progress;
progress = percentOfPercent * perc;
return d3.select(this).attr('d', self.mkCmd(progress));
};
});
}
mkCmd(perc) {
var centerX, centerY, leftX, leftY, rightX, rightY, thetaRad, topX, topY;
thetaRad = percToRad(perc / 2); // half circle
centerX = 0;
centerY = 0;
topX = centerX - this.len * Math.cos(thetaRad);
topY = centerY - this.len * Math.sin(thetaRad);
leftX = centerX - this.radius * Math.cos(thetaRad - Math.PI / 2);
leftY = centerY - this.radius * Math.sin(thetaRad - Math.PI / 2);
rightX = centerX - this.radius * Math.cos(thetaRad + Math.PI / 2);
rightY = centerY - this.radius * Math.sin(thetaRad + Math.PI / 2);
return `M ${leftX} ${leftY} L ${topX} ${topY} L ${rightX} ${rightY}`;
}
};
needle = new Needle(90, 15);
needle.drawOn(chart, 0);
needle.animateOn(chart, percent);
});
$(function dohouse() {
var paper = Raphael("frivardihouse", 250, 260);
paper.customAttributes.step = function (s) {
var len = this.orbit.getTotalLength();
var point = this.orbit.getPointAtLength(s * len);
return {
transform: "t" + [point.x, point.y] + "r" + point.alpha
};
};
var bghouse = paper.path("M236.5,80.4L128.9,2.1c-1.6-1.1-3.7-1.1-5.3,0L16.1,80.4c-3.5,2.6-1.7,8.1,2.6,8.1l13,0c-1,2.5-1.5,5.3-1.5,8.2l0,122.7c0,12,9.2,21.7,20.6,21.7l150.9,0c11.4,0,20.6-9.7,20.6-21.7l0-122.7c0-2.9-0.5-5.7-1.5-8.2h13C238.2,88.6,240,83,236.5,80.4z").attr({fill: "#cccccc", stroke: "none"});
bghouse.glow({
width:10,
fill:true,
offsetx :0,
offsety:3,
color:'#bfbfbf'
}
);
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
}
function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
let ltv = (100 - 80)/100;
/*let vardi = <?=$graph->CurrentPropValue?>;
let boligvardi = "Boligværdi " + formatNumber(vardi);
let boligvardilink = boligvardi.link("https://realkreditkonsulenten.dk/kundeportal/?page=property");*/
let equity = 20;
let h = 144*ltv;
let y = 86+((1-ltv)*144);
let EqText = formatNumber (equity);
let ltvtxt = round(ltv * 100);
var green = "#59ba41";
var darkgreen = "#1a7266";
var yellow = "#fbb732";
var red = "#c80000";
var finalfillcolor = green;
if (ltv > 0.6) {
finalfillcolor = darkgreen;
}
if (ltv > 0.82) {
finalfillcolor = yellow;
}
if (ltv > 0.95) {
finalfillcolor = red;
}
if (ltv > 1) {
h = 144;
y= 88;
}
var fillhouse = paper.rect(40.5,230,172.3,0).attr({fill: green, stroke: "none"});
/*skal hides hvis function mus kører*/
var sAnimation = Raphael.animation({ 'width': 172.3, 'height': h, 'x': 40.5, 'y': y, fill: finalfillcolor}, 2000, "backOut")
fillhouse.animate(sAnimation);
var thehouse = paper.path("M236.5,80.4L128.9,2.1c-1.6-1.1-3.7-1.1-5.3,0L16.1,80.4c-3.5,2.6-1.7,8.1,2.6,8.1l13,0c-1,2.5-1.5,5.3-1.5,8.2l0,122.7c0,12,9.2,21.7,20.6,21.7l150.9,0c11.4,0,20.6-9.7,20.6-21.7l0-122.7c0-2.9-0.5-5.7-1.5-8.2h13C238.2,88.6,240,83,236.5,80.4z M206.7,104.9l0,106.5c0,9-6.9,16.3-15.5,16.3l-129.9,0c-8.5,0-15.5-7.3-15.5-16.3l0-106.5c0-9,6.9-16.3,15.5-16.3l129.9,0C199.8,88.6,206.7,95.9,206.7,104.9z").attr({fill: "#ffffff", stroke: "none"});
var txtbelaning = paper.text(126.8,198, "BELÅNING").attr({"font-family": "Open sans", "font-weight":"700", "font-size": 20, "transform": "matrix(1 0 0 1 79.455 216.7752)", "fill":"#ffffff"});
/*var housevalue = paper.text(126.8,210, boligvardi).attr({"font-family": "Open sans", "font-weight":"400", "font-size": 13, "fill":"#ffffff"});*/
paper.customAttributes.txtprc = function (txtprc) {
return {
txtprc: [txtprc],
text: Math.floor(txtprc) +"%" + '\n'
}
}
var txtprc = paper
.text(126.1,158.2)
.attr({
"font-size": 48,
"fill": "#ffffff",
"font-family":"Open sans",
"font-weight":"700",
txtprc: [0,1000]
})
txtprc.animate({
txtprc: [ltvtxt, 1000]
}, 2000, "easeInOut")
var txtfrivardi = paper.text(126.8,42.1, "FRIVÆRDI").attr({"font-family": "Open sans", "font-weight":"600", "font-size": 12, "transform": "matrix(1 0 0 1 98.6264 51.0823)", "fill":"#585857"});
paper.customAttributes.txtfrivardival = function (txtfrivardival) {
return {
txtfrivardival: [txtfrivardival],
text: formatNumber(Math.floor(txtfrivardival)) + '\n'
}
}
var txtfrivardival = paper
.text(126.2,61.3)
.attr({
"font-size": 20,
"fill": "#585857",
"font-family":"Open sans",
"font-weight":"700",
txtfrivardival: [0,1000]
})
txtfrivardival.animate({
txtfrivardival: [equity, 1000]
}, 2000, "easeInOut")
});
};
$("#segaugeknap").click(function() {
if($(this).text()=== "OVERVÅGNINGSBAROMETER"){
$(this).text("TILBAGE");
document.getElementById('chart-gauge').innerHTML = '';
onload();
}
else{
$(this).text("OVERVÅGNINGSBAROMETER");
}
$('#frivardihouse, #housevalue_f, #gaugebox').slideToggle('slow');
document.getElementById('frivardihouse').innerHTML = '';
onload();
});
to get rid of the multiple houses and visible multiple gauges
$("#segaugeknap").click(function() {
if($(this).text()=== "OVERVÅGNINGSBAROMETER"){
$(this).text("TILBAGE");
document.getElementById('chart-gauge').innerHTML = '';
onload();
} else{
$(this).text("OVERVÅGNINGSBAROMETER");
document.getElementById('frivardihouse').innerHTML = '';
onload();
}
$('#frivardihouse, #housevalue_f, #gaugebox').slideToggle('slow');
});
You still have multiple gauges when house is shown.
tspan errors only happen when animation is still going. With above modification it only happens when gauge is still animating.
You shouldn't start drawing the 2 svg each time you click the bottun
So first step is to seperate the 2 drawing function and remove the onload wrapper function.
Then when you click on the guage button is to wait until the slide animation complete so we can calculate the width and height for the guage container Div after that is to draw the gauge and same for the house.
Please check the following jsfiddle i've forked yours and do the changes hope it's clear for you.
Check the fiddle https://jsfiddle.net/tb1k5sgc/
pv = 80;
pointerv = Math.round(pv);
function dogauge() {
var Needle, arc, arcEndRad, arcStartRad, barWidth, chart, chartInset, degToRad, el, endPadRad, height, i, margin, needle, numSections, padRad, percToDeg, percToRad, percent, radius, ref, sectionIndx, sectionPerc, startPadRad, svg, totalPercent, width;
percent = pointerv/100;
barWidth = 40;
numSections = 3;
// / 2 for HALF circle
sectionPerc = 1 / numSections / 2;
padRad = 0.05;
chartInset = 10;
// start at 270deg
totalPercent = .75;
el = d3.select('.chart-gauge');
margin = {
top: 20,
right: 20,
bottom: 30,
left: 20
};
width = el[0][0].offsetWidth - margin.left - margin.right;
height = width;
radius = Math.min(width, height) / 2;
percToDeg = function(perc) {
return perc * 360;
};
percToRad = function(perc) {
return degToRad(percToDeg(perc));
};
degToRad = function(deg) {
return deg * Math.PI / 180;
};
svg = el.append('svg').attr('width', width + margin.left + margin.right).attr('height', height + margin.top + margin.bottom);
chart = svg.append('g').attr('transform', `translate(${(width + margin.left) / 2}, ${(height + margin.top) / 2})`);
// build gauge bg
for (sectionIndx = i = 1, ref = numSections; (1 <= ref ? i <= ref : i >= ref); sectionIndx = 1 <= ref ? ++i : --i) {
arcStartRad = percToRad(totalPercent);
arcEndRad = arcStartRad + percToRad(sectionPerc);
totalPercent += sectionPerc;
startPadRad = sectionIndx === 0 ? 0 : padRad / 2;
endPadRad = sectionIndx === numSections ? 0 : padRad / 2;
arc = d3.svg.arc().outerRadius(radius - chartInset).innerRadius(radius - chartInset - barWidth).startAngle(arcStartRad + startPadRad).endAngle(arcEndRad - endPadRad);
chart.append('path').attr('class', `arc chart-color${sectionIndx}`).attr('d', arc);
}
Needle = class Needle {
constructor(len, radius1) {
this.len = len;
this.radius = radius1;
}
drawOn(el, perc) {
el.append('circle').attr('class', 'needle-center').attr('cx', 0).attr('cy', 0).attr('r', this.radius);
return el.append('path').attr('class', 'needle').attr('d', this.mkCmd(perc));
}
animateOn(el, perc) {
var self;
self = this;
return el.transition().delay(500).ease('elastic').duration(3000).selectAll('.needle').tween('progress', function() {
return function(percentOfPercent) {
var progress;
progress = percentOfPercent * perc;
return d3.select(this).attr('d', self.mkCmd(progress));
};
});
}
mkCmd(perc) {
var centerX, centerY, leftX, leftY, rightX, rightY, thetaRad, topX, topY;
thetaRad = percToRad(perc / 2); // half circle
centerX = 0;
centerY = 0;
topX = centerX - this.len * Math.cos(thetaRad);
topY = centerY - this.len * Math.sin(thetaRad);
leftX = centerX - this.radius * Math.cos(thetaRad - Math.PI / 2);
leftY = centerY - this.radius * Math.sin(thetaRad - Math.PI / 2);
rightX = centerX - this.radius * Math.cos(thetaRad + Math.PI / 2);
rightY = centerY - this.radius * Math.sin(thetaRad + Math.PI / 2);
return `M ${leftX} ${leftY} L ${topX} ${topY} L ${rightX} ${rightY}`;
}
};
needle = new Needle(90, 15);
needle.drawOn(chart, 0);
needle.animateOn(chart, percent);
};
function dohouse() {
var paper = Raphael("frivardihouse", 250, 260);
paper.customAttributes.step = function (s) {
var len = this.orbit.getTotalLength();
var point = this.orbit.getPointAtLength(s * len);
return {
transform: "t" + [point.x, point.y] + "r" + point.alpha
};
};
var bghouse = paper.path("M236.5,80.4L128.9,2.1c-1.6-1.1-3.7-1.1-5.3,0L16.1,80.4c-3.5,2.6-1.7,8.1,2.6,8.1l13,0c-1,2.5-1.5,5.3-1.5,8.2l0,122.7c0,12,9.2,21.7,20.6,21.7l150.9,0c11.4,0,20.6-9.7,20.6-21.7l0-122.7c0-2.9-0.5-5.7-1.5-8.2h13C238.2,88.6,240,83,236.5,80.4z").attr({fill: "#cccccc", stroke: "none"});
bghouse.glow({
width:10,
fill:true,
offsetx :0,
offsety:3,
color:'#bfbfbf'
}
);
function formatNumber(num) {
return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1.')
}
function round(value, precision) {
var multiplier = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
let ltv = (100 - 80)/100;
/*let vardi = <?=$graph->CurrentPropValue?>;
let boligvardi = "Boligværdi " + formatNumber(vardi);
let boligvardilink = boligvardi.link("https://realkreditkonsulenten.dk/kundeportal/?page=property");*/
let equity = 20;
let h = 144*ltv;
let y = 86+((1-ltv)*144);
let EqText = formatNumber (equity);
let ltvtxt = round(ltv * 100);
var green = "#59ba41";
var darkgreen = "#1a7266";
var yellow = "#fbb732";
var red = "#c80000";
var finalfillcolor = green;
if (ltv > 0.6) {
finalfillcolor = darkgreen;
}
if (ltv > 0.82) {
finalfillcolor = yellow;
}
if (ltv > 0.95) {
finalfillcolor = red;
}
if (ltv > 1) {
h = 144;
y= 88;
}
var fillhouse = paper.rect(40.5,230,172.3,0).attr({fill: green, stroke: "none"});
/*skal hides hvis function mus kører*/
var sAnimation = Raphael.animation({ 'width': 172.3, 'height': h, 'x': 40.5, 'y': y, fill: finalfillcolor}, 2000, "backOut")
fillhouse.animate(sAnimation);
var thehouse = paper.path("M236.5,80.4L128.9,2.1c-1.6-1.1-3.7-1.1-5.3,0L16.1,80.4c-3.5,2.6-1.7,8.1,2.6,8.1l13,0c-1,2.5-1.5,5.3-1.5,8.2l0,122.7c0,12,9.2,21.7,20.6,21.7l150.9,0c11.4,0,20.6-9.7,20.6-21.7l0-122.7c0-2.9-0.5-5.7-1.5-8.2h13C238.2,88.6,240,83,236.5,80.4z M206.7,104.9l0,106.5c0,9-6.9,16.3-15.5,16.3l-129.9,0c-8.5,0-15.5-7.3-15.5-16.3l0-106.5c0-9,6.9-16.3,15.5-16.3l129.9,0C199.8,88.6,206.7,95.9,206.7,104.9z").attr({fill: "#ffffff", stroke: "none"});
var txtbelaning = paper.text(126.8,198, "BELÅNING").attr({"font-family": "Open sans", "font-weight":"700", "font-size": 20, "transform": "matrix(1 0 0 1 79.455 216.7752)", "fill":"#ffffff"});
/*var housevalue = paper.text(126.8,210, boligvardi).attr({"font-family": "Open sans", "font-weight":"400", "font-size": 13, "fill":"#ffffff"});*/
paper.customAttributes.txtprc = function (txtprc) {
return {
txtprc: [txtprc],
text: Math.floor(txtprc) +"%" + '\n'
}
}
var txtprc = paper
.text(126.1,158.2)
.attr({
"font-size": 48,
"fill": "#ffffff",
"font-family":"Open sans",
"font-weight":"700",
txtprc: [0,1000]
})
txtprc.animate({
txtprc: [ltvtxt, 1000]
}, 2000, "easeInOut")
var txtfrivardi = paper.text(126.8,42.1, "FRIVÆRDI").attr({"font-family": "Open sans", "font-weight":"600", "font-size": 12, "transform": "matrix(1 0 0 1 98.6264 51.0823)", "fill":"#585857"});
paper.customAttributes.txtfrivardival = function (txtfrivardival) {
return {
txtfrivardival: [txtfrivardival],
text: formatNumber(Math.floor(txtfrivardival)) + '\n'
}
}
var txtfrivardival = paper
.text(126.2,61.3)
.attr({
"font-size": 20,
"fill": "#585857",
"font-family":"Open sans",
"font-weight":"700",
txtfrivardival: [0,1000]
})
txtfrivardival.animate({
txtfrivardival: [equity, 1000]
}, 2000, "easeInOut")
};
$("#segaugeknap").click(function() {
$('#frivardihouse, #gaugebox').slideToggle(400);
if($(this).text()=== "OVERVÅGNINGSBAROMETER"){
$(this).text("TILBAGE");
document.getElementById('chart-gauge').innerHTML = '';
setTimeout(dogauge, 401);
}
else{
$(this).text("OVERVÅGNINGSBAROMETER");
document.getElementById('frivardihouse').innerHTML = '';
setTimeout(dohouse, 401);
}
});
$(document).ready(function(){
dohouse();
})
.chart-gauge {
width: 100%;
height: 180px;
margin-left: 10px;
}
.chart-color1 {
fill: rgb(200,0,0);
}
.chart-color2 {
fill: rgb(251, 183, 50);
}
.chart-color3 {
fill: rgb(89, 186, 65);;
}
.needle,
.needle-center {
fill: #464A4F;
}
.prose {
text-align: center;
font-family: sans-serif;
color: #ababab;
}
.gaugebox {display: none; border-radius: 0px 0px 5px 5px !important;margin-top: -10px !important;padding: 0px 10px 20px 10px !important;}
#segauge {background-color:#000;color:#fff;width:300px;margin: 0 auto;text-align:center;padding:10px;}
.gaugebox h4 {text-align: center;font-weight: 700;margin-bottom: 0px;}
.gaugebox .gaugetxt span:first-child(){float: left;}
.gaugebox .gaugetxt span:nth-child(2){float: right;}
.gaugetxt {width: 360px; margin: 0 auto;}
.gaugefullwrapper {
background: #fff;
border-radius: 10px;
width: 380px;
margin: 0 auto;
padding-bottom: 10px;
box-shadow: 0px 4px 15px rgba(0,0,0,0.2);
}
.gaugewrapper {margin: 0 auto; width: 350px }
div#gauge {
width: 80%;height: 180px;margin: 0 auto;
}
/*hus*/
div#frivardihouse svg {
margin: 0 auto;
display: block;
padding-top: 10px;
transition: all 0.6s cubic-bezier(.87,-.41,.19,1.44)
}
div#frivardihouse svg:hover {transform: scale(1.04);
}
div#frivardihouse {
margin-top: -20px;
}
.housevalue_f {text-align: center;padding-bottom: 10px;}
.housevalue_f a span {color: #17aec6;}
.housevalue_f a {color: #666666;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.3.3/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.2.7/raphael.min.js"></script>
<div class="housegauge">
<div class="graphs house">
<div id="frivardihouse"></div>
<div class="w-btn-wrapper align_center" id="segauge"><span id="segaugeknap" class="w-btn style_solid size_medium color_primary icon_none">OVERVÅGNINGSBAROMETER</span></div>
</div>
<div class="gaugebox" id="gaugebox">
<div class="gaugefullwrapper">
<div class="gaugewrapper">
<div id="chart-gauge" class="chart-gauge"></div>
</div>
<div class="gaugetxt">
<span>Langt fra omlægning</span><span>Tæt på omlægning</span>
</div>
</div>
</div>
</div>

circle progressbar doesn't start from the middle

I have a circular progress bar that must start from 0 degree - middle of a top part of the circle. But I've noticed that it starts not in the middle, but a little to the left. How do I fix that?
Here's the code:
var bar = document.getElementById('progressbar'),
createProgressBar = function(bar) {
var options = {
start: 0,
width: bar.getAttribute('data-width'),
height: bar.getAttribute('data-height'),
percent: 90,
lineWidth: bar.getAttribute('data-linewidth')
},
canvas = document.createElement('canvas'),
paper = canvas.getContext('2d'),
span = document.createElement('span'),
radius = (options.width - options.lineWidth) / 2,
color = paper.createLinearGradient(0, 0, options.width, 0),
step = 1.5;
span.style.width = bar.style.width = options.width + 'px';
span.style.height = bar.style.height = options.height + 'px';
canvas.width = options.width;
canvas.height = options.height;
span.style.lineHeight = options.height + 'px';
color.addColorStop(0, "red");
color.addColorStop(0.5, "red");
color.addColorStop(1.0, "red");
bar.appendChild(span);
bar.appendChild(canvas);
(function animat() {
span.textContent = options.start + '%';
createCircle(options, paper, radius, color, Math.PI * 1.5, Math.PI * step);
console.log(step);
options.start++;
step += 0.02;
if (options.start <= options.percent) {
setTimeout(animat, 10);
}
})();
},
createCircle = function(options, paper, radius, color, start, end) {
paper.clearRect(
options.width / 2 - radius - options.lineWidth,
options.height / 2 - radius - options.lineWidth,
radius * 2 + (options.lineWidth * 2),
radius * 2 + (options.lineWidth * 2)
);
paper.beginPath();
paper.arc(options.width / 2, options.height / 2, radius, 0, Math.PI * 2, false);
paper.strokeStyle = '#dbd7d2';
paper.lineCap = 'round';
paper.lineWidth = options.lineWidth;
paper.stroke();
paper.closePath();
paper.beginPath();
paper.arc(options.width / 2, options.height / 2, radius, start, end, false);
paper.strokeStyle = color;
paper.lineCap = 'square';
paper.lineWidth = options.lineWidth;
paper.stroke();
paper.closePath();
};
createProgressBar(bar);
#progressbar {
position: fixed;
top: 50%;
left: 50%;
margin-top: -150px;
margin-left: -150px;
}
canvas {
position: absolute;
display: block;
left: 0;
top: 0
}
span {
display: block;
color: #222;
text-align: center;
font-family: "sans serif", tahoma, Verdana, helvetica;
font-size: 30px
}
<div id="progressbar" data-width="320" data-height="320" data-linewidth="16"></div>
That's what the progress bar looks like: https://jsfiddle.net/ue20b8bd/
P.S. I've modified the code from github: https://github.com/su-ning/html5-circle-progressbar
The problem was with the lineCap property. Using 'butt' as a lineCap fixed the problem!

How to set a script as Background of a concrete <section>?

I am using Bootstrap for a one-page website project. This website is divided in 4 parts, each one inside a 'section' with its own background color/image and content.
For one of these sections (the first one), which occupies the whole screen and has a 'Navbar' at the top and some headers inside, I would like to set a script as the background and not a simple image or solid color as in the other sections.
For this, I would like to know how to set a JavaScript code as the background, without affecting any other item inside the same section and being able to see the text over this background element.
This is the concrete script that I would like to set as background (got it from codePen.io): http://jsfiddle.net/oleg_korol/a1bxr5ua/1/
Here is the code:
var w = c.width = window.innerWidth,
h = c.height = window.innerHeight,
ctx = c.getContext('2d'),
opts = {
len: 20,
count: 50,
baseTime: 10,
addedTime: 10,
dieChance: .05,
spawnChance: 1,
sparkChance: .1,
sparkDist: 10,
sparkSize: 2,
color: 'hsl(hue,100%,light%)',
baseLight: 50,
addedLight: 10, // [50-10,50+10]
shadowToTimePropMult: 6,
baseLightInputMultiplier: .01,
addedLightInputMultiplier: .02,
cx: w / 2,
cy: h / 2,
repaintAlpha: .04,
hueChange: .1
},
tick = 0,
lines = [],
dieX = w / 2 / opts.len,
dieY = h / 2 / opts.len,
baseRad = Math.PI * 2 / 6;
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, w, h);
function loop() {
window.requestAnimationFrame(loop);
++tick;
ctx.globalCompositeOperation = 'source-over';
ctx.shadowBlur = 0;
ctx.fillStyle = 'rgba(0,0,0,alp)'.replace('alp', opts.repaintAlpha);
ctx.fillRect(0, 0, w, h);
ctx.globalCompositeOperation = 'lighter';
if (lines.length < opts.count && Math.random() < opts.spawnChance) lines.push(new Line);
lines.map(function (line) {
line.step();
});
}
function Line() {
this.reset();
}
Line.prototype.reset = function () {
this.x = 0;
this.y = 0;
this.addedX = 0;
this.addedY = 0;
this.rad = 0;
this.lightInputMultiplier = opts.baseLightInputMultiplier + opts.addedLightInputMultiplier * Math.random();
this.color = opts.color.replace('hue', tick * opts.hueChange);
this.cumulativeTime = 0;
this.beginPhase();
}
Line.prototype.beginPhase = function () {
this.x += this.addedX;
this.y += this.addedY;
this.time = 0;
this.targetTime = (opts.baseTime + opts.addedTime * Math.random()) | 0;
this.rad += baseRad * (Math.random() < .5 ? 1 : -1);
this.addedX = Math.cos(this.rad);
this.addedY = Math.sin(this.rad);
if (Math.random() < opts.dieChance || this.x > dieX || this.x < -dieX || this.y > dieY || this.y < -dieY) this.reset();
}
Line.prototype.step = function () {
++this.time;
++this.cumulativeTime;
if (this.time >= this.targetTime) this.beginPhase();
var prop = this.time / this.targetTime,
wave = Math.sin(prop * Math.PI / 2),
x = this.addedX * wave,
y = this.addedY * wave;
ctx.shadowBlur = prop * opts.shadowToTimePropMult;
ctx.fillStyle = ctx.shadowColor = this.color.replace('light', opts.baseLight + opts.addedLight * Math.sin(this.cumulativeTime * this.lightInputMultiplier));
ctx.fillRect(opts.cx + (this.x + x) * opts.len, opts.cy + (this.y + y) * opts.len, 2, 2);
if (Math.random() < opts.sparkChance) ctx.fillRect(opts.cx + (this.x + x) * opts.len + Math.random() * opts.sparkDist * (Math.random() < .5 ? 1 : -1) - opts.sparkSize / 2, opts.cy + (this.y + y) * opts.len + Math.random() * opts.sparkDist * (Math.random() < .5 ? 1 : -1) - opts.sparkSize / 2, opts.sparkSize, opts.sparkSize)
}
loop();
window.addEventListener('resize', function () {
w = c.width = window.innerWidth;
h = c.height = window.innerHeight;
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, w, h);
opts.cx = w / 2;
opts.cy = h / 2;
dieX = w / 2 / opts.len;
dieY = h / 2 / opts.len;
});
//# sourceURL=pen.js
Thanks a lot!
Original piece of code from: http://codepen.io/towc/pen/mJzOWJ
by Matei Copot
You can do this using an iframe and placing it as an absolute element with full body width and height like this:
HTML:
<body>
<div id="iframe"><iframe name="result" sandbox="allow-forms allow-popups allow-scripts allow-same-origin" frameborder="0" src="//fiddle.jshell.net/oleg_korol/a1bxr5ua/1/show/"></iframe></div>
<!--Your page content-->
</body>
CSS:
html, body {
margin:0px;
width:100%;
height:100%;
overflow:hidden;
}
iframe {
width:100%;
height:100%;
}
#iframe {
position: absolute;
float: left;
clear: both;
width: 100%;
height: 100%;
z-index: 0;
}
Here is a jsfiddle with above codes: https://jsfiddle.net/AndrewL32/kkLLxkxk/2/
And here is a StackOverflow snippet with above codes:
html, body {
margin:0px;
width:100%;
height:100%;
overflow:hidden;
}
iframe {
width:100%;
height:100%;
}
#iframe {
position: absolute;
float: left;
clear: both;
width: 100%;
height: 100%;
z-index: 0;
}
<div id="iframe"><iframe name="result" sandbox="allow-forms allow-popups allow-scripts allow-same-origin" frameborder="0" src="//fiddle.jshell.net/oleg_korol/a1bxr5ua/1/show/"></iframe></div>
WITHOUT IFRAME:
If you want to use the canvas as the background-image for the whole page, then the current code that you are using should work fine with width and height defined:
canvas {
position:absolute;
width:100%;
height:100%;
top:0px;
left:0px;
}
However if you want it as the background-image only for a certain div, then you can just add a position:relative; property to the parent div like this:
HTML:
<div id="canvas-box">
<canvas id=c></canvas>
</div>
CSS:
#canvas-box {
position:relative;
width:500px;
height:500px;
}
canvas {
position: absolute;
top: 0;
left: 0;
width:100%;
height:100%;
}
Here is a jsfiddle for adding canvas as background for a specific div: http://jsfiddle.net/AndrewL32/a1bxr5ua/5/

Categories

Resources