I'm attempting to randomly display 6 letters from the list letters in a circle. Currently I've adapted code that displays 6 divs with the class .field and provides a number (0-5) as an attribute to each field.
I'd like to randomly assign and display each letter (without repeating) within each field. However, I'm unsure about how to identify and splice into the list of fields (although I'm also unsure if splicing is the way to go). Does anyone have advice?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta charset="utf-8">
<title></title>
</head>
<style media="screen">
body {
padding: 2em;
}
#container {
width: 600px;
height: 600px;
border: 2px solid blue;
position: relative;
}
.field {
width: 100px;
height: 100px;
position: absolute;
border: 2px solid #f00;
}
.field:hover {
border: 2px solid blue;
}
#crosshair-x {
width: 100px;
height: 2px;
background: #000;
position: absolute;
right: 250px;
top: 300px;
}
#crosshair-y {
width: 2px;
height: 100px;
background: #000;
position: absolute;
left: 300px;
top: 250px;
}
</style>
<body>
Num: <input type="text" value="6" />
<div id="container">
<div id="center"></div>
<div id="crosshair-x"></div>
<div id="crosshair-y"></div>
</div>
</body>
<script type="text/javascript">
function createFields() {
var num = Math.floor(Math.random() * 6) + 1
$('.field').remove();
var container = $('#container');
for (var i = 0; i <
+$('input:text').val(); i++) {
$('<div />', {
'class': 'field',
'attribute': i,
'text': i,
}).appendTo(container);
}
}
function distributeFields() {
var ang = Math.floor(Math.random() * 360) + 0
var radius = 200;
var fields = $('.field'),
container = $('#container'),
width = container.width(),
height = container.height(),
angle = ang,
step = (2 * Math.PI) / fields.length;
fields.each(function() {
var x = Math.round(width / 2 + radius * Math.cos(angle) - $(this).width() / 2);
var y = Math.round(height / 2 + radius * Math.sin(angle) - $(this).height() / 2);
if (window.console) {
console.log($(this).text(), x, y);
}
$(this).css({
left: x + 'px',
top: y + 'px'
});
angle += step;
});
}
$('input').change(function() {
createFields();
distributeFields();
});
createFields();
distributeFields();
letters = ["A","B","C","D","E","F"]
</script>
</html>
I've adapted this code from #ThiefMaster (thank you!): Dynamically arrange some elements around a circle
Here is the thing you are looking for :
var letters;
function createFields() {
var num = Math.floor(Math.random() * 6) + 1
$('.field').remove();
var container = $('#container');
let fieldCount = $('input:text').val();
letters = ["A", "B", "C", "D", "E", "F"];
for (var i = 0; i < fieldCount; i++) {
let randomIndex = Math.floor(Math.random() * letters.length);
$('<div />', {
'class': 'field',
'attribute': i,
'text': letters[randomIndex],
}).appendTo(container);
letters.splice(randomIndex, 1);
}
}
function distributeFields() {
var ang = Math.floor(Math.random() * 360) + 0
var radius = 200;
var fields = $('.field'),
container = $('#container'),
width = container.width(),
height = container.height(),
angle = ang,
step = (2 * Math.PI) / fields.length;
fields.each(function() {
var x = Math.round(width / 2 + radius * Math.cos(angle) - $(this).width() / 2);
var y = Math.round(height / 2 + radius * Math.sin(angle) - $(this).height() / 2);
if (window.console) {
//console.log($(this).text(), x, y);
}
$(this).css({
left: x + 'px',
top: y + 'px'
});
angle += step;
});
}
$('input').change(function() {
createFields();
distributeFields();
});
createFields();
distributeFields();
body {
padding: 2em;
}
#container {
width: 600px;
height: 600px;
border: 2px solid blue;
position: relative;
}
.field {
width: 100px;
height: 100px;
position: absolute;
border: 2px solid #f00;
}
.field:hover {
border: 2px solid blue;
}
#crosshair-x {
width: 100px;
height: 2px;
background: #000;
position: absolute;
right: 250px;
top: 300px;
}
#crosshair-y {
width: 2px;
height: 100px;
background: #000;
position: absolute;
left: 300px;
top: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Num: <input type="text" value="6" />
<div id="container">
<div id="center"></div>
<div id="crosshair-x"></div>
<div id="crosshair-y"></div>
</div>
Related
I have a stormTrooper characters randomly placed around my circle called deathStar. I am trying to make my stormTroopers place in the location that my mouse clicks once they have already been clicked. But instead they are placing in random locations. I'm still having problems grasping the concept of getBoundingClientRect() and offset. I thought adding them together and subtracting from mouseClick would be the solution. I'm also open to any other advice for this project. The area I'm having problems with is the mouseDown event listener.
//Global variables
let deathStar = document.querySelector(".deathStar")
let counter = 0;
let darthVader = document.querySelector(".darthVader");
let vaderX = darthVader.offsetLeft;
let vaderY = darthVader.offsetTop;
//Death Star information
const x1 = window.scrollX + deathStar.getBoundingClientRect().left; // top left X
const y1 = window.scrollY + deathStar.getBoundingClientRect().top; // top left Y
const x2 = window.scrollY + deathStar.getBoundingClientRect().right; // bottom right X
const y2 = window.scrollY + deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
let radius = x2 - midPointX - 10;
//Create a storm trooper
function createStormTrooper(){
colorArray = ['blue', 'green', 'orange', 'yellow', 'white', 'red','purple', 'pink'];
counter++;
//create each div
let stormTrooper = document.createElement('div');
let body = document.createElement('div');
let gun = document.createElement('div');
let head = document.createElement('div');
let legSplit = document.createElement('div');
//append div to proper div
deathStar.append(stormTrooper);
stormTrooper.append(body);
body.append(gun);
body.append(head);
body.append(legSplit);
//add classes
stormTrooper.classList.add("trooper",'stormTrooperPart' + counter, "stormTrooper");
body.classList.add("trooper", 'stormTrooperPart' + counter, "body");
gun.classList.add("trooper", 'stormTrooperPart' + counter, "gun");
head.classList.add("trooper", 'stormTrooperPart' + counter, 'head');
legSplit.classList.add("trooper", 'stormTrooperPart' + counter, "legSplit");
let randomColor = Math.floor(Math.random()*8);
body.style.backgroundColor = colorArray[randomColor];
placeInsideDeathStar(stormTrooper);
}
//Places a trooper in a random spot inside the death star
function placeInsideDeathStar(stormTrooper){
let theta = Math.random() * Math.PI * 2;
let r = (Math.sqrt(Math.random()) * radius);
let yRandom = r * Math.sin(theta);
let xRandom = r * Math.cos(theta);
stormTrooper.style.transform = "translate(" + (xRandom) + "px," + (yRandom) + "px)";
}
//Create Troopers
for(let i = 0; i < 10;i++ ){
createStormTrooper();
}
let targetFound = false;
let stormTrooper;
//Storm Trooper placing and removing
document.addEventListener('mousedown', (e) => {
//variable to check if type stormtrooper
let typeTrooper = e.target.className.split(" ")[0];
//If type storm trooper of already have a target
if(typeTrooper == "trooper" || targetFound == true){
//if no stormTrooper found yet
if(targetFound == false){
stormTrooperChecker = document.querySelector("." + e.target.className.split(" ")[1]);
targetFound = true;
}
//if stormTrooper found
else{
//Distance to move stormTrooper
var xposition = (e.clientX - stormTrooperChecker.getBoundingClientRect().left + stormTrooperChecker.offsetLeft);
var yposition = (e.clientY - stormTrooperChecker.getBoundingClientRect().top + stormTrooperChecker.offsetTop);
//Move Storm Trooper
stormTrooperChecker.style.transform = "translate("+ (xposition)+ "px," + yposition + "px)";
//Check if outside of death star
if(pTheoremAB(stormTrooperChecker.offsetTop, stormTrooperChecker.offsetLeft) > pTheoremC(radius) || pTheoremAB(stormTrooperChecker.offsetTop, stormTrooperChecker.offsetLeft) < -pTheoremC(radius)){
stormTrooperChecker.classList.add("explosion")
stormTrooperChecker.innerHTML = "";
setTimeout(() => stormTrooperChecker.remove(), 1000);
}
//reset targetFound
targetFound = false;
}
//stormTrooperChecker.remove();
}
});
//P theorem
function pTheoremAB(a,b){
return ((a * a) + (b * b));
}
function pTheoremC(c){
return c * c;
}
function wDown(){
vaderY -= 2;
darthVader.style.top = vaderY + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderY +=2
}
}
function sDown(){
vaderY += 2;
darthVader.style.top = vaderY + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderY -= 2;
}
}
function aDown(){
vaderX -= 2;
darthVader.style.left = vaderX + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderX += 2;
}
}
function dDown(){
vaderX += 2;
darthVader.style.left = vaderX + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderX -= 2;
}
}
const controller = {
'w': {pressed: false},
'a': {pressed: false},
's': {pressed: false},
'd': {pressed: false},
}
document.addEventListener("keydown", (e) => {
if(controller[e.key]){
controller[e.key].pressed = true
}
if(controller['w'].pressed){
wDown();
}
if(controller['a'].pressed){
aDown();
}
if(controller['s'].pressed){
sDown();
}
if(controller['d'].pressed){
dDown();
}
})
document.addEventListener("keyup", (e) => {
if(controller[e.key]){
controller[e.key].pressed = false
}
})
body{
border: 0;
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.deathStar {
position: relative;
display:flex;
height: 700px;
width: 700px;
border-radius: 50%;
background-color: darkgrey;
top: 50%;
align-items: center;
justify-content: center;
}
.hole{
display: flex;
height: 100px;
width: 50px;
border-radius: 50%;
background-color: gray;
top: 50%;
transform: translateX(-60PX);
}
.stormTrooper{
display: flex;
position: absolute;
z-index: 2;
}
.body{
display: flex;
position: relative;
height: 30px;
width: 10px;
z-index: 2;
}
.head{
display: flex;
position: absolute;
height: 7px;
width: 7px;
transform: translate(0, 1px);
background-color: black;
}
.gun{
position: absolute;
display: flex;
height: 2px;
width: 10px;
background-color: black;
transform: translate(-9px, 10px)
}
.legSplit{
position: absolute;
display: flex;
width: 1px;
height: 8px;
background-color: black;
transform: translate(4px, 22px);
}
.darthVader{
display: flex;
position: absolute;
height: 30px;
width: 10px;
z-index: 3;
background-color: black;
}
.explosion{
position: absolute;
display: flex;
height: 0px;
width: 0px;
border-radius: 50%;
background-color: red;
transform: translate(80px, 80px);
animation-duration: 1s;
animation-name: move;
}
#keyframes move {
25% {
width: 10px;
height: 10px;
}
50% {
width: 20px;
height: 20px;
}
75% {
width: 30px;
height: 30px;
}
100% {
width: 40px;
height: 40px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="deathStar" id="deathStar">
<div class="darthVader"></div>
</div>
<div class="hole"></div>
<script src="main.js"></script>
</body>
</html>
The translate positioning is relative to the Death Star element's center, so I updated that.
translate does not affect offsetTop/Left, so your "in Death Star" logic was failing. I fixed that.
Also, you do not need to adjust for the scroll position (comes into effect only when scrolled). I fixed that.
Lastly, I had to put in some code in the handler to calculate the new midpoint of the Death Star element, as you only calculated it on initialization (it should be recalcuated on every use).
//Global variables
let deathStar = document.querySelector(".deathStar")
let counter = 0;
let darthVader = document.querySelector(".darthVader");
let vaderX = darthVader.offsetLeft;
let vaderY = darthVader.offsetTop;
//Death Star information
const x1 = deathStar.getBoundingClientRect().left; // top left X
const y1 = deathStar.getBoundingClientRect().top; // top left Y
const x2 = deathStar.getBoundingClientRect().right; // bottom right X
const y2 = deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
let radius = x2 - midPointX - 10;
//Create a storm trooper
function createStormTrooper(){
colorArray = ['blue', 'green', 'orange', 'yellow', 'white', 'red','purple', 'pink'];
counter++;
//create each div
let stormTrooper = document.createElement('div');
let body = document.createElement('div');
let gun = document.createElement('div');
let head = document.createElement('div');
let legSplit = document.createElement('div');
//append div to proper div
deathStar.append(stormTrooper);
stormTrooper.append(body);
body.append(gun);
body.append(head);
body.append(legSplit);
//add classes
stormTrooper.classList.add("trooper",'stormTrooperPart' + counter, "stormTrooper");
body.classList.add("trooper", 'stormTrooperPart' + counter, "body");
gun.classList.add("trooper", 'stormTrooperPart' + counter, "gun");
head.classList.add("trooper", 'stormTrooperPart' + counter, 'head');
legSplit.classList.add("trooper", 'stormTrooperPart' + counter, "legSplit");
let randomColor = Math.floor(Math.random()*8);
body.style.backgroundColor = colorArray[randomColor];
placeInsideDeathStar(stormTrooper);
}
//Places a trooper in a random spot inside the death star
function placeInsideDeathStar(stormTrooper){
let theta = Math.random() * Math.PI * 2;
let r = (Math.sqrt(Math.random()) * radius);
let yRandom = r * Math.sin(theta);
let xRandom = r * Math.cos(theta);
stormTrooper.style.transform = "translate(" + (xRandom) + "px," + (yRandom) + "px)";
}
//Create Troopers
for(let i = 0; i < 10;i++ ){
createStormTrooper();
}
let targetFound = false;
let stormTrooper;
//Storm Trooper placing and removing
document.addEventListener('mousedown', (e) => {
//variable to check if type stormtrooper
let typeTrooper = e.target.className.split(" ")[0];
//If type storm trooper of already have a target
if(typeTrooper == "trooper" || targetFound == true){
//if no stormTrooper found yet
if(targetFound == false){
stormTrooperChecker = document.querySelector("." + e.target.className.split(" ")[1]);
targetFound = true;
}
//if stormTrooper found
else{
//Distance to move stormTrooper
const x1 = deathStar.getBoundingClientRect().left; // top left X
const y1 = deathStar.getBoundingClientRect().top; // top left Y
const x2 = deathStar.getBoundingClientRect().right; // bottom right X
const y2 = deathStar.getBoundingClientRect().bottom; // top right Y
let midPointX = (x2 + x1) / 2;
let midPointY = (y2 + y1) / 2;
var xposition = (e.clientX - midPointX);
var yposition = (e.clientY - midPointY);
//Move Storm Trooper
stormTrooperChecker.style.transform = "translate("+ (xposition)+ "px," + yposition + "px)";
//Check if outside of death star
if(pTheoremAB(yposition, xposition) > pTheoremC(radius) || pTheoremAB(yposition, xposition) < -pTheoremC(radius)){
stormTrooperChecker.classList.add("explosion")
stormTrooperChecker.innerHTML = "";
setTimeout(() => stormTrooperChecker.remove(), 1000);
}
//reset targetFound
targetFound = false;
}
//stormTrooperChecker.remove();
}
});
//P theorem
function pTheoremAB(a,b){
return ((a * a) + (b * b));
}
function pTheoremC(c){
return c * c;
}
function wDown(){
vaderY -= 2;
darthVader.style.top = vaderY + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderY +=2
}
}
function sDown(){
vaderY += 2;
darthVader.style.top = vaderY + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderY -= 2;
}
}
function aDown(){
vaderX -= 2;
darthVader.style.left = vaderX + "px";
if(-pTheoremAB((vaderX - 345),(vaderY - 335)) <= -pTheoremC(radius)){
vaderX += 2;
}
}
function dDown(){
vaderX += 2;
darthVader.style.left = vaderX + "px";
if(pTheoremAB((vaderX - 345),(vaderY - 335)) >= pTheoremC(radius)){
vaderX -= 2;
}
}
const controller = {
'w': {pressed: false},
'a': {pressed: false},
's': {pressed: false},
'd': {pressed: false},
}
document.addEventListener("keydown", (e) => {
if(controller[e.key]){
controller[e.key].pressed = true
}
if(controller['w'].pressed){
wDown();
}
if(controller['a'].pressed){
aDown();
}
if(controller['s'].pressed){
sDown();
}
if(controller['d'].pressed){
dDown();
}
})
document.addEventListener("keyup", (e) => {
if(controller[e.key]){
controller[e.key].pressed = false
}
})
body{
border: 0;
background: black;
display: flex;
align-items: center;
justify-content: center;
}
.deathStar {
position: relative;
display:flex;
height: 700px;
width: 700px;
border-radius: 50%;
background-color: darkgrey;
top: 50%;
align-items: center;
justify-content: center;
}
.hole{
display: flex;
height: 100px;
width: 50px;
border-radius: 50%;
background-color: gray;
top: 50%;
transform: translateX(-60PX);
}
.stormTrooper{
display: flex;
position: absolute;
z-index: 2;
}
.body{
display: flex;
position: relative;
height: 30px;
width: 10px;
z-index: 2;
}
.head{
display: flex;
position: absolute;
height: 7px;
width: 7px;
transform: translate(0, 1px);
background-color: black;
}
.gun{
position: absolute;
display: flex;
height: 2px;
width: 10px;
background-color: black;
transform: translate(-9px, 10px)
}
.legSplit{
position: absolute;
display: flex;
width: 1px;
height: 8px;
background-color: black;
transform: translate(4px, 22px);
}
.darthVader{
display: flex;
position: absolute;
height: 30px;
width: 10px;
z-index: 3;
background-color: black;
}
.explosion{
position: absolute;
display: flex;
height: 0px;
width: 0px;
border-radius: 50%;
background-color: red;
transform: translate(80px, 80px);
animation-duration: 1s;
animation-name: move;
}
#keyframes move {
25% {
width: 10px;
height: 10px;
}
50% {
width: 20px;
height: 20px;
}
75% {
width: 30px;
height: 30px;
}
100% {
width: 40px;
height: 40px;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div class="deathStar" id="deathStar">
<div class="darthVader"></div>
</div>
<div class="hole"></div>
<script src="main.js"></script>
</body>
</html>
I understand that we need to use transform: rotate(ndeg); in order to rotate a specific element in CSS. In this case, I want to do it dynamically. Using jQuery, I want to rotate the box/container div when the user drags the handle (the red background) on n degrees as the user wishes. Is it possible in jQuery?
body {
padding: 50px;
}
.box_element {
border: 1px solid black;
width: 200px;
height: 200px;
position: relative;
z-index: -1;
}
.handle {
position: absolute;
bottom: -10px;
right: -10px;
width: 10px;
height: 10px;
border: 1px solid;
background: red;
z-index: 10;
}
<body>
<div class="box_element">
THIS IS TEST
<div class="handle"></div>
</div>
</body>
Here you need to write few code to make it possible, try live code https://codepen.io/libin-prasanth/pen/xxxzbLg
var stop,
active = false,
angle = 0,
rotation = 0,
startAngle = 0,
center = {
x: 0,
y: 0
},
R2D = 180 / Math.PI;
function start(e) {
e.preventDefault();
var bb = this.getBoundingClientRect(),
t = bb.top,
l = bb.left,
h = bb.height,
w = bb.width,
x,
y;
center = {
x: l + w / 2,
y: t + h / 2
};
x = e.clientX - center.x;
y = e.clientY - center.y;
startAngle = R2D * Math.atan2(y, x);
return (active = true);
}
function rotate(e) {
e.preventDefault();
var x = e.clientX - center.x,
y = e.clientY - center.y,
d = R2D * Math.atan2(y, x);
rotation = d - startAngle;
return (rot.style.webkitTransform = "rotate(" + (angle + rotation) + "deg)");
}
function stop() {
angle += rotation;
return (active = false);
}
rot = document.getElementById("draggable");
rot.addEventListener("mousedown", start, false);
window.addEventListener("mousemove", function(event) {
if (active === true) {
event.preventDefault();
rotate(event);
}
});
window.addEventListener("mouseup", function(event) {
event.preventDefault();
stop(event);
});
#draggable {
left: 50px;
top: 50px;
width: 100px;
height: 100px;
position: relative;
border: 1px solid #000;
}
#draggable:before{
content: "";
position: absolute;
bottom: -5px;
right: -5px;
width: 10px;
height: 10px;
background: #f00;
}
<div id="draggable">
</div>
You can make use of a css-variable and then change the value of the variable when clicked.
const box_element = document.getElementById('box_element');
const handle = document.getElementById('handle');
handle.addEventListener('click', function() {
let currentVal = getComputedStyle(box_element).getPropertyValue('--rotate_deg');
box_element.style.setProperty(
'--rotate_deg', ((parseInt(currentVal.replace('deg', '')) + 90) % 360) + 'deg');
});
:root {
--rotate_deg: 0deg;
}
.box_element {
margin: 1em;
border: 1px solid black;
width: 100px;
height: 100px;
position: relative;
z-index: -1;
transform: rotate(var(--rotate_deg))
}
.handle {
position: absolute;
bottom: -10px;
right: -10px;
width: 10px;
height: 10px;
border: 1px solid;
background: red;
z-index: 10;
cursor: pointer;
}
<div class="box_element" id="box_element">
THIS IS TEST
<div class="handle" id="handle"></div>
</div>
I want this div to go from point A to point B and vice-versa. Problem is the dist variable (distance) never gets to 0, it is usually either 1 or -1 (or some other range of values), which results in the div getting stuck and not going anywhere. In my complete code, point A and B positions are randomized every time I open the page.
The example below is reproducing the problem. To see it working as intended set #pointA { top: 5px; left: 5px; } | #pointB { top: 5px; left: 105px; }
var score = 0, points = 0, boxMode = 0, speed, speedX, speedY, angleRadians,
distX, distY, dist;
var destinationX = $("#pointB").position().left;
var destinationY = $("#pointB").position().top;
var pointAPos = $("#pointA").position();
var pointAx = pointAPos.left;
var pointAy = pointAPos.top;
var pointBPos = $("#pointB").position();
var pointBx = pointBPos.left;
var pointBy = pointBPos.top;
var boxPos = $('#box').position();
var boxX = pointAx;
var boxY = pointAy;
function calculateDistance(x, y) {
distX = boxX - x;
distY = boxY - y;
dist = Math.sqrt((distX*distX)+(distY*distY));
}
function boxMove() {
angleRadians = Math.atan2(-distX, -distY);
speed = 2;
speedX = speed * Math.sin(angleRadians);
speedY = speed * Math.cos(angleRadians);
document.getElementById("box").style.left = boxX + "px";
document.getElementById("box").style.top = boxY + "px";
boxX += speedX;
boxY += speedY;
}
function boxAI() {
calculateDistance(destinationX, destinationY);
if (!dist == 0) {
boxMove();
} else {
if (boxMode == 0) {
points += 1;
if (points == 50) {
// change destination to point A
destinationX = pointAx;
destinationY = pointAy;
boxMode = 1;
}
} else {
// change destination to point B
destinationX = pointBx;
destinationY = pointBy;
score += points;
points = 0;
boxMode = 0;
}
}
}
function mainLoop() {
boxAI();
$("#debug").html(points + " " + score + " " + boxMode);
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
#levelWrapper {
position: relative;
width: 400px;
height: 150px;
top: 2px;
margin: auto;
border: 1px solid red;
}
#pointA {
position: absolute;
background: beige;
width: 45px;
height: 45px;
top: 3px;
left: 50px;
margin: auto;
}
#pointB {
position: absolute;
background: beige;
width: 45px;
height: 45px;
top: 45px;
left: 195px;
margin: auto;
}
#box {
position: absolute;
background: black;
height: 5px;
width: 5px;
}
#debug {
position: relative;
background: white;
width: 250px;
height: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="debug"></div>
<div id="levelWrapper">
<div id="pointA">A</div>
<div id="pointB">B</div>
<div id="box"></div>
</div>
<script src="jquery-3.2.1.js"></script>
<script type="text/javascript" src="woods_2.js"></script>
</body>
In JavaScript the ! operator has precedence over the ==, so if (dist != 0) would already be an improvement.
But as you use a speed variable which determines the difference between two consecutive measurements of the distance, you should make your test accordingly, and see if the distance is one step removed from zero:
if (dist >= speed)
Here is your code with some changes:
var score = 0, points = 0, boxMode = 0, speed, speedX, speedY, angleRadians,
distX, distY, dist;
var destinationX = $("#pointB").position().left;
var destinationY = $("#pointB").position().top;
var pointAPos = $("#pointA").position();
var pointAx = pointAPos.left;
var pointAy = pointAPos.top;
var pointBPos = $("#pointB").position();
var pointBx = pointBPos.left;
var pointBy = pointBPos.top;
var boxPos = $('#box').position();
var boxX = pointAx;
var boxY = pointAy;
var speed = 2; // make speed visible to other functions
function calculateDistance(x, y) {
distX = boxX - x;
distY = boxY - y;
dist = Math.sqrt((distX*distX)+(distY*distY));
}
function boxMove() {
angleRadians = Math.atan2(-distX, -distY);
speedX = speed * Math.sin(angleRadians);
speedY = speed * Math.cos(angleRadians);
document.getElementById("box").style.left = boxX + "px";
document.getElementById("box").style.top = boxY + "px";
boxX += speedX;
boxY += speedY;
}
function boxAI() {
calculateDistance(destinationX, destinationY);
// As the distance makes jumps of <speed> units,
// check whether it is within one step of the target
if (dist >= speed) {
boxMove();
} else {
score++; // Not sure what score should be measuring
if (boxMode == 0) {
// Change destination to point A
destinationX = pointAx;
destinationY = pointAy;
boxMode = 1;
} else {
// Change destination to point B
destinationX = pointBx;
destinationY = pointBy;
boxMode = 0;
}
}
}
function mainLoop() {
boxAI();
$("#debug").html(points + " " + score + " " + boxMode);
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
#levelWrapper {
position: relative;
width: 400px;
height: 150px;
top: 2px;
margin: auto;
border: 1px solid red;
}
#pointA {
position: absolute;
background: beige;
width: 45px;
height: 45px;
top: 3px;
left: 50px;
margin: auto;
}
#pointB {
position: absolute;
background: beige;
width: 45px;
height: 45px;
top: 45px;
left: 195px;
margin: auto;
}
#box {
position: absolute;
background: black;
height: 5px;
width: 5px;
}
#debug {
position: relative;
background: white;
width: 250px;
height: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="debug"></div>
<div id="levelWrapper">
<div id="pointA">A</div>
<div id="pointB">B</div>
<div id="box"></div>
</div>
I did not understand what you wanted to do with score and points, so you will need to modify the code in that respect. For now I removed the changes to the points variable, and only increased score with every bounce.
I am using following link to show menus
http://codepen.io/anon/pen/dWdJbV
But I want to show them only in upper half circle. Even menu count changes it should use only upper half circle.
Js code
var items = document.querySelectorAll('.circle a');
for(var i = 0, l = items.length; i < l; i++) {
items[i].style.left = (50 - 35*Math.cos(-0.5 * Math.PI - 2*(2/l)*i*Math.PI)).toFixed(4) + "%";
items[i].style.top = (50 + 35*Math.sin(-0.5 * Math.PI - 2*(5/l)*i*Math.PI)).toFixed(4) + "%";
}
document.querySelector('.menu-button').onclick = function(e) {
e.preventDefault(); document.querySelector('.circle').classList.toggle('open');
}
I tried by changing values sin sin and cos but not getting required output
Here is the quick demo :
var isOn = false;
$('#menu-button').click(function() {
if(isOn) {
reset();
} else {
setPosition();
}
});
function setPosition() {
isOn = true;
var links = $('#menu-button a');
var radius = (links.length * links.width()) / 2;
var degree = Math.PI / links.length, angle = degree / 2;
links.each(function() {
var x = Math.round(radius * Math.cos(angle));
var y = Math.round(radius * Math.sin(angle));
$(this).css({
left: x + 'px',
top: -y + 'px'
});
angle += degree;
});
}
function reset() {
$('#menu-button a').css({
left: 0 + 'px',
top: 0 + 'px'
});
isOn = false;
}
body {
margin: 0;
background: #39D;
}
#menu-button:before {
position: absolute;
top: 0; left: 0;
width: 50px;
height: 50px;
background: #dde;
cursor: pointer;
text-align: center;
line-height: 50px;
color: #444;
border-radius:50%;
content:"\f0c9"; font: normal normal normal 14px/1 FontAwesome;
font-size:26px;
}
#menu-button {
position: absolute;
margin: auto;
top: 150px; left: 0; right: 0;
width: 50px;
height: 50px;
cursor: pointer;
text-align: center;
}
#menu-button > a {
position: absolute;
display: block;
width: 50px;
height: 50px;
-webkit-transition: top .5s, left .5s;
-moz-transition: top .5s, left .5s;
text-align: center;
text-decoration: none;
line-height: 50px;
color: #EBEAE8;
z-index: -1;
border-radius:50%;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Demo by http://creative-punch.net -->
<div id="menu-button" class="entypo-menu">
</div>
I made this changes in you example for displaying items only in top part of circle:
var items = document.querySelectorAll('.circle a');
var angle = 0;
var step = (Math.PI) / items.length;
for(var i = 0, l = items.length; i < l; i++) {
items[i].style.left = (50 - 35*Math.cos(angle).toFixed(4)) + "%";
items[i].style.top = (50 + 35* (-Math.abs(Math.sin(angle)))).toFixed(4) + "%";
angle += step;
}
So you need only angles from 0 to 180 degrees. That's why i use (-Math.abs(Math.sin(angle)))
On hover main image, the zoom image should display its properties like the specified width and height. Code is working but, the problem in zoom image on hover main image.
/* This is my script. I have used this for my code in this, marksize indicates id="mark" in my html main image and zoomImg indicates width and height for on hover the main image. */
$(function(){
$("#show").simpleZoom({
zoomBox : "#zoom",
markSize : \[120, 169\],
zoomSize : \[800, 400\],
zoomImg : \[480, 677\]
});
});
(function($){
$.fn.simpleZoom = function(options){
var defs = {
markSize : \[200, 100\],
zoomSize : \[400, 400\],
zoomImg : \[800, 800\]
};
var opt = $.fn.extend({}, defs, options);
return this.each(function(){
var markBox = $(this);
var zoomBox = $(opt.zoomBox);
var zoom_img = $(opt.zoomBox).find("img");
var markBoxSize = \[markBox.width(), markBox.height(), markBox.offset().left, markBox.offset().top\];
var markSize = opt.markSize;
var zoomSize = opt.zoomSize;
var zoomImg = opt.zoomImg;
var mark_ele = "<i id='mark'></i>";
var mark_css = {position:"absolute", top:0, left:0, width:markSize\[0\]+"px", height:markSize\[1\]+"px", backgroundColor:"#000", opacity:.5, filter:"alpha(opacity=50)", display:"none", cursor:"crosshair"};
var show_w = markBoxSize\[0\]-markSize\[0\];
var show_h = markBoxSize\[1\]-markSize\[1\];
//created mark element and add cascading style sheets
zoomBox.css({width:zoomSize\[0\]+"px", height:zoomSize\[1\]+"px"});
markBox.append(mark_ele);
$("#mark").css(mark_css);
markBox.mouseover(function(){
$("#mark").show();
zoomBox.show();
}).mouseout(function(){
$("#mark").hide();
zoomBox.hide();
}).mousemove(function(e){
var l = e.pageX-markBoxSize\[2\]-(markSize\[0\]/2);
var t = e.pageY-markBoxSize\[3\]-(markSize\[1\]/2);
if(l < 0){
l = 0;
}else if(l > show_w){
l = show_w;
}
if(t < 0){
t = 0;
}else if(t > show_h){
t = show_h;
}
$("#mark").css({left:l+"px", top:t+"px"});
var z_x = -(l/show_w)*(zoomImg\[0\]-zoomSize\[0\]);
var z_y = -(t/show_h)*(zoomImg\[1\]-zoomSize\[1\]);
zoom_img.css({left:z_x+"px", top:z_y+"px"});
});
});
}
})(jQuery);
#show {
width: 100%;
height: 400px;
overflow: hidden;
position: relative;
left: 0;
}
#show_mark {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 100px;
background-color: #000;
opacity: .5;
filter: alpha(opacity=50);
cursor: crosshair;
border: 1px solid #999;
display: none;
}
#zoom {
position: absolute;
left: 250px;
top: 0;
z-index: 99;
/*width: 400px;*/
height: 400px;
display: none;
overflow: hidden;
border: 1px solid #eee;
}
#zoom img {
position: absolute;
left: 0;
top: 0;
}
#show_pic{
display: block !important;
width: 60% !important;
height: 400px !important;
margin: 0 0 0 21%;
}
<div class="main">
<div id="show">
<img src="<?php echo 'data:image;base64,'.$productimage; ?>" id="show_pic" />
</div>
<div id="zoom">
<img src="<?php echo 'data:image;base64,'.$productimage; ?>"/>
</div>
</div>
The above shown is my image. Please refer and help me out soon.
Instead of the above code i have done with this and it's working fine.
HTML code
<div class="bzoom_wrap">
<ul id="bzoom">
<li>
<img class="bzoom_thumb_image" src="saree.jpeg" />
<img class="bzoom_big_image" src="saree.jpeg"/>
</li>
<li>
<img class="bzoom_thumb_image" src="saree1.jpeg"/>
<img class="bzoom_big_image" src="saree1.jpeg"/>
</li>
<li>
<img class="bzoom_thumb_image" src="saree2.jpeg"/>
<img class="bzoom_big_image" src="saree2.jpeg"/>
</li>
</ul>
</div>
Scripts i have used
<script type="text/javascript">
$("#bzoom").zoom({
zoom_area_width: 400,
autoplay_interval: 3000,
small_thumbs: 3,
autoplay: false
});
</script>
<script>
(function ($) {
$.fn.zoom = function (options) {
var _option = {
align: "left",
thumb_image_width: 380,
thumb_image_height: 400,
source_image_width: 450,
source_image_height: 450,
zoom_area_width: 400,
zoom_area_height: "justify",
zoom_area_distance: 10,
zoom_easing: true,
click_to_zoom: false,
zoom_element: "auto",
show_descriptions: true,
description_location: "bottom",
description_opacity: 0.7,
small_thumbs: 3,
smallthumb_inactive_opacity: 1,
smallthumb_hide_single: true,
smallthumb_select_on_hover: false,
smallthumbs_position: "bottom",
show_icon: true,
hide_cursor: false,
// speed: 600,
autoplay: true,
// autoplay_interval: 6000,
keyboard: true,
right_to_left: false,
}
if (options) {
$.extend(_option, options);
}
var $ul = $(this);
if ($ul.is("ul") && $ul.children("li").length && $ul.find(".bzoom_big_image").length) {
$ul.addClass('bzoom clearfix').show();
var $li = $ul.children("li").addClass("bzoom_thumb"),
li_len = $li.length,
autoplay = _option.autoplay;
$li.first().addClass("bzoom_thumb_active").show();
if (li_len < 2) {
autoplay = false;
}
$ul.find(".bzoom_thumb_image").css({width: _option.thumb_image_width, height: _option.thumb_image_height}).show();
var scalex = _option.thumb_image_width / _option.source_image_width,
scaley = _option.thumb_image_height / _option.source_image_height,
scxy = _option.thumb_image_width / _option.thumb_image_height;
var $bzoom_magnifier, $bzoom_magnifier_img, $bzoom_zoom_area, $bzoom_zoom_img;
if (!$(".bzoom_magnifier").length) {
$bzoom_magnifier = $('<li class="bzoom_magnifier"><div class=""><img src="" /></div></li>');
$bzoom_magnifier_img = $bzoom_magnifier.find('img');
$ul.append($bzoom_magnifier);
$bzoom_magnifier.css({top: top, left: left});
$bzoom_magnifier_img.attr('src', $ul.find('.bzoom_thumb_active .bzoom_thumb_image').attr('src')).css({width: _option.thumb_image_width, height: _option.thumb_image_height});
$bzoom_magnifier.find('div').css({width: _option.thumb_image_width * scalex, height: _option.thumb_image_height * scaley});
}
if (!$('.bzoom_zoom_area').length) {
$bzoom_zoom_area = $('<li class="bzoom_zoom_area"><div><img class="bzoom_zoom_img" /></div></li>');
$bzoom_zoom_img = $bzoom_zoom_area.find('.bzoom_zoom_img');
var top = 0,
left = 0;
$ul.append($bzoom_zoom_area);
if (_option.align == "left") {
top = 0;
left = 0 + _option.thumb_image_width + _option.zoom_area_distance;
}
$bzoom_zoom_area.css({top: top, left: left});
$bzoom_zoom_img.css({width: _option.source_image_width, height: _option.source_image_height});
}
var autoPlay = {
autotime: null,
isplay: autoplay,
start: function () {
if (this.isplay && !this.autotime) {
this.autotime = setInterval(function () {
var index = $ul.find('.bzoom_thumb_active').index();
changeLi((index + 1) % _option.small_thumbs);
}, _option.autoplay_interval);
}
},
stop: function () {
clearInterval(this.autotime);
this.autotime = null;
},
restart: function () {
this.stop();
this.start();
}
}
var $small = '';
if (!$(".bzoom_small_thumbs").length) {
var top = _option.thumb_image_height + 10,
width = _option.thumb_image_width,
smwidth = (_option.thumb_image_width / _option.small_thumbs) - 10,
smheight = smwidth / scxy,
ulwidth =
smurl = '',
html = '';
for (var i = 0; i < _option.small_thumbs; i++) {
smurl = $li.eq(i).find('.bzoom_thumb_image').attr("src");
if (i == 0) {
html += '<li class="bzoom_smallthumb_active"><img src="' + smurl + '" alt="small" style="width:' + smwidth + 'px; height:' + smheight + 'px;" /></li>';
} else {
html += '<li style="opacity:1;"><img src="' + smurl + '" alt="small" style="width:' + smwidth + 'px; height:' + smheight + 'px;" /></li>';
}
}
$small = $('<li class="bzoom_small_thumbs" style="top:' + top + 'px; width:' + width + 'px;"><ul class="clearfix" style="width: 485px;">' + html + '</ul></li>');
$ul.append($small);
$small.delegate("li", "click", function (event) {
changeLi($(this).index());
autoPlay.restart();
});
autoPlay.start();
}
function changeLi(index) {
$ul.find('.bzoom_thumb_active').removeClass('bzoom_thumb_active').stop().animate({opacity: 0}, _option.speed, function () {
$(this).hide();
});
$small.find('.bzoom_smallthumb_active').removeClass('bzoom_smallthumb_active').stop().animate({opacity: _option.smallthumb_inactive_opacity}, _option.speed);
$li.eq(index).addClass('bzoom_thumb_active').show().stop().css({opacity: 0}).animate({opacity: 1}, _option.speed);
$small.find('li:eq(' + index + ')').addClass('bzoom_smallthumb_active').show().stop().css({opacity: _option.smallthumb_inactive_opacity}).animate({opacity: 1}, _option.speed);
$bzoom_magnifier_img.attr("src", $li.eq(index).find('.bzoom_thumb_image').attr("src"));
}
_option.zoom_area_height = _option.zoom_area_width / scxy;
$bzoom_zoom_area.find('div').css({width: _option.zoom_area_width, height: _option.zoom_area_height});
$li.add($bzoom_magnifier).mousemove(function (event) {
var xpos = event.pageX - $ul.offset().left,
ypos = event.pageY - $ul.offset().top,
magwidth = _option.thumb_image_width * scalex,
magheight = _option.thumb_image_height * scalex,
magx = 0,
magy = 0,
bigposx = 0,
bigposy = 0;
if (xpos < _option.thumb_image_width / 2) {
magx = xpos > magwidth / 2 ? xpos - magwidth / 2 : 0;
} else {
magx = xpos + magwidth / 2 > _option.thumb_image_width ? _option.thumb_image_width - magwidth : xpos - magwidth / 2;
}
if (ypos < _option.thumb_image_height / 2) {
magy = ypos > magheight / 2 ? ypos - magheight / 2 : 0;
} else {
magy = ypos + magheight / 2 > _option.thumb_image_height ? _option.thumb_image_height - magheight : ypos - magheight / 2;
}
bigposx = magx / scalex;
bigposy = magy / scaley;
$bzoom_magnifier.css({'left': magx, 'top': magy});
$bzoom_magnifier_img.css({'left': -magx, 'top': -magy});
$bzoom_zoom_img.css({'left': -bigposx, 'top': -bigposy});
}).mouseenter(function (event) {
autoPlay.stop();
$bzoom_zoom_img.attr("src", $(this).find('.bzoom_big_image').attr('src'));
$bzoom_zoom_area.css({"background-image": "none"}).stop().fadeIn(400);
$ul.find('.bzoom_thumb_active').stop().animate({'opacity': 0.5}, _option.speed * 0.7);
$bzoom_magnifier.stop().animate({'opacity': 1}, _option.speed * 0.7).show();
}).mouseleave(function (event) {
$bzoom_zoom_area.stop().fadeOut(400);
$ul.find('.bzoom_thumb_active').stop().animate({'opacity': 1}, _option.speed * 0.7);
$bzoom_magnifier.stop().animate({'opacity': 0}, _option.speed * 0.7, function () {
$(this).hide();
});
autoPlay.start();
})
}
}
})(jQuery);
</script>
My style sheet
<style>
.bzoom { direction: ltr; }
.bzoom,
.bzoom_thumb,
.bzoom_thumb_image,
.bzoom_big_image,
.bzoom_zoom_preview,
.bzoom_icon,
.bzoom_hint { display: none }
.bzoom,
.bzoom ul,
.bzoom li,
.bzoom img,
.bzoom_hint,
.bzoom_icon,
.bzoom_description {
margin: 0;
padding: 0;
border: 0;
list-style: none;
}
.bzoom,
.bzoom_magnifier div,
.bzoom_magnifier div img,
.bzoom_small_thumbs ul,
ul .bzoom_small_thumbs li,
.bzoom_zoom_area div,
.bzoom_zoom_img { position: relative; }
.bzoom img,
.bzoom li {
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
-webkit-user-drag: none;
-moz-user-drag: none;
user-drag: none;
}
.bzoom,
.bzoom_small_thumbs li { float: left; }
.bzoom_right { float: right;}
.bzoom li {
position: absolute;
border: 1px solid #cfcece;
}
.bzoom img {
vertical-align: bottom;
width: 50px;
height: 70px;
border: 1px solid #eaeaea;
}
.bzoom .bzoom_zoom_area,
.bzoom_zoom_area {
background: #fff url(./img/loading.gif) center no-repeat;
border: 1px solid #ddd;
padding: 6px;
-webkit-box-shadow: 0 0 10px #ddd;
-moz-box-shadow: 0 0 10px #ddd;
box-shadow: 0 0 10px #ddd;
display: none;
z-index: 20;
}
.bzoom_zoom_area div { overflow: hidden; }
.bzoom_zoom_area .bzoom_zoom_img { position: absolute; }
.bzoom_wrap .bzoom_magnifier {
background: #fff;
outline: #bbb solid 1px;
display: none;
cursor: move;
}
.bzoom_magnifier div { overflow: hidden; }
.bzoom_wrap .bzoom_small_thumbs { overflow: hidden; }
.bzoom_wrap .bzoom_small_thumbs li {
border: 1px solid #FFF;
margin: 0px 10px 0px 0px;
position: relative;
border: 1px solid #cfcece;
}
.bzoom_wrap ul li.bzoom_smallthumb_active {
-webkit-box-shadow: 0 0 10px #ddd;
-moz-box-shadow: 0 0 10px #ddd;
box-shadow: 0 0 10px #ddd;
border: 1px solid #535353;
}
</style>