Fibonacci Sphere with svg(images) instead of points - javascript

I am trying to do a Fibonacci Sphere with a canvas like the following code, but instead of the same point showing everywhere I want to show different images, possibly svgs like logos and other images. I've done some research in google like visiting codepen and other places but couldn't find anything that worked. I imagine it would be something like the one in this website here. Any idea on how to approach this?
var cant = 100;
var offset = 2 / cant;
var increment = Math.PI * (3 - Math.sqrt(5));
var canvas = document.getElementById("canvas");
var i;
var circle;
//---Build the elements
for(i = 0; i < cant; i++){
circle = document.createElement("div");
circle.className = "point";
circle.setAttribute("data-index", i);
canvas.appendChild(circle);
};
//---Apply transformations to points
function updatePoints(evt){
var x, y, z, r, a, scale, opacity, point, style;
var angle = (evt) ? (-evt.pageX / 4) * Math.PI / 180 : 0;
for(i = 0; i < cant; i++){
y = (i * offset - 1) + (offset / 2);
r = Math.sqrt(1 - Math.pow(y, 2));
a = ((i + 1) % cant) * increment + angle;
x = Math.cos(a) * r;
z = Math.sin(a) * r;
scale = Math.round(z * 20000) / 100;
opacity = (1 + z) / 1.5;
style = "translate3d(" + (125 + x * 100) + "px, " + (125 + y * 100) + "px, " + scale + "px)";
point = canvas.querySelectorAll("[data-index='" + i +"']");
point[0].style.WebkitTransform = style;
point[0].style.msTransform = style;
point[0].style.transform = style;
point[0].style.opacity = opacity;
}
}
//---Update the points at start
updatePoints();
//---Update the points on mouse move
document.addEventListener("mousemove", updatePoints);
body, html{
height: 100%;
position: relative;
}
body{
background-color: #232B2B;
margin: 0;
padding: 0;
}
#canvas{
height: 250vh;
margin: 0 0;
position: relative;
width: 250vh;
}
.point{
background: red;
border-radius: 50%;
height: 4px;
position: absolute;
transform-style: preserve-3d;
width: 4px;
}
<div id="canvas">
</div>
Any help would be most helpful.

You can continue using the createElement method.
I added this, to show a random image (from picsum) for each dot:
// Create a new img element
img = document.createElement('img');
// Add the src to each img element.
//Here using the iterator variable to
//change the id of the photo we are retrieving
img.src = 'https://picsum.photos/id/' + i +'/20/20'
// Append the img to the div
circle.appendChild(img);
And I made the circles a bit larger in the CSS (20px) so you can see it.
If you want specific images, you could create an array inside your JS, or pull from a folder on your server.
var cant = 100;
var offset = 2 / cant;
var increment = Math.PI * (3 - Math.sqrt(5));
var canvas = document.getElementById("canvas");
var i;
var circle;
//---Build the elements
for(i = 0; i < cant; i++){
circle = document.createElement("div");
img = document.createElement('img');
img.src = 'https://picsum.photos/id/' + i +'/20/20'
circle.appendChild(img);
circle.className = "point";
circle.setAttribute("data-index", i);
canvas.appendChild(circle);
};
//---Apply transformations to points
function updatePoints(evt){
var x, y, z, r, a, scale, opacity, point, style;
var angle = (evt) ? (-evt.pageX / 4) * Math.PI / 180 : 0;
for(i = 0; i < cant; i++){
y = (i * offset - 1) + (offset / 2);
r = Math.sqrt(1 - Math.pow(y, 2));
a = ((i + 1) % cant) * increment + angle;
x = Math.cos(a) * r;
z = Math.sin(a) * r;
scale = Math.round(z * 20000) / 100;
opacity = (1 + z) / 1.5;
style = "translate3d(" + (125 + x * 100) + "px, " + (125 + y * 100) + "px, " + scale + "px)";
point = canvas.querySelectorAll("[data-index='" + i +"']");
point[0].style.WebkitTransform = style;
point[0].style.msTransform = style;
point[0].style.transform = style;
point[0].style.opacity = opacity;
}
}
//---Update the points at start
updatePoints();
//---Update the points on mouse move
document.addEventListener("mousemove", updatePoints);
body, html{
height: 100%;
position: relative;
}
body{
background-color: #232B2B;
margin: 0;
padding: 0;
}
#canvas{
height: 250vh;
margin: 0 0;
position: relative;
width: 250vh;
}
.point{
background: red;
border-radius: 50%;
height: 20px;
position: absolute;
transform-style: preserve-3d;
width: 20px;
overflow: hidden;
}
<div id="canvas">
</div>

