How leaflet loads tile maps for custom rules? - javascript

Now there is a map of custom tile rules locally. There is already a custom JavaScript library that can be called normally. Now I need to replace this library with leaflet. How to use the algorithm in the old JavaScript library and leaflet to make the tile map Normal call?
The tile map projection rule is Mercator projection. The tile size is irregular. The width is 256 pixels. The height is the same on each line, but the different line heights are different. The old JavaScript library defines the ellipsoid parameters. Various levels of scale, rank number calculation rules, etc., now want to use leaflet to load these tile maps, how to use the old rules and leaflet combination?
MapBase defines various basic parameters, loadMapImage is a key function
function LoadMapImage() {
var tileLoadInfo = mapBase.getViewInfo();
MapInfo.Map.basemapslicedlayer.empty();
for (var i = 0; i < tileLoadInfo.TileInfo.length; i++) {
if (MapInfo.Map.Tiles[tileLoadInfo.TileInfo[i].Col + "_" + tileLoadInfo.TileInfo[i].Row + "_" + tileLoadInfo.Mode] == undefined) {
if (tileLoadInfo.Mode == 6) {
var src = DNCOptions.url + "&" + DNCOptions.paramX + "=" + tileLoadInfo.TileInfo[i].Row + "&" + DNCOptions.paramY + "=" + tileLoadInfo.TileInfo[i].Col + "&" + DNCOptions.paramZ + "=" + tileLoadInfo.TileInfo[i].Level + "&SessionID=" + WinfoDNCSessionID
} else if (tileLoadInfo.Mode == 8 || tileLoadInfo.Mode == 9) {
var level = tileLoadInfo.Level + 2;
if (tileLoadInfo.Mode == 9) {
level = tileLoadInfo.Level - 3
}
src = MapInfo.ServicePath + "?REQUEST=GetMap&SERVICE=CacheMap&Y=" + tileLoadInfo.TileInfo[i].Col + "&X=" + tileLoadInfo.TileInfo[i].Row + "&LEVEL=" + level + "&LAYERS=" + DNCOptions.layername + "&SessionID=" + WinfoDNCSessionID
} else {
var src = MapInfo.ServicePath + "?REQUEST=GetMap&SERVICE=WINFODNC&X=" + tileLoadInfo.TileInfo[i].Col + "&Y=" + tileLoadInfo.TileInfo[i].Row + "&LEVEL=" + tileLoadInfo.Level + "&LAYERS=" + tileLoadInfo.Mode + "&SessionID=" + WinfoDNCSessionID
}
MapInfo.Map.Tiles[tileLoadInfo.TileInfo[i].Col + "_" + tileLoadInfo.TileInfo[i].Row + "_" + tileLoadInfo.Mode] = w$("<img>").css({
position: "absolute",
left: tileLoadInfo.TileInfo[i].Offset_x,
top: tileLoadInfo.TileInfo[i].Offset_y
}).attr("src", src)
}
MapInfo.Map.basemapslicedlayer.append(MapInfo.Map.Tiles[tileLoadInfo.TileInfo[i].Col + "_" + tileLoadInfo.TileInfo[i].Row + "_" + tileLoadInfo.Mode].css({
position: "absolute",
left: tileLoadInfo.TileInfo[i].Offset_x,
top: tileLoadInfo.TileInfo[i].Offset_y
}))
}
}
function GetTileInfoByViewportParam(vp) {
var Box = {};
var i, row1, row2, col1, col2, hTileSize;
var L, R, T, B;
var LT = ScreenPoint2Coordinate(vp, 0, 0);
Box.Top = LT[0];
Box.Left = LT[1];
var RB = ScreenPoint2Coordinate(vp, vp.Width, vp.Height);
Box.Bottom = RB[0];
Box.Right = RB[1];
var rc = CalculateTile(LevelZeroTileSizeDegrees, Box, vp.Level);
row1 = rc[0];
row2 = rc[2];
col1 = rc[1];
col2 = rc[3];
var LRTB = CalculateTileExtend(LevelZeroTileSizeDegrees, vp.Level, row1, col1);
L = LRTB[0];
R = LRTB[1];
T = LRTB[2];
B = LRTB[3];
var Offset = Coordinate2ScreenPoint(vp, T, L);
vp.Offset_x = Offset[0];
vp.Offset_y = Offset[1];
MapViewInfo.Level = vp.Level;
MapViewInfo.Box = Box;
i = 0;
var offsety = vp.Offset_y;
MapViewInfo.TileInfo = [];
for (var j = row1; j >= row2; j--) {
hTileSize = CalculateTileSize(vp.Level, j, col1);
var offsetx = vp.Offset_x;
for (var z = col1; z <= col2; z++) {
var tileInfo = {};
tileInfo.Row = j;
tileInfo.Col = z;
tileInfo.Height = hTileSize;
tileInfo.Widht = TileSize;
tileInfo.Offset_x = offsetx;
tileInfo.Offset_y = offsety;
offsetx += TileSize;
MapViewInfo.TileInfo[i] = tileInfo;
i++
}
offsety += hTileSize
}
return MapViewInfo
};
According to the default initialization map method of leaflet, the parameters can only be retrieved to the blank tile.

