Building a grid of circles with text inside and... moving things around - javascript

I'm desperately trying to build a grid with circles and text inside. So far so good, I can do that... My real problem is being able to find each set and move it around (text AND circle). I've tried to look at similar issues, but I can't find out by myself... If someone could give me a clue, I'd greatly appreciate.
Here's a simplified code (only 1 line) that doesn't work :
$(function() {
// Prepare drawing zone
var paper = Raphael(document.getElementById('question'), '100%', '100%');
var word = 'Sunday';
var group = new Array();
// Draw 5 circles with text inside
for (i=0; i<5; i++) {
group[i] = paper.set();
group[i].push(paper.circle(50+i*60, 50, 30));
group[i].push(paper.text(50+i*60, 50, word));
group[i].click(function() {
group[i].translate(20,20); // HERE'S THE PROBLEM group[i] DOESN'T WORK !
group[i].rotate(Math.random() * 90);
});
}
});
I can't find out a way of 'calling' my sets for further reference...
Of course, If I have only 1 set (and no array=, it works...
Thanks for your help!
Celfred.
Edit : jsfiddle : http://jsfiddle.net/rrWqM/
Edit : I'm not sure I'm clear enough. What I would like is to be able to click on 1 circle (and text), and see THIS circle AND text move. If I click on another one, then the other one moves... It sounds so simple I can't believe I'm stuck on that... Thanks for the help.

Here is a [fiddle][http://jsfiddle.net/DusKv/1/]
The problem in your code is that the i variable does not have the right value when the click callback function is invoked. You can work around this by defining a local variable in the enclosing scope.
// Prepare drawing zone
var paper = Raphael(document.getElementById('question'), '100%', '100%');
var word = 'Sunday';
var group = new Array();
// Draw 10 circles with text inside
for (i = 0; i < 10; i++) {
var set = paper.set();
set.push(paper.circle(50 + i * 30, 50, 50));
set.push(paper.text(50 + i * 30, 50, word));
set.click(function() {
set.translate(Math.random() * 350, Math.random() * 380); // HERE'S THE PROBLEM group[i] DOESN'T WORK !
set.rotate(Math.random() * 90);
});
group[i] = set;
}

Eventually, I found a turnaround this way : jsfiddle
Now I get a correct reference in my click event.
I must admit I didn't quite understand my initial problem. If you could at least tell me if this new 'solution' sounds good to you, I'd appreciate ;-)
Celfred.

Related

Rendering too many points on Javascript-player

As part of a project, I have to render a video on a JS-player from a text file which has the points - all the changed coordinates along-with the color in each frame. Below is the code I'm using to draw these point on the screen.
But the issue is that the number of changed pixels in each frame are as high as ~20,000 and I need to display these in less than 30ms (inter-frame time difference). So, when I run this code the browser hangs for almost each frame. Could someone suggest an improvement for this?
Any help is really appreciated.
c.drawImage(img,0,0,800,800);
setInterval(
function(){
while(tArr[index]==time) {
var my_imageData = c.getImageData(0,0,width, height);
color(my_imageData,Math.round(yArr[index]),Math.round(xArr[index]),Math.round(iArr[index]),255);
c.putImageData(my_imageData,0,0);
index=index+1;
}
time = tArr[index];
}
,30);
xArr, yArr, iArr, tArr are arrays of x-coordinate, y-coordinate, intensity value and time of appearance respectively for the corresponding point to be rendered
function color(imageData,x,y,i,a){ //wrapper function to color the point
var index = (x + y * imageData.width) * 4;
imageData.data[index+0] = i;
imageData.data[index+1] = i;
imageData.data[index+2] = i;
imageData.data[index+3] = a;
}

Drag and Drop not recognizing child of drag object in Animate CC

I'm trying to make a drag and drop, but it's been giving me a bunch of issues. I fix one and another comes up. I had it working where it would see if any part of my drag object entered a target area, but I wanted it to just recognize one part (it's graphic of a pointy thermometer, and you can't measure temperature with the head in real life) demo here.
The error I'm getting is that "Uncaught TypeError: Cannot read property 'drag' of undefined" (I labeled 'drag' on the demo, but its a child movieclip inside the drag object)
also, 'thermometer' and 'drag' are both named instances of movieclips.
The Code:
var dragger = this.thermometer;
//tried this to see if it would help
var tip = this.thermometer.drag;
var right = this.targetRight;
var wrong = this.targetWrong;
For moving it:
dragger.on("pressmove", function(evt){
evt.currentTarget.x = evt.stageX;
evt.currentTarget.y = evt.stageY;
if(intersect(tip, right)){
evt.currentTarget.alpha=0.2;
}
else if(intersect(tip, wrong)){
evt.currentTarget.alpha=0.7;
}
else{
evt.currentTarget.alpha=1;
}
stage.update(evt);
}, this);
For releasing it
dragger.on("pressup", function(evt){
//lock position of drag object and play animation if any
dragger.x = dragger.x;
dragger.y = dragger.y;
if(hitTestArray.length > 1){
dragger.alpha = 1;
stage.update(evt);
}//else{
if(intersect(tip, right)){ //Intersection testing for good (also tried 'dragger.drag' to see if that would work. it didn't)
alert("YAY you're right AND it works!");
dragger.alpha = 1;
}else if(intersect(tip, wrong)){ //intersection Testing for bad
alert("BOO its wrong, but YAY it works");
dragger.alpha = 1;
}
stage.update(evt);
//}
}, this);
UPDATED INTERSECT:
for testing intersection.
function intersect(obj1, obj2){
var objBounds1 = obj1.nominalBounds.clone();
var objBounds2 = obj2.nominalBounds.clone();
var pt = obj1.globalToLocal(objBounds2.x, objBounds2.y);
var h1 = -(objBounds1.height / 2 + objBounds2.height);
var h2 = objBounds2.height / 2;
var w1 = -(objBounds1.width / 2 + objBounds2.width);
var w2 = objBounds2.width / 2;
if(pt.x > w2 || pt.x < w1) return false;
if(pt.y > h2 || pt.y < h1) return false;
return true;
}
To sum up, I need to know how to make it not undefined so that I can test for that little box being in one of the big boxes.
The error is happening because you used this.currentTarget instead of evt.currentTarget on that one line.
Note that your actual code is not the same as the code you posted above. Here is the code in the live demo:
if(intersect(this.currentTarget.drag, right)){
evt.currentTarget.alpha=0.2;
} else if(intersect(this.currentTarget.drag, wrong)){
evt.currentTarget.alpha=0.7;
}
else{
evt.currentTarget.alpha=1;
}
Not sure if this will solve all your issues, but it should at least get you moving forward.
[UPDATE]
Looking a little deeper, there a number of issues that are likely contributing to your intersect function not working:
Your right/left bounds are not correct. EaselJS objects do not have a width or height (more info), so the bounds you set just have an x and y.
You can use nominalBounds to get the proper bounds. This provides the untransformed, original bounds of the symbol. You will have to account for any scaling. In this case, the bounds are:
* left: {x: 0, y: 0, width: 275, height: 300}
* right: {x: 0, y: 0, width: 413, height: 430}
Your intersection will have to consider the display list hierarchy. Specifically, when comparing position and size, they should be relative to each other. If your drag target is positioned inside another clip, it will need to consider the parent positioning. I recommend always doing localToGlobal on coordinates when comparing them.
Example:
// Find the clip's top/left position in the global scope
var p = myContainer.localToGlobal(myClip.x, myClip.y);
// OR
// Find the clip's position in the global scope
var p = myClip.localToGlobal(0, 0);

Linking two.js with dat.GUI

I want to link the change letter.linewidth = 10 with a control in dat.GUI.
Here is the code for the full letter variable:
var letter = two.interpret(document.querySelector('.assets svg'));
letter.linewidth = 10;
letter.cap = letter.join = 'round';
letter.noFill().stroke = '#333';
To add an element to dat.GUI it says in the docs "The property must be public, i.e. defined by this.prop = value", though when I add this. in front of letter.linewidth it breaks the functionality of two.js and does not interpret the SVG.
I'm kinda' new to JavaScript and having a tough time figuring this one out.
Any help would be greatly appreciated.
So after lots of playing around, I found the fix.
Here is the code to draw the SVG through two.js:
var letter = two.interpret(document.querySelector('.assets svg'));
letter.linewidth = 100;
letter.cap = letter.join = 'round';
letter.noFill().stroke = '#272727';
letter.scale = 1;
I was calling the letter wrong with dat.GUI. Here is my code for dat.GUI:
window.onload = function() {
var gui = new dat.GUI();
gui.add(letter, 'linewidth', 1, 100);
}
I don't know if this will be useful for anyone, but hey, hopefully this will help if somebody is running into the same problem.

How to add new line character for each node text in arbor js

I have a network,with 14 nodes, and each node has a label, and also edges for connecting these nodes to each other. I tried to enter a long label for one of these nodes, and unfortunatly it seems that arborjs show labels on nodes just horizontally, so I tried to put a new line character in a label text "\n" and it will render it as an space, so I was wondering if anybody knows how to have multiple line label for a node in arbor js?
Here is the code :
<script language="javascript" type="text/javascript">
var sys = arbor.ParticleSystem(1000, 700,0.01);
sys.parameters({gravity:false});
sys.renderer = Renderer("#viewport") ;
var data = {
nodes:{
STRUCTURE:{'color':'black','shape':'rect','label':'STRUCTURE', },
Engineering:{'color':'salmon','shape':'rect','label':'Engineering'},
Architecture:{'color':'salmon','shape':'rect','label':'Architecture'},
ArtsSciences:{'color':'salmon','shape':'rect','label':'Arts & Sciences'},
EarthEnergy:{'color':'salmon','shape':'rect','label':'Earth & Energy'},
SustainableDesign:s{'color':'lightskyblue','shape':'rect','label':'Sustainable Design'},
sutabledesignleaf1:{'color':'lawngreen','shape':'rect','label':'Earthen Structures'},
MaterialsStructures:{'color':'lightskyblue','shape':'rect','label':'Materials & Structures'},
MaterialsStructuresleaf1:{'color':'lawngreen','shape':'rect','label':'AEROSPACE/MECH. ENGINEERING'},
LithosphereDynamics:{'color':'lightskyblue','shape':'rect','label':'Lithosphere Dynamics'},
Energy:{'color':'lightskyblue','shape':'rect','label':'Energy'},
LithosphereDynamicsleaf1:{'color':'lawngreen','shape':'rect','label':'Structure/Tectonophy'},
Energyleaf1:{'color':'lawngreen','shape':'rect','label':'Structural Control on Reservoirs'},
ArtsSciencesleaf1:{'color':'lawngreen','shape':'rect','label':'VARIOUS THEMES Market Structure'},
},
edges:{
STRUCTURE:{ Engineering:{}, Architecture:{} , ArtsSciences:{}, EarthEnergy:{}},
ArtsSciences:{ArtsSciencesleaf1:{}},
EarthEnergy:{Energy:{},LithosphereDynamics:{}},
Energy:{Energyleaf1:{}},
LithosphereDynamics:{LithosphereDynamicsleaf1:{}},
Engineering:{MaterialsStructures:{}},
MaterialsStructures:{MaterialsStructuresleaf1:{}},
Architecture:{SustainableDesign:{}},
SustainableDesign:{sutabledesignleaf1:{}}
}
};
sys.graft(data);
var canvas = document.selectElementById('viewport') ;
var context = canvas.getContext('2d');
context.font = '40pt Calibri';
context.fillStyle = 'blue';
</script>
suppose in this code, for STRUCTURE node's label we have "STRUCTURE" but when I want to have like a long text lie "kaskdjhkjahdkjhaskjdhjkahskjdhakjshdkjahdkjhaskjdhkjahsdkjhakjsdhkjashdkjhasdkjhkajshdkjhakjdhkajshdk" it doesn't break it to two lines, it will show up as one line, and even if I put a new line character, it will consider it as a space and it will show that again in one line, any help is appreciated.
Thanks in advance
Thank you for your answer, last night, I figured out that unfortunately there is no way on canvas fillText() to draw text in multiple line, so I had to write my wrapper for that, here is the function that I wrote, and it's working right now,
function wrap_text(var rawstring,var line_width)
{
var strarray = new Array() ;
var temp_str = new Array() ;
var j = 0 ;var i = 0 ;
strarray = text.split(' ');
var temp = strarray[j] ;
j++;
while(j < strarray.length)
{
while(temp.length <30)
{
temp = temp+" "+strarray[j];
j++;
}
temp_str[i]=temp ; i++;
var temp = "" ;
}
return temp_str;
}
var wrap_result = wrap_text('kjakjhkjashd kajasd asdmbdmnad nmauhiqwe kbawem mnbasdm',20);
for (var i = 0; i <wrap_result.length ; i--)
{
console.log(wrap_result[i]);
}
I know this post is 2 year too late, though I was still having the same issue and unable to find the solution anywhere. The main problem is the canvas fillText does not support multiple lines. So you have to add multiple lines to the label. The trick is to split out the returns into an array and loop over the array for each new line.
To keep the code clean, I prefer to not to directly edit the function in the files. To get the multiple lines to work add to your custom JS the below function which will override the Cytoscape internal label rendering. Works for both cytoscape.js & cytoscape.min.js
//function to override the default label rending to support multiple lines
;(function($$){ 'use strict';
var CanvasRenderer = $$('renderer', 'canvas');
CanvasRenderer.prototype.drawText = function(context, element, textX, textY) {
var style = element._private.style;
var parentOpacity = element.effectiveOpacity();
if( parentOpacity === 0 ){ return; }
var text = this.setupTextStyle( context, element );
if ( text != null && !isNaN(textX) && !isNaN(textY) ) {
var lineWidth = 2 * style['text-outline-width'].value; // *2 b/c the stroke is drawn centred on the middle
if (lineWidth > 0) {
context.lineWidth = lineWidth;
context.strokeText(text, textX, textY);
}
//START NEW CODE
//remove old label rendinging
//context.fillText(text, textX, textY);
//explode the text into an array split up by line returns
var lines = text.split("\n");
//loop through each of the lines
for (var index = 0; index < lines.length; ++index) {
//render the multiple lines
context.fillText(lines[index], textX, (textY + (style['font-size'].pxValue * 1.2 * index)));
}
//END NEW CODE
}
};
})( cytoscape );
This question really concerns canvas.fillText(), not arbor.js, see this question. In short, this is a limitation of the fillText function.
That said, you can solve this problem relatively simply. The following all assumes you are basing your rendering on the "atlas" example, but you can figure it out from the idea anyway I think.
// draw the text
if (label){
ctx.font = "bold 11px Arial"
ctx.textAlign = "center"
// if (node.data.region) ctx.fillStyle = palette[node.data.region]
// else ctx.fillStyle = "#888888"
ctx.fillStyle = "#888888"
// ctx.fillText(label||"", pt.x, pt.y+4)
ctx.fillText(label||"", pt.x, pt.y+4)
}
Check out the code above to see how the text is rendered. We can replace the line ctx.fillText(label||"", pt.x, pt.y+4) with a loop based on multiple lines you want to render. Make your label value something like line 1\nline 2\nline 3, then use String.split() to make it into an array like so:
var lines = label.split("\n");
Now, loop through lines and render a ctx.fillText() for each one. If you are basing your project closely on the examples you may need to adjust the layout to make it look right, but hopefully this has put you on the right track.

Simple javascript game, hide / show random square

I'm working on a simple game and I need some help to improve my code
So here's the game:
Some square show and hide randomely for a few seconds and you have to clic on them.
I use RaphaelJS to draw the square and a few of JQuery ($.each() function)
I work in a div, that's how I draw my squares (6 squares), x y are random numbers.
var rec1 = paper.rect(x, y, 50, 50).attr({
fill: "blue",});
Can I use for() to build my squares with a different var name for each one ?
I try with var = varName+i but it didn't work.
To hide and show the square I use two functions call with two setTimeout:
function box1() {rec1.show();}
function hidebox1() {rec1.hide();}
var time1 = setTimeout(box1, 1000);
var time1 = setTimeout(hidebox1, 2000);
I know it looks crappy...
I'm sure there is a way to use a toggle, or something more fancy to do that if you could help me finding it :) Because right now I have to do that for every square...
Thanks a lot for your help.
Your instinct to try to use varName plus some i to identify which varName you want is spot on, and JavaScript (like most languages) has that idea built in through what's called an array.
A simple one looks something like this:
var foo = [1, 5, 198, 309];
With that array, you can access foo[0] which is 1, or foo[3] which is 309.
Note two things: First, we identify which element of the array we want using square brackets. Second, we start counting at 0, not 1.
You can create an empty array like var varName = []; and then add new elements to it using varName.push( newValueToPutIn );
With those tools, you can now get at what you wanted. Now you can do something like:
var recs = [];
for(var i = 0; i < 100; i++) {
var rec = paper.rect(x, y, 50, 50).attr({fill: 'blue'});
recs.push(rec);
}
And recs[0] and recs[1] and so forth will refer to your various boxes.
For the first question, an array is the way to go.
For the second part, you could encapsulate the square and its show/hide stuff into a new anonymous object, like this:
var recs = [];
var numberOfRecs = 6;
for (var i = 0; i < numberOfRecs; i++) {
//determine x and y?
recs.push({
box: paper.rect(x, y, 50, 50).attr({ fill: "blue" }),
showBriefly: function(timeFromNow, duration) {
window.setTimeout(this.box.show, timeFromNow);
window.setTimeout(this.box.hide, timeFromNow + duration);
}
});
}
//show the 3rd box 1000 ms from now, for a duration of 1000 ms
recs[2].showBriefly(1000, 1000);

Categories

Resources