Related

Calculate position (X, Y) on cirlcle base on height

I think the title is a little bit confusing so I will try to say it better.
Image you have this code:
#NadrzFrontView:before {
--beginHeight: var(--startHeight);
--endHeight: var(--finishHeight);
animation: 2s fillin ease forwards;
content: "";
position: absolute;
bottom: 0;
width: 300px;
height: 0;
background-color: #00FFF5;
display: inline-block;
}
#NadrzFrontView {
width: 300px;
height: 300px;
border-radius: 50%;
border: 3px solid black;
position: relative;
overflow: hidden;
}
<div id="NadrzFrontView" style="--startHeight: 0%; --finishHeight: 50%;"> </div>
It looks like this:
Now, you can determent left, top position and height of an element using this script:
function getOffset(el) {
var rect = el.getBoundingClientRect();
return {
left: rect.left + window.pageXOffset,
top: rect.top + window.pageYOffset,
width: rect.width || el.offsetWidth,
height: rect.height || el.offsetHeight
};
}
Ok, when we are able to find these then we go to our problem:
function SomeFunction() {
var thickness = 1;
var color = '#000000';
var off_nadrz = getOffset(document.getElementById('NadrzFrontView'));
var elem = document.getElementById('NadrzFrontView');
var pseudoStyle = window.getComputedStyle(elem, ':before');
var off_pseudo_elem = getOffset(elem);
off_pseudo_elem.top += parseInt(pseudoStyle.top, 10);
off_pseudo_elem.left += parseInt(pseudoStyle.left, 10);
off_pseudo_elem.height = parseInt(pseudoStyle.height, 10);
//finding middle of the circle
var x1 = off_nadrz.left + (off_nadrz.width / 2);
var y1 = off_nadrz.top + (off_nadrz.height / 2);
//draw point in the middle of circle
document.getElementById("AllLines").innerHTML += CreateHtmlPoint(color, x1, y1);
//fincding point on the side of an element
var x2; //I need to find this -- see more in examples
var y2; //I need to find this -- see more in examples
document.getElementById("AllLines").innerHTML += CreateHtmlPoint(color, x2, y2); //This does not work
}
function CreateHtmlPoint(color, cx, cy) {
cx -= 5; // - 5, because width of point is 10
cy -= 5; // - 5, because height of point is 10
return "<div style='padding:0px; z-index: 2; margin:0px; height: 10px; width: 10px; background-color:" + color + "; line-height:1px; position:absolute; left:" + cx + "px; top:" + cy + "px; border-radius: 50%;' />";
}
So, now example of an x2 and y2 would look like this:
Basically, we know on what coordinades is top of circle (off_nadrz.top), bottom of circle (off_nadrz.top + (off_nadrz.height / 2)) and height of an circle (off_nadrz.height). We also know same things of an psuedo_element (blue thing in the circle). From this we need to calculate x2 and y2.
Thanks for every suggestion because I am fighting with this problem for 2 days now...
you have only to apply the circumference formula:
var y2 = y1 - ( off_pseudo_elem.height - off_nadrz.height / 2 );
once you have y2, calculate x2:
var r = off_nadrz.height / 2; // if the figure is a circle, not an ellipse
var x2 = x1 + Math.sqrt( r * r - ( y2 - y1 ) * ( y2 - y1 ) );

Creating a disney dust style cursor trail