Related

"for" in wrong loop .js

I'm having some problem with this function. I ask sorry if the code looks a bit confused.
Basically what i'm trying to do is to divide some elements between the top and bottom of the documents having between them the same space circa.
i wrote this code but seems like the first "for" cycle goes loop ever and ever again.
** update**
so i improved the code and now the problem seems to be the variable "ifc"(if-counter). It suppose to increase by one every time that one of the if or else if is completed , but as you can see on the console it always remain 0 .
anyone can help?
thanks
var sizewidth = window.innerWidth;
var sizeheight = 3000;
function initialPosition(){
var els = document.querySelectorAll('.ico');
var tb = Math.round(els.length * 0.4);
console.log(tb);
var lr = els.length - tb;
var distPixEachTopBottom = sizewidth / (tb/2);
console.log(distPixEachTopBottom);
var distPixEachLefRight = sizeheight / (lr/2);
var nextTop = 0;
var nextLeft = 0;
var nextBottom = 0;
var nextRight = 0 ;
for (i = 0; i < els.length; i++) {
var ifc = 0;
console.log('i' + i);
if(i < tb){
var sf = 0;
for(;;){
console.log('sf' + sf + 'tb ' + tb);
if(ifc > 1){
console.log('ifc'+ ifc);
ifc = 0;
break
}else if(ifc == 0){
els[i].style.top = 0 +'px';
els[i].style.left = nextTop + 'px';
console.log('ifc ' + ifc + 'i ' + i + 'nexttop' + nextTop)
nextTop = nextTop + distPixEachTopBottom;
ifc++;
break;
}else if(ifc == 1){
els[i].style.bottom = 0 +'px';
els[i].style.right = nextBottom + 'px';
console.log('ifc ' + ifc + 'i ' + i + 'nextbottom' + nextBottom)
nextBottom = nextBottom + distPixEachTopBottom;
ifc++;
break;
}else{
console.log('else if problem')
break;
}
}
}else{
}
}
initialPosition();
update
i created a pen as you asked
codepen
So basically of all the boxes the 40% of them (6 in this case) should be divided between top and bottom but they go just on top.
So I solved by myself .
I put the var ifc before then any function .
Anyway thanks everyone

How to calculate `lib.ema` starting from the previous period?

Hi I need to calculate EMA in Zenbot, but starting from the previous period, how does one do that?
return function ema (s, key, length, source_key) {
if (!source_key) source_key = 'close'
if (s.lookback.length >= length) {
var prev_ema = s.lookback[0][key]
if (typeof prev_ema === 'undefined' || isNaN(prev_ema)) {
var sum = 0
s.lookback.slice(0, length).forEach(function (period) {
sum += period[source_key]
})
prev_ema = sum / length
}
var multiplier = 2 / (length + 1)
s.period[key] = (s.period[source_key] - prev_ema) * multiplier + prev_ema
}
}
}
Recently figured out the same thing, you can use this commit as a reference.
+++ b/extensions/strategies/wavetrend/strategy.js
## -0,0 +1,172 ##
...
+ onPeriod: function (s, cb) {
+ if (s.period.wto) {
+ s.signal = null // hold
+ let prev_wto = s.lookback[0].wto
+ let wto = s.period.wto
+ let prev_hcl3 = s.lookback[0].hcl3
+ let hcl3 = s.period.hcl3
+ let prev_ema = s.lookback[0].ema
+ let ema = s.period.ema
+
+ if (!s.sell_signal_close)
+ s.sell_signal_close = 0
+ if (!s.buy_signal_close)
+ s.buy_signal_close = 0
+ if (!s.sell_pct_orig)
+ s.sell_pct_orig = s.sell_pct
+ if (!s.buy_pct_orig)
+ s.buy_pct_orig = s.sell_pct

state in react is returning back to the original value

I'am trying to implement a rogue like dungeon crawler game in react,I render the map before component mounts once and i later re-render the level using levelRender() function,but my state is returning back to its orginal value which is set by componentWillMount() function.Debugging shows that state is being chaged by levelRender() function but at end it returns to original state,which i think shouldn't be happening.I know my code is bit long but i guess problem lies with way i call componentWillMount() and levelRender() function.
In the game,brown box is the portal which should trigger the levelRender,when it is run over by player which is red box.
here is link to my codepen,use arrow keys to move around :)
const Map = React.createClass({
getInitialState() {
return {
width: 40,
height: 50,
wallRender: 0,
gameLevel: 0,
Probabilities: {
levelA: [3, 5, 2],
levelB: [3.5, 3, 3.5],
levelC: [8, 1, 1]
}
}
},
componentWillMount() {
document.addEventListener("keydown", this.handleKeyDown, false);
var map = [];
var rooms = [];
var render = [];
var level = this.state.gameLevel;
//use rot.js to generate map
var w = this.state.width,
h = this.state.height;
var objects = ["e", "h", "w"];
var probability;
var enemies = [];
var weapon = [];
var health = []
if (level == 0) {
probability = this.state.Probabilities.levelA;
} else if (level == 1) {
probability = this.state.Probabilities.levelB;
} else {
probability = this.state.Probabilities.levelC;
}
// var map = new ROT.Map.Digger();
var data = {};
var rotMap = new ROT.Map.Rogue(w, h);
var display = new ROT.Display({ width: w, height: h, fontSize: 6 });
rotMap.create(function (x, y, type) {
data[x + "," + y] = type;
display.DEBUG(x, y, type);
})
map = rotMap.map;
var rooms = rotMap.rooms;
// console.log(map);
// console.log(rooms)
var playerPosition = [rooms[0][0].x + 1, rooms[0][0].y + 1];
var portalPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
// console.log(playerPosition)
map[playerPosition[0]][playerPosition[1]] = "p";
map[portalPosition[0]][portalPosition[1]] = "*";
var pp = playerPosition;
//
// set up enemies and health
rooms.map(function (rooms) {
rooms.map(function (room) {
var rx = room.x; var ry = room.y;
var noe = Math.floor(Math.random() * ((1 + 2) - 2 + 1)) + 2;
for (var i = 0; i < noe; i++) {
// generate enemy postions
var ex = Math.floor(Math.random() * ((room.width + rx) - rx + 1)) + rx;
var ey = Math.floor(Math.random() * ((room.height + ry) - ry + 1)) + ry;
if ((ex >= rx && ex < room.width + rx) && (ey >= ry && ey < room.height + ry)) {
var totalProbability = eval(probability.join("+"));//get total weight (in this case, 10)
var weighedObjects = new Array();//new array to hold "weighted" fruits
var currentObject = 0;
while (currentObject < objects.length) {
for (i = 0; i < probability[currentObject]; i++)
weighedObjects[weighedObjects.length] = objects[currentObject]
currentObject++
}
var randomnumber = Math.floor(Math.random() * totalProbability)
var x = weighedObjects[randomnumber];
if (x == 'e') {
map[ex][ey] = "e";
var stats = {
loc: ex + " " + ey,
health: 50,
damage: 20
}
enemies.push(stats)
} else if (x == 'h') {
map[ex][ey] = "h";
var stats = {
loc: ex + " " + ey,
boost: 80
}
health.push(stats)
} else if (x == 'w') {
map[ex][ey] = "w";
var stats = {
loc: ex + " " + ey,
damageBoost: 40
}
weapon.push(stats)
}
// console.log(ex + " " + ey + " " + (room.width + rx) + " " + (room.height + ry))
}
}
})
})
// place enemy
// console.log(enemies);
// console.log(health);
// console.log(weapon)
// setup field of view
var fov = this.setFov(pp)
this.setState({
gameState: map,
gameRooms: rooms,
playerPosition: playerPosition,
playerHealth: 50,
playerDamage: 5,
portalPosition: portalPosition,
fov: fov,
enemies: enemies,
health: health,
weapon: weapon
});
},
levelRender(){
console.log("level rendered")
var map = [];
var rooms = [];
var render = [];
var level=this.state.gameLevel;
//use rot.js to generate map
var w = this.state.width,
h = this.state.height;
var objects = ["e", "h", "w"];
var probability;
var enemies = [];
var weapon = [];
var health = []
if (level == 0) {
probability = this.state.Probabilities.levelA;
} else if (level == 1) {
probability = this.state.Probabilities.levelB;
} else {
probability = this.state.Probabilities.levelC;
}
// var map = new ROT.Map.Digger();
var data = {};
var rotMap = new ROT.Map.Rogue(w, h);
var display = new ROT.Display({ width: w, height: h, fontSize: 6 });
rotMap.create(function (x, y, type) {
data[x + "," + y] = type;
display.DEBUG(x, y, type);
})
map = rotMap.map;
var rooms = rotMap.rooms;
var playerPosition = [rooms[0][0].x + 1, rooms[0][0].y + 1];
if(level==0 || level ==1){
var portalPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
map[portalPosition[0]][portalPosition[1]] = "*";
}else{
var bossPosition = [rooms[2][2].x + 2, rooms[2][2].y + 2];
map[portalPosition[0]][portalPosition[1]] = "boss";
}
map[playerPosition[0]][playerPosition[1]] = "p";
var pp = playerPosition;
//
// set up enemies and health
rooms.map(function (rooms) {
rooms.map(function (room) {
var rx = room.x; var ry = room.y;
var noe = Math.floor(Math.random() * ((1 + 2) - 2 + 1)) + 2;
for (var i = 0; i < noe; i++) {
// generate enemy postions
var ex = Math.floor(Math.random() * ((room.width + rx) - rx + 1)) + rx;
var ey = Math.floor(Math.random() * ((room.height + ry) - ry + 1)) + ry;
if ((ex >= rx && ex < room.width + rx) && (ey >= ry && ey < room.height + ry)) {
var totalProbability = eval(probability.join("+"));//get total weight (in this case, 10)
var weighedObjects = new Array();//new array to hold "weighted" fruits
var currentObject = 0;
while (currentObject < objects.length) {
for (i = 0; i < probability[currentObject]; i++)
weighedObjects[weighedObjects.length] = objects[currentObject]
currentObject++
}
var randomnumber = Math.floor(Math.random() * totalProbability)
var x = weighedObjects[randomnumber];
if (x == 'e') {
map[ex][ey] = "e";
var stats = {
loc: ex + " " + ey,
health: 50,
damage: 20
}
enemies.push(stats)
} else if (x == 'h') {
map[ex][ey] = "h";
var stats = {
loc: ex + " " + ey,
boost: 80
}
health.push(stats)
} else if (x == 'w') {
map[ex][ey] = "w";
var stats = {
loc: ex + " " + ey,
damageBoost: 40
}
weapon.push(stats)
}
// console.log(ex + " " + ey + " " + (room.width + rx) + " " + (room.height + ry))
}
}
})
})
// setup field of view
var fov = this.setFov(pp)
console.log(this.state.gameState)
this.setState({
gameState: map,
gameRooms: rooms,
playerPosition: playerPosition,
bossPosition:bossPosition,
portalPosition: portalPosition,
fov: fov,
enemies: enemies,
health: health,
weapon: weapon
});
console.log(this.state.gameState)
},
setFov(playerPos) {
var pp = playerPos;
var fov = [];
var x = pp[0]; var y = pp[1];
fov.push(x - 2 + "," + (y - 1)); fov.push(x - 2 + "," + y); fov.push(x - 2 + "," + (y + 1));
fov.push(x - 1 + "," + (y - 2)); fov.push(x - 1 + "," + (y - 1)); fov.push(x - 1 + "," + y); fov.push(x - 1 + "," + (y + 1)); fov.push(x - 1 + "," + (y + 2));
fov.push(x + "," + (y - 2)); fov.push(x + "," + (y - 1)); fov.push(x + "," + y); fov.push(x + "," + (y + 1)); fov.push(x + "," + (y + 2));
fov.push(x + 1 + "," + (y - 2)); fov.push(x + 1 + "," + (y - 1)); fov.push(x + 1 + "," + y); fov.push(x + 1 + "," + (y + 1)); fov.push(x + 1 + "," + (y + 2));
fov.push(x + 2 + "," + (y - 1)); fov.push(x + 2 + "," + y); fov.push(x + 2 + "," + (y + 1));
fov.push(x - 3 + "," + y); fov.push(x + 3 + "," + y); fov.push(x + "," + (y - 3)); fov.push(x + "," + (y + 3))
return fov;
},
handleKeyDown(e) {
// left arrow
var playerLoc = this.state.playerPosition;
if (e.keyCode == 37) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x)][(y - 1)] == 0 || map[(x)][(y - 1)] == "w" || map[(x)][(y - 1)] == "h" || map[(x)][(y - 1)] == "*") {
if (map[(x)][(y - 1)] == "*") {
var level = this.state.gameLevel + 1;
this.setState({
gameLevel:level
})
this.levelRender();
}
if (map[(x)][(y - 1)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x)][(y - 1)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x)][(y - 1)] = "p";
playerPos[0] = x
playerPos[1] = y - 1;
}
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// up arrow
if (e.keyCode == 38) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x - 1)][(y)] == 0 || map[(x - 1)][(y)] == "w" || map[(x - 1)][(y)] == "h") {
// update player health and damage
if (map[(x - 1)][(y)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x - 1)][(y)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x - 1)][(y)] = "p";
playerPos[0] = x - 1
playerPos[1] = y;
}
// console.log(map)
// console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// right arrow
if (e.keyCode == 39) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
// console.log(map)
// console.log(playerPos)
if (map[(x)][(y + 1)] == 0 || map[(x)][(y + 1)] == "w" || map[(x)][(y + 1)] == "h") {
// update player health and damage
if (map[(x)][(y + 1)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x)][(y + 1)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x)][(y + 1)] = "p";
playerPos[0] = x
playerPos[1] = y + 1;;
}
//console.log(map)
//console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
// down arrow
if (e.keyCode == 40) {
var map = this.state.gameState;
var playerPos = this.state.playerPosition;
var x = playerPos[0], y = playerPos[1];
if (map[(x + 1)][(y)] == 0 || map[(x + 1)][(y)] == "w" || map[(x + 1)][(y)] == "h") {
// update player health and damage
if (map[(x + 1)][(y)] == "h") {
var health = this.state.playerHealth + 30;
this.setState({
playerHealth: health
})
}
if (map[(x + 1)][(y)] == "w") {
var damage = this.state.playerDamage + 20;
this.setState({
playerDamage: damage
})
}
map[x][y] = 0;
map[(x + 1)][(y)] = "p";
playerPos[0] = x + 1
playerPos[1] = y;
}
// console.log(map)
// console.log(playerPos)
// change fov
var pp = playerPos;
var fov = this.setFov(pp)
this.setState({
gameState: map,
playerPosition: playerPos,
fov: fov
})
}
},
render() {
// rendering map
var map = this.state.gameState;
var fov = this.state.fov;
if(this.state.gameLevel==1){
console.log(map)
}
var render = [];
for (var i = 0; i < this.state.width; i++) {
var dummy = [];
for (var j = 0; j < this.state.height; j++) {
var arena = { background: "white", color: "white" };
var wallColor = "grey";
var wall = { background: wallColor, color: wallColor, border: "2px solid black" };
var enemy = { background: "blue", color: "blue" };
var player = { background: "red", color: "red" };
var health = { background: "green", color: "green" }
var weapon = { background: "orange", color: "orange" }
var portal = { background: "brown", color: "brown" }
var boss ={background:"yellow",color:"yellow"}
// check if cell is in fov
var val = i + "," + j;
if (map[i][j] == 0) {
// implement field of view
var x = arena;
// if (fov.includes(val)) {
// x.visibility = "visible";
// console.log(val)
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={x}>00;</td>);
} else if (map[i][j] == "p") {
dummy.push(<td style={player}>00;</td>);
} else if (map[i][j] == "e") {
var x = enemy;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td border={5} style={enemy}>00;</td>);
} else if (map[i][j] == "h") {
var x = health;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={health}>00;</td>);
} else if (map[i][j] == "*") {
var x = portal;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={portal}>00;</td>);
}
else if (map[i][j] == "w") {
var x = weapon;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={weapon}>00;</td>);
}else if (map[i][j] == "boss") {
var x = boss;
// if (fov.includes(val)) {
// x.visibility = "visible";
// } else {
// x.visibility = "hidden";
// }
dummy.push(<td style={boss}>00;</td>);
}
else {
var x = wall;
// if (fov.includes(val)) {
// x.visibility = "visible";
// // console.log(val)
// } else {
// x.visibility = "hidden";
// }
// generate random hue of colors
dummy.push(<td style={wall}>00;</td>);
}
}
render.push(<tr>{dummy}</tr>);
}
return (
<div>
<div id="info">
<span id="health">Health:{this.state.playerHealth} </span>
<span id="damage">Damage:{this.state.playerDamage} </span>
<span id="message">{this.state.playerMessage}</span>
</div>
<div id="gameArea" tabIndex="0" >
<table align="right">
{render}
</table>
</div>
</div>
)
}
})
ReactDOM.render(<Map />, document.getElementById("app"));
You are setting the state in levelRender and overwriting the same with the previous state.
On line 452, this.leverRender is being invoked, which actually sets the new game state (desired). Later, on line 485, state is being overwritten with the variable map which has got the old values, which is responsible for the undesired output. This has to be resolved by setting the state only once, or setting it twice but with updated values of map.

