in my user.data.crop_position value is "[ 100, 100, 200, 200 ]";
var crop_position=user.data.crop_position.slice(1,user.data.crop_position.length-2);
$('#cropbox').Jcrop({
setSelect: crop_position,
onChange: showPreview,
onSelect: showPreview,
aspectRatio: 1
});
doing this my jcrop is not select at set postion what can i do
it is due to the string i am passing in how can i remove this ,
i know this is silly question but i got these kind of problem many time also please suggest me that in future these kind of problem dont came.
regards
rahul
The Jcrop Manual says that setSelect takes an array, not a string.
[100, 100, 200, 200] // rather than
'[100, 100, 200, 200]'
If you can't change the input format, at least you can parse it using $.parseJSON before passing it to Jcrop:
var crop_position = $.parseJSON(user.data.crop_position);
Edit: If necessary (double quotes are actually present in the string value), you can use $.parseJSON twice, first to decode the encoded string value and second to decode the array within the encoded string:
var crop_position = $.parseJSON($.parseJSON(user.data.crop_position));
Or just strip off the surrounding double quotes before $.parseJSON:
var crop_position = $.parseJSON(user.data.crop_position.slice(1, -1));
setSelect - array [ x, y, x2, y2 ] Set an initial selection area
So you need an array not a string for setSelect. Why don't you make user.data.crop_position an array itself? If there is no way to change the representation you can do the conversion with a simple algorithm:
var pos = '"[ 100, 100, 200, 200 ]"'; // user.data.crop_position
var crop_position = pos.replace(/["\[\] ]/g, '').split(',');
for (var i = crop_position.length; i--;) {
crop_position[i] = +crop_position[i];
}
Now you've got an array of values instead of a string.
Related
Just trying to get my head around using react and aframe together with the spread operator etc.
So I have an Entity using Meshline
<Entity meshline="lineWidth: 20; path: -2 -1 0, 0 -2 0, 2 -1; color: #E20049" />
I'm trying to make that path string dynamic with 2 objects i.e. something like
buttonConfig.position = {
x:config.position.x-3,
y:config.position.y+3,
z:config.position.z,
}
lineX = {
lineWidth : 20,
path: {...config.position,...buttonConfig.position},
color: '#ffffff',
}
But that's obviously not working because I get a
TypeError: value.split is not a function
How do I turn that object into a string of values via AFRAME/React? Or am I trying to be too clever here and should just build the string?
Although the component should be taking object arrays as its input, it seems to always parse the path with its parse() function (64th line).
I've tried with [{x,y,z},{x,y,z}], but with no luck.
The workaround is easy though: the AFRAME.utils.coordinates.stringify function, which turns an {x,y,z} object into a "x y z" string.
So having an array of coordinate objects, you can get Your coords with one forEach:
array.forEach((el, index)=>{
stringified += AFRAME.utils.coordinates.stringify(el)
if(index != array.length - 1) {
stringified +=","
}
}
and use the stringified as Your meshline path.
It's a bit late, but i've managed to get a working fiddle.
If I set a variable like this:
var coords = jcrop_api.tellSelect();
It returns my current Jcrop selections coordinates in an x,y,x2,y2,h,w format.
Now if I want to set my coordinates back to that, I could go:
jcrop_api.animateTo(coords)
But the animateTo function only takes an array of 4, [x, y, w, h]
When I try to do the above way, it eventually breaks the code.
So how do I change my variable coords to fit this format?
Thanks
The API functions you mention at least at the 0.9.12 version of the plugin..
jcrop_api.tellSelect() returns an object like this:
{
x: 0,
y: 0,
x2: 10,
y2: 10,
w: 10,
h:10
}
and jcrop_api.animateTo needs one array like [x,y,x2,y2], so, try this:
var c = jcrop_api.tellSelect();
jcrop_api.animateTo([c.x,c.y, c.x2, c.y2]);
I have made a Fabricjs canvas where the user can move around images and so on... I use JSON.stringify(canvas) to get all the data in text. The problem is that i get ALL the data when i just want certain ones like scaleX, ScaleY,Angle ect. How can i do this?
HTml
<div id="CanvasContainer">
<canvas id="Canvas" width="270" height="519"></canvas>
</div>
Javascript
function exportData(){
JSON.stringify(canvas);
console.log(JSON.stringify(canvas));
}
JSON without additional properties
var json = canvas.toJSON();
JSON with additional properties included
var json = canvas.toJSON(['lockMovementX', 'lockMovementY', 'lockRotation', 'lockScalingX', 'lockScalingY', 'lockUniScaling']);
JSON without default values
canvas.includeDefaultValues = false;
var json = canvas.toJSON();
You can pass a replacer function as a second argument to the JSON.stringify function.
var wantedKeys = ['scaleX', 'scaleY', 'angle'];
JSON.stringify({ scaleX: 0, scaleY: 1, angle: 3, notThisOne: 4}, function (key, value) {
if (!key || wantedKeys.indexOf(key) !== -1) return value;
}); //{"scaleX":0,"scaleY":1,"angle":3}
The replacer can also simply be an array of keys to keep:
JSON.stringify({ scaleX: 0, scaleY: 1, angle: 3, notThisOne: 4}, wantedKeys);
With a lack of math neurons in my brain, i struggle a bit in finding my way around this.
I need to create a simple javascript function that will receive three parameters:
A one-dimensional, normal indexed Array with X elements (the values being unique IDs)
A target ID to select
An amount of elements to return
The third parameter would ask the function to return a set of elements, with the element having the target ID being either in the center of the result, or next to it.
The result of the function should be an array as well.
A few examples to make it a more visual explanation:
function([100,120,140,160,180,200], 120, 3)
// should return [100,120,140]
function([100,120,140,160,180,200], 160, 4)
// should return [140,160,180,200]
function([100,120,140,160,180,200], 180, 5)
// should return [140,160,180,200,100]
The case covered by the last example is what confuses me while writing the code, which i am currently attempting to, but i find myself writing strange conditions, numerous if-statements and code that generally seems like a work-around. Also the cases of parameter 3 being larger than the amount of elements in parameter 1 are a bit of an over-brainer for me.
I feel unsafe continuing with this code, because it feels buggy and simply not proper. Surely somebody with proper math skills could provide me with the theory i need to understand how to accomplish this in a more elegant fashion.
Theory or pseudo-code will suffice, but if someone has something like this ready at hand, please don't hesitate to share it.
Thank You!
(Here is what i have written so far - based on the prototype JS class implementation)
var CBasicMatrix=Class.create({
initialize: function(elementList){
this.elementList=elementList;
},
select: function(id, amount){
if(amount>this.elementList.length)
amount=this.elementList.length;
if(!this.elementList.length) return false;
var elementIndex=this.elementList.indexOf(id);
if(elementIndex==-1) return false;
var isRound=amount%2==0;
var amountHalf=isRound ? (amount/2) : (Math.ceil(amount/2)-1);
// [464,460,462,461,463]
var result=[];
if(elementIndex-amountHalf >= 0) {
var startIndex=(elementIndex-amountHalf);
for(i=startIndex;i<=startIndex+amount;i++){
result.push(this.elementList[i];
}
} else {
// more seemingly stupid iterative code coming here
}
}
});
Edit: In order to make this more understandable i will state the purpose. This code is supposed to be used for kind of a slideshow, in which multiple elements (parameter 3) are visible at the same time. Parameter 1 is the list of (the IDs of the) total elements in their correct order as they appear in the HTML declaration. Parameter 2 is the element that is currently selected and therefore should appear in the middle.
Here is my solution:
function method(arr, value, n) {
var result = [],
len = arr.length,
index = arr.indexOf(value);
for (var i = 0; index > -1 && i < n ; i++) {
result.push(arr[(len + index - ~~(n / 2) + (n % 2 ^ 1) + i) % len]);
}
return result;
}
TESTS:
var arr = [100, 120, 140, 160, 180, 200];
method(arr, 120, 3); // [100, 120, 140]
method(arr, 160, 4); // [140, 160, 180, 200]
method(arr, 180, 5); // [140, 160, 180, 200, 100]
method(arr, 100, 3); // [200, 100, 120]
I will help you by providing a pseudo code :
1 . if there is no match you should return an empty array.
2 . if there is a match you just divide the third parameter by 2, you take the result , you loop from the element found's index minus the previous result until the third parameter's value and you store the elements in a new array.
3 . you return the new array.
Update:
I saw your code and I don't see any problem with it.
After some careful debugging and overthinking my approach, i managed to find a solution that seems proper and safe. I am sure this could be optimised further and if anyone has any suggestions, feel free to share them.
var CBasicMatrix=Class.create({
initialize: function(elementList){
this.elementList=elementList;
},
select: function(id, amount){
if(amount>this.elementList.length)
amount=this.elementList.length;
if(!this.elementList.length) return false;
var elementIndex=this.elementList.indexOf(id);
if(elementIndex==-1) return false;
var isRound=amount%2==0;
var amountHalf=isRound ? (amount/2) : (Math.floor(amount/2));
var result=[];
var startIndex=(elementIndex-amountHalf);
var endIndex=(startIndex+amount-1);
var targetIndex=0;
for(i=startIndex;i<=endIndex;i++){
targetIndex=i;
if(i>this.elementList.length-1) targetIndex=i-this.elementList.length;
if(i<0) targetIndex=i+this.elementList.length;
result.push(this.elementList[targetIndex]);
}
return result;
}
});
I'm writing a 2D gravity simulation game and I'm trying to add save/load functionality. In the game I store all of the current planets in an array. Each planet is represented by a Body object which contains the coordinates, mass, and motion vector of the planet. It also stores an array of the last 100 coordinates of the planet in order to draw the planet's trail on the screen.
I want to use JSON.stringify() to serialize the planets array. I'd like to save the first attributes of each planet (mass, location, motion) but I don't need to save the last 100 coordinates (the trail array). I don't want to completely delete the coordinates otherwise the trails will disappear from the screen. Can I stringify only a portion of each object? If not, can I remove that portion of the JSON string after it's been encoded? Or should I move the coordinates elsewhere during the save process then copy them back into each planet once it's been saved?
In modern web browsers you can use Array#map.
var serialized = JSON.stringify(planets.map(function(planet){
return {
mass: planet.mass,
location: planet.location,
motion: planet.motion
};
}));
Or, the equivalent using a for loop.
try it this way
var saved = JSON.stringify( {mass:body.mass,location:body.location,motion:body.motion} );
it shall give you just the three parts as a json string.
A bit more extended you could provide your body class such an export function.
For example:
Bodyclass.export = function( toexport ) {
if ( undefined === toexport || toexport.constructor != Array ) {
var toexport = [ 'mass', 'location', 'motion' ];
}
var export = {};
for ( var i = 0; i < toexport; i++) {
export[ toexport[ i ] ] = this[ toexport[ i ] ];
]
}
var saved = JSON.stringify( body.export() );
The best would be to create both a serialization and deserialization method. This will allow you to create the most efficient storage format while still allowing you to reconstruct as much of the objects as you deem necessary.
You can use export/import, save/restore, serialize/deserialize terminology, whichever you see fit.
Having methods like this will increase you maintainability in the long run as well.
You can use second parameter of JSON.stringify (replacer)
const planet = {
name: "Pluto",
lastCoords: [[0, 0], [1,1,]]
}
const json = JSON.stringify(planet, (key, value) => key === "lastCoords" ? undefined : value)
// json === {"name":"Pluto"}