Jquery/javascript: circulate an image [duplicate] - javascript

I have an image (red, below), that I want to make travel along a circular path. The red image should always end in the same spot as it started.
Notes:
The grey circular path is invisible. I am just highlighting the path it will follow.
What is the best method/library to achieve this technique?

Do you really need a library, it's not that hard to do
$(document).ready(function (e) {
var startAngle = 0;
var unit = 215;
var animate = function () {
var rad = startAngle * (Math.PI / 180);
$('.circle').css({
left: 250 + Math.cos(rad) * unit + 'px',
top: unit * (1 - Math.sin(rad)) + 'px'
});
startAngle--;
}
var timer = setInterval(animate, 10);
});
FIDDLE
Here's one that does one loop, stops at the same place etc.
$(document).ready(function (e) {
var startAngle = 180;
var unit = 215;
var animate = function () {
if (startAngle > -180) {
var rad = startAngle * (Math.PI / 180);
$('.circle').css({
left: 250 + Math.cos(rad) * unit + 'px',
top: unit * (1 - Math.sin(rad)) + 'px'
});
startAngle--;
setTimeout(animate, 10);
}
}
$('.circle').on('click', function() {
startAngle = 180;
animate();
});
});
FIDDLE

Please look into these links:
CSS Technique
Stackoverflow Answers : Answer 1 || Answer 2
JSFiddle : Fiddle 1
var t = 0;
function moveit() {
t += 0.05;
var r = 100;
var xcenter = 100;
var ycenter = 100;
var newLeft = Math.floor(xcenter + (r * Math.cos(t)));
var newTop = Math.floor(ycenter + (r * Math.sin(t)));
$('#friends').animate({
top: newTop,
left: newLeft,
}, 1, function() {
moveit();
});
}
$(document).ready(function() {
moveit();
});

Related

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.

How should I code this jQuery code in Javascript?