JQuery SVG not working

I am trying to create a circular page with tabs around it and the SVG path are not being appended to the html.
Any help would be grateful. I have not worked with JS in a long time since I have moved on to Java so my skills are rusty.
var tabs = 10;
var radius = 500;
var xcords = [];
for (var i = 1; i <= tabs; i++) {
xcords[xcords.length] = radius + Math.cos(36 * i + 18) * radius;
}
var ycords = [];
for (var i = 1; i <= tabs; i++) {
ycords[ycords.length] = radius + Math.sin(36 * i + 18) * radius;
}
$(document).ready(function(){
for (var i = 1; i < tabs; i++) {
$(".svg").prepend("<path class='piece' />");
$(".piece").attr({
"d" : "M" + xcords[i] + "," + ycords[i] + "L500,500 L" + xcords[i + 1] + "," + ycords[i + 1] " A500,500 0 0,0 " + xcords[i] + "," + ycords[i] + " Z"
});
}
$(".piece").mouseenter(function() {
$(this).fadeTo(100, 0.7);
});
$(".piece").mouseleave(function() {
$(this).fadeTo(100, 1);
});
$(".piece").click(function() {
$(".center").attr("fill",$(this).attr("fill"));
});
});
I know that the array id not large enough to get xcords[11] but a solution to it would be helpful.