I'm trying to make a cursor that leaves a trail of magic dust like in that intro to any Disney film: example. So the way I see it is it's split into two parts. 1. the trail and 2. similar trail that falls and fades out. So far I have made the basic trail work quite well, the code below is for the falling trail and essentially a copy of it with a css animation..
The problem I'm having is it's jittering a lot. I'm guessing the css animation is not great for performance and is causing this to really jitter on my page. I've just read up on requestAnimationFrame but am new to this so not sure how to implement it.. How could I use requestAnimationFrame instead of css here?
I also think creating the animation custom in js would allow there to also be a random offset in the animation of the falling particles.. much more like in the video.
window.addEventListener('mousemove', function (e) {
//trail
[1, .9, .8, .5, .25, .6, .4, .3, .2].forEach(function (i) {
var j = (1 - i) * 50;
var elem = document.createElement('div');
var size = Math.ceil(Math.random() * 10 * i) + 'px';
elem.style.position = 'fixed';
elem.style.zIndex = 6;
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.width = size;
elem.style.opacity = "0.5";
elem.style.height = size;
elem.style.background = 'hsla(' +
Math.round(Math.random() * 160) + ', ' +
'60%, ' +
'90%, ' +
i + ')';
elem.style.borderRadius = size;
elem.style.pointerEvents = 'none';
document.body.appendChild(elem);
window.setTimeout(function () {
document.body.removeChild(elem);
}, Math.round(Math.random() * i * 1000));
});
// falling trail
[1, .9, .8, .5, .25, .6, .3, .2].forEach(function (i) {
var j = (1 - i) * 50;
var elem = document.createElement('div');
var size = Math.ceil(Math.random() * 10 * i) + 'px';
elem.style.position = 'fixed';
elem.style.zIndex = 6;
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.width = size;
elem.style.opacity = "0.5";
elem.style.height = size;
elem.style.animation = "fallingsparkles 1s";
elem.style.background = 'hsla(' +
Math.round(Math.random() * 160) + ', ' +
'60%, ' +
'90%, ' +
i + ')';
elem.style.borderRadius = size;
elem.style.pointerEvents = 'none';
document.body.appendChild(elem);
window.setTimeout(function () {
document.body.removeChild(elem);
}, Math.round(Math.random() * i * 1000));
});
}, false);
body {
width:100%;
height:100%;
background-color: #000;
}
#keyframes fallingsparkles {
from {
transform: translateY(0);
}
to {
transform: translateY(50px);
}
}
<body></body>
What a cool little animation. I think it will be annoying in the long run, but still: cool.
What I don't like about this solution is that I had to do a continuous recursive loop, that goes on even if there are no elements to animate. There are probably ways to avoid that, but it would be too complex for just to showcase how to implement requestAnimationFrame. As you can see, it's not that hard to use requestAnimationFrame. You just call the same method that you do the calculations in.
Apart from adding each element to the body, I also added the element into sparkleArr with a few more properties through addAnimationProperties. I finally added a whole new method - moveSparkles - for calculating movement and removing the elements. calculateInterpolation calculates the percentage of how long the element should move, based on when the element was created, when it will disappear and the current time.
I think the code is self-explanatory. I had to do a comment on one place, where I don't think it would be possible to explain the code through variables or method names.
let trailArr = [1, .9, .8, .5, .25, .6, .4, .3, .2];
var sparklesArr = [];
function trailAnimation(e, i, maxYTranslation) {
let elem = document.createElement('div');
elem = styleSparkle(elem, e, i);
elem.classList.add("sparkle");
document.body.appendChild(elem);
elem = addAnimationProperties(elem, i, maxYTranslation);
sparklesArr.push(elem);
}
function styleSparkle(elem, e, i) {
let j = (1 - i) * 50;
let size = Math.ceil(Math.random() * 10 * i) + 'px';
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.width = size;
elem.style.height = size;
elem.style.borderRadius = size;
elem.style.background = 'hsla(' +
Math.round(Math.random() * 160) + ', ' +
'60%, ' +
'90%, ' +
i + ')';
return elem;
}
function addAnimationProperties(elem, i, maxYTranslation) {
const ANIMATION_SPEED = 1100;
let lifeExpectancy = Math.round(Math.random() * i * ANIMATION_SPEED);
elem.maxYTranslation = maxYTranslation;
elem.animationSpeed = ANIMATION_SPEED;
elem.created = Date.now();
elem.diesAt = elem.created + lifeExpectancy;
return elem;
}
function moveSparkles() {
let remove = false;
let moveIndex = 0;
let sparkle;
for (let i = 0; i < sparklesArr.length; i++) {
sparkle = sparklesArr[i];
remove = sparkle.diesAt <= Date.now();
if (remove) {
document.body.removeChild(sparkle);
} else {
if (sparkle.maxYTranslation) {
let interpolation = calculateInterpolation(sparkle);
sparkle.style.transform = `translateY(${interpolation}px)`;
}
sparklesArr[moveIndex++] = sparkle; // faster than array.splice()
}
}
sparklesArr.length = moveIndex;
requestAnimationFrame(moveSparkles);
}
function calculateInterpolation(sparkle) {
let currentMillis = Date.now();
let lifeProgress = (currentMillis - sparkle.created) / sparkle.animationSpeed;
let interpolation = sparkle.maxYTranslation * lifeProgress;
return interpolation;
}
window.addEventListener('mousemove', function (e) {
trailArr.forEach((i) => {trailAnimation(e, i)});
let maxYTranslation = '80';
trailArr.forEach((i) => {trailAnimation(e, i, maxYTranslation)});
}, false);
moveSparkles(); // starts the recursive loop
body {
width:100%;
height:100%;
background-color: #000;
}
.sparkle {
position: fixed;
z-index: 6;
opacity: 0.5;
pointer-events: none;
}
<body></body>
I made another version thats quite fun.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
width: 100%;
height: 100%;
background-color: #000;
}
.star-five {
background: transparent;
margin: 50px 0;
position: relative;
display: block;
color: #ffffff;
width: 0px;
height: 0px;
border-right: 100px solid transparent;
border-bottom: 70px solid #ffffff;
border-left: 100px solid transparent;
/* transform: rotate(35deg) scale(0.1) translate(-1450px, -250px); */
}
.star-five:before {
border-bottom: 80px solid #ffffff;
border-left: 30px solid transparent;
border-right: 30px solid transparent;
background-color: transparent;
position: absolute;
height: 0;
width: 0;
top: -45px;
left: -65px;
display: block;
content: '';
transform: rotate(-35deg);
}
.star-five:after {
background-color: transparent;
position: absolute;
display: block;
color: #ffffff;
top: 3px;
left: -105px;
width: 0px;
height: 0px;
border-right: 100px solid transparent;
border-bottom: 70px solid #ffffff;
border-left: 100px solid transparent;
transform: rotate(-70deg);
content: '';
}
</style>
</head>
<body>
<script>
window.addEventListener('mousemove', function (e) {
//trail
[.7, .9, .8, .5, .25, .6, .4, .3, .2].forEach(function (i) {
var j = (1 - i) * 50;
var elem = document.createElement('div');
var size = Math.ceil(Math.random() * 10 * i) + 'px';
//ramdom number between 0 and 1
var precision = 50; // 2 decimals
var randomnum = Math.floor(Math.random() * (10 * precision - 1 * precision) + 1 * precision) / (1*precision);
var rOpacity = randomnum/10;
var rSize = randomnum/120;
elem.style.position = 'fixed';
elem.classList.add('star-five')
elem.style.zIndex = 6;
elem.style.transform = `rotate(35deg) scale(${rSize})`
//elem.style.transform = `rotate(35deg) scale(${rSize}) translate(-1450px, -250px)`
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) - 100 + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) - 100 + 'px';
//elem.style.width = size;
//console.log(rSize);
elem.style.opacity = rOpacity;
//elem.style.height = size;
// elem.style.background = 'hsla(' +
// Math.round(Math.random() * 160) + ', ' +
// '60%, ' +
// '100%, ' +
// i + ')';
//elem.style.borderRadius = size;
elem.style.pointerEvents = 'none';
document.body.appendChild(elem);
window.setTimeout(function () {
document.body.removeChild(elem);
}, Math.round(Math.random() * i * 1000));
});
////
}, false);
</script>
</body>
</html>
I'm mostly posting this for others to use, where I refactored the code a bit. Nothing has changed, but it's easier to follow. I will follow up with a real answer.
let trailArr = [1, .9, .8, .5, .25, .6, .4, .3, .2];
function trailAnimation(e, i, callbackFn) {
var elem = document.createElement('div');
elem = styleSparkle(elem, e, i);
if (typeof callbackFn == 'function') {
elem = callbackFn(elem);
}
elem.classList.add("sparkle");
document.body.appendChild(elem);
window.setTimeout(function () {
document.body.removeChild(elem);
}, Math.round(Math.random() * i * 1000));
}
function styleSparkle(elem, e, i) {
let j = (1 - i) * 50;
let size = Math.ceil(Math.random() * 10 * i) + 'px';
elem.style.top = e.pageY - window.scrollY + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.left = e.pageX + Math.round(Math.random() * j - j / 2) + 'px';
elem.style.width = size;
elem.style.height = size;
elem.style.borderRadius = size;
elem.style.background = 'hsla(' +
Math.round(Math.random() * 160) + ', ' +
'60%, ' +
'90%, ' +
i + ')';
return elem;
}
window.addEventListener('mousemove', function (e) {
trailArr.forEach((i) => {trailAnimation(e, i)});
trailArr.forEach((i) => {trailAnimation(e, i, (elem) => {
elem.style.animation = "fallingsparkles 1s";
return elem;
})});
}, false);
body {
width:100%;
height:100%;
background-color: #000;
}
.sparkle {
position: fixed;
z-index: 6;
opacity: 0.5;
pointer-events: none;
}
#keyframes fallingsparkles {
from {
transform: translateY(0);
}
to {
transform: translateY(50px);
}
}
<body></body>