This exercise I need a function that moves the div randomly inside of the body when I click with the left button mouse.
I'm having some difficulties to swap this code(jquery) into javascript. How would it be?
var counter = 0;
var div = document.getElementsByClassName('a');
function click() {
if (counter < 1) {
var pos = makeNewPosition();
this.style.left = pos[1] + 'px';
this.style.top = pos[0] + 'px';
}
}
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = window.innerHeight = -50;
var w = window.innerWidth = -50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
<div onclick="click()" class="a">Click</div>
This is the jQuery that I wanted to code in javascript.
$(document).ready(function(){
var counter = 0;
$('.a').click( function () {
if (counter < 1 ) {
var pos = makeNewPosition();
this.style.left = pos[1] +'px';
this.style.top = pos[0] +'px';
}
});
});
function makeNewPosition(){
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
JavaScript:
window.addEventListener("load", function() {
var counter = 0,
div = document.querySelector(".a");
div.addEventListener("click", function() {
if (counter < 1) {
var pos = makeNewPosition();
this.style.left = pos[1] + 'px';
this.style.ltop = pos[0] + 'px';
}
counter++;
});
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = window.innerHeight -50;
var w = window.innerWidth -50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
.a {
position: absolute;
top: 100;
left: 100
}
<div class="a">Click</div>
Based on this jQuery:
$(function() {
var counter = 0;
$('.a').click(function() {
if (counter < 1) {
var pos = makeNewPosition();
$(this).css({
"left": pos[1] + 'px',
"top": pos[0] + 'px'
});
}
counter++;
});
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = $(window).height() - 50;
var w = $(window).width() - 50;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
.a {
position: absolute;
top: 100;
left: 100
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="a">Click</div>
The most idiomatic way would be to first get a reference to the element
const div = document.getElementsByClassName('a')[0];
then add an event listener to the element
div.addEventListener('click', click); //Attach your handler function to the event

In round range slider, how can i change background color of the changed path?

I have got this function but i am unable to get the path to which the slider when dragged should change the background color of the circle...
$(document).ready(function () {
$("#circle").append('<canvas id="slideColorTracker" class="slideColor"></canvas>');
var canvas = document.getElementById("slideColorTracker");
var context = canvas.getContext('2d');
var $circle = $("#circle"),
$handler = $("#handler"),
$p = $("#test").val(),
handlerW2 = $handler.width() / 2,
radius = ($circle.width()/2)+10,
offset = $circle.offset(),
elementPos = { x: offset.left, y: offset.top },
mHold = 0,
PI = Math.PI / 180
$handler.mousedown(function () {
mHold = 1;
var dim = $("#slideColorTracker");
if ($(".slideColor").length > 1) {
$("#slideColorTracker").remove();
}
});
$(document).mousemove(function (e){
move(e);
}).mouseup(function () { mHold = 0 });
function move(e) {
if (mHold) {
debugger
var deg = 180;
var startAngle = 4.72;
var mousePos = { x: e.pageX - elementPos.x, y: e.pageY - elementPos.y }
var atan = Math.atan2(mousePos.x - radius, mousePos.y - radius);
var deg = -atan / PI + 180;
var percentage = (deg * 100 / 360) | 0;
var endAngle = percentage;
var X = Math.round(radius * Math.sin(deg * PI)),
Y = Math.round(radius * -Math.cos(deg * PI));
var cw = X + radius - handlerW2 - 10; //context.canvas.width /2;
var ch = Y + radius - handlerW2 - 10;
$handler.css({
left: X + radius - handlerW2 - 10,
top: Y + radius - handlerW2 - 10,
})
context.beginPath();
context.arc(($circle.width() / 2), ($circle.height() / 2), radius+20, startAngle, endAngle, false);
context.lineWidth = 15;
context.strokeStyle = 'black';
context.stroke();
$("#test").val(percentage);
$circle.css({ borderColor: "hsl(200,70%," + (percentage * 70 / 100 + 30) + "%)" });
}
}
});
I do not want to use any plugin!
Any help will be much appreciated, since i am new to jquery!
Your $handler does not drag for me unless I change it to this:
$handler.css({
left: mousePos.x,
top: mousePos.y,
position:'absolute'
})
When dragged passed $cirlce.width / 2 it does stroke it correctly.

remove elements in dom animation

I try to delete some animated elements if they pass the screen height. For that an array will be checked in a for loop. The array have the id's of the created div's. Theoretically should all div's which have an y position which is higher than the screen height become removed and the values from the array deleted. But now it becomes every n element removed. Know anyone the issue for that? box = setInterval(newbox, 1000); affect the behaviour when I change the interval time.
fiddle
var cx = wwidth / 100;
var cy = wheight / 100;
var maxpos = cx * 80;
var speed;
var box;
var counter = 0;
var rectids = [];
var deleting;
function newbox() {
var allpositions = Array(0, cx * 25, cx * 50, cx * 75);
var rectpos = allpositions[Math.floor(Math.random() * allpositions.length)];
speed = 0;
var box = document.createElement('div');
counter++;
box.className = "game-btn";
box.id = 'n' + counter;
box.style.cssText = "top:" + speed + "px;left:" + rectpos + "px;width:" + cx * 25 + "px;height:" + cy * 10 + "px;position:absolute";
console.log(rectpos);
document.body.appendChild(box);
rectids.push(box.id);
}
function game() {
box = setInterval(newbox, 1000);
animaterects = setInterval(function () {
speed += cx / 300;
$(".game-btn").css("top", "+=" + speed + "px");
}, 10);
deleting = setInterval(function () {
for (var i = 0; i < rectids.length; i++) {
var x = $("#" + rectids[i]).position();
if (x.top > wheight) {
$("#" + rectids[i]).remove();
rectids.splice(rectids[i]);
}
}
}, 50);
}
game();

jQuery connect with lines

How can I connect numbers with dotted lines in the below jsfiddle.
I want these lines to start from border of inner circle, either from jQuery or from css. I mean around border of inner circle start from inner border edge to number , ....... 1, ..... 2 to show guide lines.
http://jsfiddle.net/ineffablep/x03f61db/
function createFields() {
$('.field').remove();
var container = $('#container');
for(var i = 0; i < +$('input:text').val()+1; i++) {
$('<div/>', {
'class': 'field',
'text': i
}).appendTo(container);
}
}
function distributeFields() {
var fields = $('.field'), container = $('#container'),
width = center.width()*2, height = center.height()*2,
angle = 0, step = (2*Math.PI) / fields.length;
var radius = width/2;
var containerLength=$('input:text').val();
angle=step* (containerLength-1);
fields.each(function() {
var x = Math.round(width + radius * Math.cos(angle));
var y = Math.round(height + radius * Math.sin(angle));
$(this).css({
right: x + 'px',
top: y + 'px'
});
angle -= step;
});
}
var center = $('#center');
$(window).resize(function(height) {
$('#container').width($(window).height()*0.9)
$('#container').height($(window).height()*0.9)
var width = $('#container').width() * 0.4;
console.log("width",$('#container').width());
console.log("height",$('#container').height());
var radius = width/2;
width += 'px';
radius += 'px';
center.css({
width: width, height: width,
'-moz-border-radius' : radius,
'-webkit-border-radius' : radius,
'border-radius' : radius
});
createFields();
distributeFields();
// rest of your code for font-size setting etc..
});
$(window).resize();
$('input').change(function() {
createFields();
distributeFields();
});
I have achieved this with Canvas
context.fillStyle = '#00867F';
context.fill();
context.lineWidth = 1;
context.strokeStyle = '#F0EBF1';
context.stroke();
context.setLineDash([1,2]);
context.moveTo(lx, ly);
context.lineTo(nx, ny);

Categories