Get X/Y Coordinates with Mouseclick

I am trying to get X/Y coordinates from a div with a mouseclick.
I allready use this script:
Now I want to collect more X/Y coordinates, not just one.
so if I click in the div twice or more times, I want to list the coordinates under the div.
<div>"click"
"click"</div>
------------------------
coordinates 1: X/Y
coordinates 2: X/Y
.
.
.
Does anyone know how I do that?
Here's exactly what you asked for.
Fiddle: http://jsfiddle.net/ZZEk8/118/
Add to HTML:
<span class="log"></span>
JS:
var clicks = [],
updatedClicks = "";
$('.clickable').on('click', function (ev) { //We don't use .bind() after jQuery 1.7, use .on() now.
var $div = $(ev.target);
var $display = $div.find('.display');
var offset = $div.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
$display.text('x: ' + x + ', y: ' + y);
clicks.push(x + "/" + y);
updatedClicks += "coordinates" + " " + clicks.length + ":" + " " + clicks[clicks.length -1] + "<br />";
$('.log').html(updatedClicks);
});
UPDATE:
OP requested a way to limit the coords and delete one.
Fiddle: http://jsfiddle.net/ZZEk8/125/
var clicks = [],
updatedClicks = [],
limit = 5;
$('.clickable').on('click', function (ev) {
var $div = $(ev.target);
var $display = $div.find('.display');
var offset = $div.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
$display.text('x: ' + x + ', y: ' + y);
//Stops adding at limit
if (clicks.length < limit){
addCoord(x,y);
}
});
$('.delete').on('change', function(ev) {
if(clicks.length){
var selection = this.value -1;
deleteCoord(selection);
} else { //If there are no coords to delete run this
return false;
}
});
function addCoord (x,y){
clicks.push(x + "/" + y);
updatedClicks.push("Coordinates" + ":" + " " + clicks[clicks.length -1] + "<br />");
$('.log').html(updatedClicks.join(" "));
}
function deleteCoord(selection) {
clicks.splice(selection, 1);
updatedClicks.splice(selection, 1);
$('.log').html(updatedClicks.join(" "));
}
Add a new element <div id="log"></div> after your existing element.
In your JavaScript code add
document.getElementById("log").innerHTML += "<br/>Coordinates: X=" + x + "; Y=" + y;
In your jsfiddle example:
$display.html($display.html() + '<br/> x: ' + x + ', y: ' + y);
I do it using div elements, but you can change it.
See fiddle
My JS change is
$display.append($('<div />').text('x: ' + x + ', y: ' + y));
And in HTML
<div class='clickable'>
<div class='display'></div>
</div>
Or this one, with a srollbar when needed.
If you want to save coordinates, you can collect them in an array, like this:
//Declare an array with 0 length
var arr = new Array(0);
$('.clickable').bind('click', function (ev) {
var $div = $(ev.target);
var $display = $div.find('.display');
var offset = $div.offset();
var x = ev.clientX - offset.left;
var y = ev.clientY - offset.top;
$display.text('x: ' + x + ', y: ' + y);
//increase the length of array before insert the value of coords
arr.length = arr.length+1;
//insert the value
arr[arr.length-1] = "coordinates" + arr.length + ":" + x +"/" + y;
});
Then, to operate coordinates you can tour your array with for-loop

Categories