Alternative to element.getBoundingClientRect()

I have been using getBoundingClientRect(). At the beginning, I'm getting performance issues due to this. If I remove this method from my code, there is working well. Any alternatives to getBoundingClientRect() in javascript.
In this sample, I have created 2000 elements in button click and changed their positions in another button click. In that, I'm getting performance issues when using getBoundingClientRect().
Anyone help me to resolve this.
document.getElementById("click1").onclick = function() {
for (var i = 0; i < 2000; i++) {
var ele = document.createElement("DIV");
ele.id = i + '';
ele.className = "square";
ele.setAttribute("style", "position: absolute;left: 200px; top: 100px");
document.getElementById("marker").appendChild(ele);
}
};
document.getElementById("click").onclick = function() {
var markerCollection = document.getElementById("marker");
var width = 20,
height = 20;
var radius = width * 2;
var area = 2 * 3.14 * radius;
var totalMarker = 0;
var numberOfMarker = Math.round(area / width);
totalMarker += numberOfMarker;
var percent = Math.round((height / area) * 100);
percent =
markerCollection.children.length - 1 < numberOfMarker ?
100 / markerCollection.children.length - 1 :
percent;
var angle = (percent / 100) * 360;
var centerX = 200,
centerY = 100;
var count = 1;
var newAngle = 0,
first = false;
var dt1 = 0,
dt2 = 0;
dt1 = new Date().getTime();
for (var i = 0; i < markerCollection.children.length; i++) {
if (i != 1 && (i - 1) % totalMarker === 0) {
count++;
radius = (width + 10) * count;
newAngle = 0;
area = 2 * 3.14 * radius;
numberOfMarker = Math.round(area / width);
percent = Math.round((height / area) * 100);
angle = (percent / 100) * 360;
totalMarker += numberOfMarker;
}
var x1 = centerX + radius * Math.sin((Math.PI * 2 * newAngle) / 360);
var y1 = centerY + radius * Math.cos((Math.PI * 2 * newAngle) / 360);
var offset = markerCollection.children[i].getBoundingClientRect();
markerCollection.children[i]["style"].left = (x1 - (offset.width / 2)) + "px";
markerCollection.children[i]["style"].top = (y1 - (offset.height / 2)) + "px";
newAngle += angle;
}
dt2 = new Date().getTime();
alert(dt2 - dt1);
};
<!DOCTYPE html>
<html>
<head>
<style>
.square {
height: 20px;
width: 20px;
background-color: #555;
border: 1px solid red;
}
</style>
</head>
<body>
<button id="click1">Create Element</button>
<button id="click">Click To Change</button>
<div id='marker' style="width: 350px;height: 200px;border: 1px solid red">
</div>
</div>
<script>
</script>
</body>
</html>
If I'm not misreading your code, all you're using getBoundingClientRect() for is to calculate the width and height of an element you already know the width and height of (20x20px).
Just use your width and height variables directly, or possibly avoid having to do the offset calculation entirely, add transform: translate(-50% -50%) to the element's style.

margin right not working on canvas html5 and trouble with scroll bar removal

I have the following canvas:
Codepen link
What I want: Equal margin on both sides of canvas without any horizontal scroll bars.
Problem: margin-right property does not to work. I have seen some solutions that solve this problem by specifying a fixed width, but I cannot have a fixed width in my case. I want my canvas to adjust its width height according to the size of the window.
The following Javascript takes care of that:
window.addEventListener('resize' , resizeCanvas , false);
function resizeCanvas(){
canvas.width = window.innerWidth;
canvas.height = window.innerHeight/1.2;
}
So is there a different solution?
For the overflow problem, if I put overflow-x: hidden inside the body then only the scrollbar disappears but the problem persists. The canvas still extends past the screen hence the right border of the canvas is No longer visible.
See here
Here is my code:
HTML
<body onload="start()">
<canvas id="myCanvas"></canvas>
</body>
CSS
body{
}
canvas{
border: 1px solid black;
border-radius: 5px;
background-color: #fff;
margin: auto 50px auto 50px; /* works for left margin but not for right */
}
Thanks!
Another thing:
I have not set width: 100% for the canvas because it distorts the content inside it.
As Chris is saying you need to set the width of the canvas lower than the full width of the page:
canvas.width = window.innerWidth - 100;
Note that you need to take the border-width of the canvas and in your codepen the body also has a margin of 8px into account as well:
canvas.width = window.innerWidth - 118;
CSS calc() method is what you need. Just subtract the margins from 100% and you get the desired result. See the demo below. CSS calc() reference
function start() {
var canvas = document.getElementById('myCanvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight / 1.2;
var ctx = canvas.getContext('2d');
function rand(min, max) {
return parseInt(Math.random() * (max - min + 1), 10) + min;
}
function get_random_color() {
var h = rand(1, 360);
var s = rand(30, 100);
var l = rand(30, 70);
return 'hsl(' + h + ',' + s + '%,' + l + '%)';
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
var balls = [];
var ballCount = getRandomInt(2, 10);
//document.getElementById('ballCountInfo').innerHTML = ballCount;
//document.getElementById('box').innerHTML = ballCount;
var startpointX = 100;
var startpointY = 50;
for (var i = 0; i < ballCount; i++) {
var randValue = getRandomInt(20, 30);
balls.push({
x: startpointX,
y: startpointY,
vx: getRandomInt(3, 3) * direction(),
vy: getRandomInt(1, 1) * direction(),
radius: randValue,
mass: randValue,
color: get_random_color(),
draw: function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fillStyle = this.color;
ctx.fill();
}
});
startpointX = startpointX + 50;
startpointY = startpointY + 40;
}
function direction() {
var chosenValue = Math.random() < 0.5 ? 1 : -1;
return chosenValue;
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (var i = 0; i < ballCount; i++) {
balls[i].draw();
balls[i].x += balls[i].vx;
balls[i].y += balls[i].vy;
if ((balls[i].y + balls[i].vy + balls[i].radius) > canvas.height || (balls[i].y + balls[i].vy - balls[i].radius) < 0) {
balls[i].vy = -balls[i].vy;
}
if ((balls[i].x + balls[i].vx + balls[i].radius) > canvas.width || (balls[i].x + balls[i].vx - balls[i].radius) < 0) {
balls[i].vx = -balls[i].vx;
}
}
// onBoxTouched();
//collision check
for (var i = 0; i < ballCount; i++) {
for (var j = i + 1; j < ballCount; j++) {
var distance = Math.sqrt(
(balls[i].x - balls[j].x) * (balls[i].x - balls[j].x) +
(balls[i].y - balls[j].y) * (balls[i].y - balls[j].y)
);
if (distance < (balls[i].radius + balls[j].radius)) {
var ax = (balls[i].vx * (balls[i].mass - balls[j].mass) + (2 * balls[j].mass * balls[j].vx)) / (balls[i].mass + balls[j].mass);
var ay = (balls[i].vy * (balls[i].mass - balls[j].mass) + (2 * balls[j].mass * balls[j].vy)) / (balls[i].mass + balls[j].mass);
balls[j].vx = (balls[j].vx * (balls[j].mass - balls[i].mass) + (2 * balls[i].mass * balls[i].vx)) / (balls[i].mass + balls[j].mass);
balls[j].vy = (balls[j].vy * (balls[j].mass - balls[i].mass) + (2 * balls[i].mass * balls[i].vy)) / (balls[i].mass + balls[j].mass);
balls[i].vx = ax;
balls[i].vy = ay;
}
}
}
raf = window.requestAnimationFrame(draw);
}
function onBoxTouched() {
for (var i = 0; i < ballCount; i++) {
if (balls[i].x + balls[i].radius > 600 && balls[i].x + balls[i].radius < 750 &&
balls[i].y + balls[i].radius > 200 && balls[i].y + balls[i].radius < 350) {
//var ele = document.getElementById("box");
ele.style.backgroundColor = balls[i].color;
balls.splice(i, 1);
ballCount = ballCount - 1;
if (ballCount == 0) {
ele.style.fontSize = "x-large";
ele.innerHTML = "Over";
} else {
ele.innerHTML = ballCount;
}
//document.getElementById('ballCountInfo').innerHTML=" "+ballCount;
}
}
}
window.requestAnimationFrame(draw);
window.addEventListener('resize', resizeCanvas, false);
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight / 1.2;
}
}
* {}
html,
body {}
canvas {
border: 1px solid black;
border-radius: 5px;
background-color: #fff;
width: calc(100% - 40px);
/*substract the total margin from 100% and will automoatically adjuts accordint to your need*/
margin: auto 20px auto 20px;
/* works for left margin but not for right */
}
#box {
width: 150px;
height: 150px;
background-color: plum;
border-radius: 5px;
position: absolute;
top: 200px;
left: 600px;
font-size: 72px;
font-weight: bold;
color: white;
line-height: 150px;
text-align: center;
}
#info {
float: left;
font-size: 24px;
color: #6D8390;
margin-top: 20px;
}
<body onload="start()">
<canvas id="myCanvas"></canvas>
</body>
Hope it helps :)
instead of messing around with margins, just change the width of your canvas and center it.
CSS
canvas {
border: 1px solid black;
border-radius: 5px;
background-color: #fff;
width: 90%!important;
}
HTML
<body onload="start()">
<center>
<canvas id="myCanvas"></canvas>
</center>
</body>
https://codepen.io/anon/pen/GEmLPL

Strange issue with arithmetics (?)

Background: I'm working on a library for creating "low resolution" display.
Now I wanted to test it with a simple demo - it should draw a radial gradient around cursor.
I think I got the math right and it is working, except when you move your mouse into the bottom left corner.
I tried printing the numbers, changing order and all, but can't find the cause.
Here is also a Fiddle: https://jsfiddle.net/to5qfk7o/
var size = 16; // number of pixels
var lo = new Lores('#board', size, size);
// DRAWING FUNCTION
setInterval(function () {
// Mouse coords
var m_x = lo.mouse.x;
var m_y = lo.mouse.y;
// print where is mouse - for debug
console.log(m_x + "," + m_y);
// for all pixels on screen
for (var x = 0; x < size; x++) {
for (var y = 0; y < size; y++) {
// mouse distance from this pixel
var distance = (Math.sqrt((m_x - x) * (m_x - x) + (m_y - y) * (m_y - y)));
// convert: 0..255, "size"..0
var color = 255 - Math.floor((255 / size) * distance);
// set color
if (color < 0) {
lo.set(y, x, 'black');
} else {
lo.set(x, y, 'rgb(' + color + ', 0, 0)');
}
}
}
}, 100);
// ---- LIBRARY CODE -----
function Lores(selector, width, height) {
this.boardElem = document.querySelector(selector);
this.boardElem.className += ' lores-screen';
this.grid = [];
this.mouse = {
inside: false,
x: 0,
y: 0 // position rounded to nearest board "pixel"
};
this.width = width;
this.height = height;
if (this.boardElem === null) {
console.error('No such element!');
return;
}
if (width <= 0 || height <= 0) {
console.error('Dimensions must be positive!');
return;
}
// Inject a style block for the sizes
var css = selector + ' > div {height:' + (100 / height) + '%}';
css += selector + ' > div > div {width:' + (100 / width) + '%}';
var style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.head.appendChild(style);
var frag = document.createDocumentFragment();
// Create the grid
for (var i = height; i > 0; i--) {
var rowElem = document.createElement('div');
rowElem.dataset.y = i;
var row = [];
for (var j = width; j > 0; j--) {
var cellElem = document.createElement('div');
cellElem.dataset.x = j;
rowElem.appendChild(cellElem);
row.push(cellElem);
}
frag.appendChild(rowElem);
this.grid.push(row);
}
this.boardElem.appendChild(frag);
console.log('yo');
var self = this;
// add mouse listener
document.addEventListener('mousemove', function (e) {
var rect = self.boardElem.getBoundingClientRect();
var x = (self.width * (e.clientX - rect.left)) / rect.width;
var y = (self.height * (e.clientY - rect.top)) / rect.height;
self.mouse.x = Math.floor(x);
self.mouse.y = Math.floor(y);
self.mouse.inside = (x >= 0 && x < self.width && y >= 0 && y < self.height);
}, false);
}
Lores.prototype.set = function (x, y, color) {
if (x < 0 || x >= this.width || y < 0 || y >= this.height) return;
this.grid[y][x].style.backgroundColor = color;
};
#board {
margin: 0 auto;
width: 128px;
height: 128px;
outline: 1px solid black;
}
#board > div:nth-child(odd) > div:nth-child(odd) {
background: #eee
}
#board > div:nth-child(even) > div:nth-child(even) {
background: #eee
}
.lores-screen {
display: block;
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.lores-screen, .lores-screen * {
white-space: nowrap;
padding: 0;
}
.lores-screen * {
margin: 0
}
.lores-screen > div {
display: block;
}
.lores-screen > div > div {
display: inline-block;
vertical-align: top;
height: 100%;
}
<div id="board"></div>
It could be something trivial, I really don't know. Thanks!
The problem is a simple typo in your if statement. You have x and y mixed up in the set of your first branch. Having said that, we can eliminate the branch entirely. A simple Math.max(0, ...) will default it to black.
Change the following:
var color = 255 - Math.floor((255 / size) * distance);
// set color
if (color < 0) {
lo.set(y, x, 'black');
} else {
lo.set(x, y, 'rgb(' + color + ', 0, 0)');
}
to
var color = Math.max(0, 255-Math.floor((255 / size) * distance));
lo.set(x, y, 'rgb(' + color + ', 0, 0)');
jsfiddle
change
// set color
if (color < 0) {
lo.set(y, x, 'black');
} else {
lo.set(x, y, 'rgb(' + color + ', 0, 0)');
}
to
// set color
lo.set(x, y, 'rgb(' + Math.max(color, 0) + ', 0, 0)');
https://jsfiddle.net/hrvqa457/

Categories