Plugin Freewall, cannot get wall function to work - javascript

I am trying to create a grid style layout for my homepage that pulls random information every time the user loads the page. I have created the function but cannot even get it to display the wall items.
Here is the code I am using. Please point me in the right direction and I will be able to solve it but I cannot find my issue right now.
$(function() {
var temp = "<div class='bubble eventBrick' id='{brickID}' style='width:{width}px; height: {height}px;'><div class='rectangle' style='background: {ribbonColor};'><h2>{brickInfo}</h2></div><div class='triangle-l'><div class='info' style='border-color: transparent {triColor} transparent transparent;'></div> <!-- Left triangle --></div>";
var w = 1, h = 1, html = '', limitEventItem = 16, podcastBrick = 1, longBrick = 3;
var wallBricks = [
'podBrick',
'longBrick',
'trackBrick',
'newsBrick',
'socialBrick',
'photoBrick'
]
var wallBrickList = new Array();
var total = limitEventItem;
var trackBrickLimit = 3;
var newsBrickLimit = 3;
var socialBrickLimit = 3;
var photoBrickLimit = 3;
var eventWall = new freewall("#eventWall");
eventWall.reset({
selector: '.eventBrick',
animate: true,
cellW: 156.5,
cellH: 136,
delay: 15,
gutterX: 24,
gutterY: 10,
onResize: function(){
eventWall.fitZone();
}
});
for (t = 0; t <= trackBrickLimit; t++){
h = 1;
w = 1;
html += temp.replace(/\{height\}/g, h*100).replace(/\{width\}/g, w*100).replace("{brickInfo}", "Track Item").replace("{ribbonColor}", "#7f9db9").replace("{triColor}", "#7f9db9");
$("#eventWall").html(html);
html = '';
}
for (n = 0; n <= newsBrickLimit; n++) {
h = 1;
w = 1;
html += temp.replace(/\{height\}/g, h*100).replace(/\{width\}/g, w*100).replace("{brickInfo}", "News Item").replace("{ribbonColor}", "#FF9933").replace("{triColor}", "#FF9933");
$("#eventWall").html(html);
html = '';
}
for (s = 0; s <= socialBrickLimit; s++) {
h = 1;
w = 1;
html += temp.replace(/\{height\}/g, h*100).replace(/\{width\}/g, w*100).replace("{brickInfo}", "Social Item").replace("{ribbonColor}", "#3366FF").replace("{triColor}", "#3366FF");
$("#eventWall").html(html);
html = '';
}
for (p = 0; p <= photoBrickLimit; p++) {
h = 1;
w = 1;
html += temp.replace(/\{height\}/g, h*100).replace(/\{width\}/g, w*100).replace("{brickInfo}", "Photo Item").replace("{ribbonColor}", "#33FF00").replace("{triColor}", "#33FF00");
$("#eventWall").html(html);
html = '';
}
eventWall.fitZone((600), (815));
function randomList(total) {
var brickLimit = total;
var brickTotal = 0;
var news = Math.floor((Math.random()*4) +1);
brickTotal += news;
if (brickTotal <= 2) {
var social = Math.floor((Math.random()*4)+1);
var tracks = Math.floor((Math.random()*4)+1);
brickTotal = brickTotal + social + tracks;
if (brickTotal <= 10) {
extraBanner = 1;
var photo = brickTotal - total - 1;
} else {
var photo = brickTotal - total - 1;
}
} else {
var social = Math.floor((Math.random()*3)+1);
var photo = Math.floor((Math.random()*3)+1);
var tracks = brickLimit - news - photo - social;
}
var brickCount = new Object()
brickCount[0] = track;
brickCount[1] = news;
brickCount[2] = social;
brickCount[3] = photo;
return brickCount;
}
});
If I am missing a concept please tell me the concept, where I can learn more and examples so I might be able to rework this by myself.

Please check with the selector:
<div class='bubble {eventBrick}Brick'
and
selector: '.eventBrick',

Related

Paint by number Illustrator script

I am from supercoloring and we decided to convert our vector illustrations in color to color by number worksheets. Our input files are color and outline images in svg format.
Outline version (like a coloring page) + Color version
outline version and
color version
What we want to get is the following
result
We would like that a color palette is generated under the outline version of the image based on the color data from the color version of the image. Moreover, numbers corresponding to this palette are placed inside each color space of the outlined version.
I understand that no script in the world would do this properly, but at least I am striving to reduce the time spent by the editor (person) to put these numbers manually in the Illustrator. I understand that our color vector images may have too many colors and shades so we need somehow to limit the result colors of the palette ( to fuse them into large groups of basic colors).
I searched all over the stackoverflow solutions and found some ingenious like Paint with numbers with Adobe Illustrator Javascript and
I'm looking to create an automated numbering system for custom paint by number kits in photoshop (Kudos to Yuri Khristich). However, they are not exactly adapted to our needs.
Most of scripts on the web generate outlined images from color version, but the quality is compromised. We have already a proper outline version that we want to use as a base for color by number worksheet.
Here is the script to make a 'color palette' for selected artwork.
And here, as you know, is the script to add color names to all filled areas.
So I took the two script, made a couple of minimal tweaks and get almost the result you want. All you need after the scripts is to copy the layer with numbers and 'palette' from a colored artwork to a outline version.
Script #1
// Modified version
// https://stackoverflow.com/questions/75344674/paint-by-number-illustrator-script
// Original:
// https://productivista.com/make-a-list-of-colors-from-your-selection/
/*
Date: July, 2020
Author: Katja Bjerrum, email: katja#productivista.com, www.productivista.com
============================================================================
NOTICE:
This script is provided "as is" without warranty of any kind.
Free to use, not for sale.
============================================================================
Released under the MIT license.
http://opensource.org/licenses/mit-license.php
============================================================================
*/
//#target illustrator
var doc = app.activeDocument;
var myLayer = doc.activeLayer;
app.coordinateSystem = CoordinateSystem.ARTBOARDCOORDINATESYSTEM;
var swGrps = doc.swatchGroups;
var mainSwGr = doc.swatchGroups[0];
var sel = doc.selection;
var actionSet = 'CreateSwatchGroup';
var actionName = 'ColourGroup';
var actionPath = Folder.myDocuments + '/Adobe Scripts/';
if (!Folder(actionPath).exists) Folder(actionPath).create();
//app.doScript("Colorgroup", "ToSwatchScript"); // Action, that creates swatch group
var actionDoc =
[ '/version 3',
'/name [' + actionSet.length + ' ' + ascii2Hex(actionSet) + ']',
'/isOpen 1',
'/actionCount 1',
'/action-1 {',
'/name [' + actionName.length + ' ' + ascii2Hex(actionName) + ']',
' /keyIndex 0',
' /colorIndex 0',
' /isOpen 1',
' /eventCount 1',
' /event-1 {',
' /useRulersIn1stQuadrant 0',
' /internalName (ai_plugin_swatches)',
' /localizedName [ 8',
' 5377617463686573',
' ]',
' /isOpen 0',
' /isOn 1',
' /hasDialog 1',
' /showDialog 1',
' /parameterCount 1',
' /parameter-1 {',
' /key 1835363957',
' /showInPalette 4294967295',
' /type (enumerated)',
' /name [ 15',
' 4e657720436f6c6f722047726f7570',
' ]',
' /value 17',
' }',
' }',
'}'].join('');
createAction(actionDoc, actionName, actionPath);
app.redraw();
app.doScript (actionName, actionSet);
app.redraw();
app.unloadAction(actionSet, '');
var convMM = 2.8346456692; // initialization of the variable to convert points to mm
var colorgroup = doc.swatchGroups[doc.swatchGroups.length - 1]; // Choose the last swatch group
var stY = -200; //
var stX = 20;
var recW = 25;
var recH = 25;
var offX = recW / 5;
var offY = recH / 4;
var textoffY = recH / 4;
var rows = 4;
var cols = 4;
var black = new GrayColor();
black.gray = 80;
var white = new GrayColor() ;
white.gray = 0;
var noStroke = doc.swatches[0].color;
if (swGrps.length <=1){
alert ("Please create swatch group from your selection");
}
else if (sel <= 0){
//docRef.placedItems[0].selected == false;
alert ("Please make a selection");
delSwatchGr(colorgroup); //delete swatch group
}
else{
swatchGroupList(colorgroup, stY, stX);//create corlor list
// delSwatchGr(colorgroup);//delete swatch group
}
//Function, that creates color list
function swatchGroupList(swatchGroup, stY, stX) {
// Groups everything in the list
var mainGroup = myLayer.groupItems.add();
mainGroup.name = "Colors";
mainGroup.moveToBeginning(myLayer);
//Name of the color list
var nameText = myLayer.textFrames.add();
nameText.contents = swatchGroup.name; // the name of the swatch group
nameText.position = [stX, stY + recH];
var nameStyle = nameText.textRange.characterAttributes;
nameStyle.size = 12;//size in punkt
//nameStyle.textFont = textFonts.getByName("Avenir-Book");//the font
nameStyle.capitalization = FontCapsOption.ALLCAPS;//ALL CAPITALS
var swatches = swatchGroup.getAllSwatches();
var swatchArray = [];
for (i = swatches.length-1; i>=0; i--) {
var mySwatch = swatches[i];
mySwatch.name = i + 1;
var subGroup = createSwatchGroup(mySwatch, textoffY);
swatchArray.push(subGroup);
}
nameText.moveToEnd(mainGroup);
var myGroup = swatchArray;
var maxW = maxWidth(myGroup);
for (var j = 0; j < myGroup.length; j++) {
var mySubGroup = myGroup[j];
mySubGroup.moveToBeginning(mainGroup);
}
for (var i = 0; i < mainGroup.groupItems.length; i++) {
var mySubGroup = mainGroup.groupItems[i];
if (mainGroup.groupItems.length > 7) {
rows = 7;
var c = i%rows;
var r = Math.floor(i/rows);
mySubGroup.position = [stX + r * (maxW + 10), stY - c * (recH + offY)];
}
else {
rows = 7;
var c = i % rows;
var r = Math.floor(i / rows);
mySubGroup.position = [stX, stY - c * (recH + offY)];
}
}
// textSwatch.moveToBeginning(SubGroup);
// path_ref.moveToBeginning(SubGroup);
// SubGroup.position = [stX + c * 140, stY - r * (path_ref.height + offY)];
subGroup.moveToBeginning(mainGroup);
}
function lightColor(c){
if(c.typename)
{
switch(c.typename)
{
case "CMYKColor":
return (c.black>=10 || c.cyan>10 || c.magenta>10 || c.yellow > 10) ? true : false;
case "RGBColor":
return (c.red<230 || c.green<230 || c.blue<230) ? true : false;
case "GrayColor":
return c.gray >= 10 ? true : false;
case "SpotColor":
return lightColor(c.spot.color);
//return false;
}
}
}
function fitItem(item, itemW, itemH, diff) {
var oldWidth = item.width
var oldHeight = item.height
if (item.width > item.height) {
// landscape, scale height using ratio from width
item.width = itemW - diff.deltaX
var ratioW = item.width / oldWidth
item.height = oldHeight * ratioW
} else {
// portrait, scale width using ratio from height
item.height = itemH - diff.deltaY
var ratioH = item.height / oldHeight
item.width = oldWidth * ratioH
}
}
function itemBoundsDiff(item) {
var itemVB = item.visibleBounds
var itemVW = itemVB[2] - itemVB[0] // right - left
var itemVH = itemVB[1] - itemVB[3] // top - bottom
var itemGB = item.geometricBounds
var itemGW = itemGB[2] - itemGB[0] // right - left
var itemGH = itemGB[1] - itemGB[3] // top - bottom
var deltaX = itemVW - itemGW
var deltaY = itemVH - itemGH
var diff = { deltaX: deltaX, deltaY: deltaY }
return diff
}
function delSwatchGr(swGr){
var swGrSws = swGr.getAllSwatches();
for (var j = 0; j < swGrSws.length; j++){
var sw = swGrSws[j];
sw.color = new CMYKColor();
}
swGr.remove();
}
//Function finds the max group width
function maxWidth(myGroup) {
var maxFound = 0;
for (var j = 0; j < myGroup.length; j++) {
var GrWidth = myGroup[j].width;
//var Widthmax = GrWidth.width;
maxFound = Math.max(maxFound, GrWidth);
}
return maxFound;
}
function createSwatchGroup(sw, myOffset) {
//Is "MyForm" path exists?
try{
var path_ref_ori = app.activeDocument.pathItems.getByName("MyForm" || "myform" || "MYFORM");
}
catch(e) {
var path_ref_ori = false;
}
if (path_ref_ori) {
myPath = path_ref_ori.duplicate();
var boundsDiff = itemBoundsDiff(myPath);
fitItem(myPath, recW, recH, boundsDiff);
myPath.name = "NewForm";
myPath.position = [0, 0];
}
else {
var myPath = createMyPath()
}
myPath.fillColor = sw.color;
myPath.stroked = true;
myPath.strokeWidth = 0.3;
myPath.strokeColor = lightColor(myPath.fillColor) ? noStroke : black;
var textSwatch = myLayer.textFrames.add(); //swatch text
textSwatch.contents = sw.name;
textSwatch.position = [myPath.width + 1.3 * convMM, -myOffset];
var textSwStyle = textSwatch.textRange.characterAttributes;
textSwStyle.size = 10; //size in punkt
//textSwStyle.textFont = textFonts.getByName("MyriadPro-Semibold"); //the font
var SubGroup = myLayer.groupItems.add(); //groups path and text
SubGroup.name = sw.name;
SubGroup.position = [0, 0];
textSwatch.moveToBeginning(SubGroup);
myPath.moveToBeginning(SubGroup);
return SubGroup;
}
function createMyPath(){
//Is "MyForm" path exists?
try{
var path_ref_ori = app.activeDocument.pathItems.getByName("MyForm" || "myform" || "MYFORM");
}
catch(e) {
var path_ref_ori = false;
}
if (path_ref_ori) {
path_ref = path_ref_ori.duplicate();
var boundsDiff = itemBoundsDiff(path_ref);
fitItem(path_ref, recW, recH, boundsDiff);
path_ref.name = "NewForm";
path_ref.position = [0, 0];
}
else {
var path_ref = myLayer.pathItems.rectangle(0, 0, recW, recH); //swatch path item
}
return path_ref
};
function createAction(str, set, path) {
var f = new File('' + path + '/' + set + '.aia');
f.open('w');
f.write(str);
f.close();
app.loadAction(f);
f.remove();
};
function ascii2Hex(hex) {
return hex.replace(/./g, function (a) { return a.charCodeAt(0).toString(16) });
};
Input (after select the artwork and run the script):
Result (added the global swatches and the 'color palette' at the bottom):
Script #2
// Based on:
// https://stackoverflow.com/questions/73705368/paint-with-numbers-with-adobe-illustrator-javascript
var doc = app.activeDocument,
lays = doc.layers,
WORK_LAY = lays.add(),
NUM_LAY = lays.add(),
i = lays.length - 1,
lay;
// main working loop
for (; i > 1; i--) {
//process each layer
lay = lays[i];
lay.name = lay.name + " Num:" + (i - 1); // i-1 as 2 layers beed added.
process(lay.pathItems, false);
process(lay.compoundPathItems, true); // if any
}
//clean up
NUM_LAY.name = "Numbers";
WORK_LAY.remove();
function process(items, isCompound) {
var j = 0,
b, xy, s, p, op;
for (; j < items.length; j++) {
// process each pathItem
op = items[j];
try { color = op.fillColor.spot.name } catch(e) { continue } // <-- HERE
// add stroke
if (isCompound) {
// strokeComPath(op);
} else {
// !op.closed && op.closed = true;
// op.filled = false;
// op.stroked = true;
};
b = getCenterBounds(op);
xy = [b[0] + (b[2] - b[0]) / 2, b[1] + (b[3] - b[1]) / 2];
s = (
Math.min(op.height, op.width) < 20 ||
(op.area && Math.abs(op.area) < 150)
) ? 20 : 40; // adjust font size for small area paths.
add_nums(color, xy, s); // <--- HERE
}
}
function getMinVisibleSize(b) {
var s = Math.min(b[2] - b[0], b[1] - b[3]);
return Math.abs(s);
}
function getGeometricCenter(p) {
var b = p.geometricBounds;
return [(b[0] + b[2]) / 2, (b[1] + b[3]) / 2];
}
// returns square of distance between p1 and p2
function getDist2(p1, p2) {
return Math.pow(p1[0] + p2[0], 2) + Math.pow(p1[1] + p2[1], 2);
}
// returns visibleBounds of a path in a compoundPath p
// which is closest to center of the original path op
function findBestBounds(op, p) {
var opc = getGeometricCenter(op);
var idx = 0,
d;
var minD = getDist2(opc, getGeometricCenter(p.pathItems[0]));
for (var i = 0, iEnd = p.pathItems.length; i < iEnd; i++) {
d = getDist2(opc, getGeometricCenter(p.pathItems[i]));
if (d < minD) {
minD = d;
idx = i;
}
}
return p.pathItems[idx].visibleBounds;
}
function applyOffset(op, checkBounds) {
var p = op.duplicate(WORK_LAY, ElementPlacement.PLACEATBEGINNING),
// offset value the small the better, but meantime more slow.
offset = function() {
var minsize = Math.min(p.width, p.height);
if (minsize >= 50) {
return '-1'
} else if (20 < minsize && minsize < 50) {
return '-0.5'
} else {
return '-0.2' // 0.2 * 2 (both side ) * 50 (Times) = 20
}
},
xmlstring = '<LiveEffect name="Adobe Offset Path"><Dict data="I jntp 2 R mlim 4 R ofst #offset"/></LiveEffect>'
.replace('#offset', offset()),
TIMES = 100; // if shapes are too large, should increase the value.
if (checkBounds) {
// check its size only if it needs, because it's too slow
while (TIMES-- && getMinVisibleSize(p.visibleBounds) > 3) p.applyEffect(xmlstring);
} else {
while (TIMES--) p.applyEffect(xmlstring);
}
return p;
}
function getCenterBounds(op) {
var originalMinSize = getMinVisibleSize(op.visibleBounds);
var p = applyOffset(op, false);
if (getMinVisibleSize(p.visibleBounds) > originalMinSize) {
// in some cases, path p becomes larger for some unknown reason
p.remove();
p = applyOffset(op, true);
}
var b = p.visibleBounds;
if (getMinVisibleSize(b) > 10) {
activeDocument.selection = [p];
executeMenuCommand("expandStyle");
p = activeDocument.selection[0];
if (p.typename == "CompoundPathItem") {
b = findBestBounds(op, p);
}
}
p.remove();
return b;
}
function add_nums(n, xy, s) {
var txt = NUM_LAY.textFrames.add();
txt.contents = n;
txt.textRange.justification = Justification.CENTER;
txt.textRange.characterAttributes.size = s;
txt.position = [xy[0] - txt.width / 2, xy[1] + txt.height / 2];
}
function strokeComPath(compoundPath) {
var p = compoundPath.pathItems,
l = p.length,
i = 0;
for (; i < l; i++) {
// !p[i].closed && p[i].closed = true;
// p[i].stroked = true;
// p[i].filled = false;
}
};
Result (added the layer with numbers after run the script):
Final outlined version with numbers and the 'color palette'
Note: you have to ungroup and unmask the color artwork before you run the Script #2.
Here is the results for the rest examples:
As you can see the 'final' artwork still need a quite amount of additional manual work: to move or remove extra numbers.
And it makes sense to reduce the number of colors in original color artworks (perhaps it's possible to do with a script to some extent, as well).

performance.getEntrieByName(); not working on Wordpress Thumbnails images on Firefox

I'm creating a WordPress website and want to include a javascript that calculates the size in bytes of pages of the site. I've created this little script that I call with onload on the body.
<script type="text/javascript">
function getPageSize() {
console.log("tests begin");
// HTML size
var mypagesize;
var iTimePage = 0;
iTimePage = performance.getEntriesByName(window.location.href)[0];
mypagesize = iTimePage.transferSize / 1024.0;
// images size
var imgElems = window.document.getElementsByTagName('img');
console.log(imgElems);
var myimgsize = 0;
var iTimeImg = 0;
for (var i = 0, len = imgElems.length; i < len; i++) {
var url = imgElems[i].src || imgElems[i].href;
console.log(imgElems);
if (url && url.length > 0) {
iTimeImg = performance.getEntriesByName(url)[0];
console.log(url.length);
if (iTimeImg) {
myimgsize += (iTimeImg.transferSize / 1024.0);
}
}
}
//CSS size
var linkElems = window.document.getElementsByTagName('link');
var mylinksize = 0;
var iTimeLink = 0;
for (var i = 0, len = linkElems.length; i < len; i++) {
var url = linkElems[i].src || linkElems[i].href;
if (url && url.length > 0) {
iTimeLink = performance.getEntriesByName(url)[0];
if (iTimeLink) {
mylinksize += iTimeLink.transferSize / 1024.0;
}
}
}
//JS size
var scriptElems = window.document.getElementsByTagName('script');
var myscriptsize = 0;
var iTimeScript = 0;
for (var i = 0, len = scriptElems.length; i < len; i++) {
var url = scriptElems[i].src || scriptElems[i].href;
if (url && url.length > 0) {
iTimeScript = performance.getEntriesByName(url)[0];
if (iTimeScript) {
myscriptsize += iTimeScript.transferSize / 1024.0;
}
}
}
var pagesizereduce = Math.round(mypagesize + myimgsize + mylinksize + myscriptsize);
console.log("tests end");
console.log(mypagesize);
console.log(myimgsize);
console.log(mylinksize);
console.log(myscriptsize);
document.getElementById('desktop').innerHTML = pagesizereduce;
document.getElementById('mobile').innerHTML = pagesizereduce;
}
</script>
The only problem I have is for the images. it works perfectly on Chrome but on Firefox if my image is a featured image on WordPress, the performancegetEntriesByName(); is undefined. If the images are in the post it work perfectly.
Is there a problem with Mozilla handling js differently of chrome ? Or is it a WordPress problem with the featured images on Mozilla ?

Creating a card matching game

I want to create a card matching game but I have an issue showing the images that are supposed to be hidden. When I click on a card, the path of the image shows instead of the actual image.
Here are all the codes that I have written:
div#card_board {
background: #ccc;
border: #999 1px solid;
width: 710px;
height: 600px;
padding: 24px;
margin: 0px auto;
}
div#card_board>div {
background: url(cardQtion.jpg) no-repeat;
background-size: 100%;
border: #000 1px solid;
width: 114px;
height: 132px;
float: left;
margin: 10px;
padding: 20px;
font-size: 64px;
cursor: pointer;
text-align: center;
}
<script>
var cardArray = new Array();
cardArray[0] = new Image();
cardArray[0].src = 'cardA.jpg';
cardArray[1] = new Image();
cardArray[1].src = 'cardA.jpg';
cardArray[2] = new Image();
cardArray[2].src = 'cardB.jpg';
cardArray[3] = new Image();
cardArray[3].src = 'cardB.jpg';
cardArray[4] = new Image();
cardArray[4].src = 'cardC.jpg';
cardArray[5] = new Image();
cardArray[5].src = 'cardC.jpg';
cardArray[6] = new Image();
cardArray[6].src = 'cardD.jpg';
cardArray[7] = new Image();
cardArray[7].src = 'cardD.jpg';
cardArray[8] = new Image();
cardArray[8].src = 'cardE.jpg';
cardArray[9] = new Image();
cardArray[9].src = 'cardE.jpg';
cardArray[10] = new Image();
cardArray[10].src = 'cardF.jpg';
cardArray[11] = new Image();
cardArray[11].src = 'cardF.jpg';
var cardVal = [];
var cardIDs = [];
var cardBackFace = 0;
Array.prototype.cardMix = function() {
var i = this.length,
j, temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard() {
cardBackFace = 0;
var output = "";
cardArray.cardMix();
for (var i = 0; i < cardArray.length; i++) {
output += '<div id="card_' + i + '" onclick="cardBackcard(this,\'' + cardArray[i].src + '\')"></div>';
}
document.getElementById('card_board').innerHTML = output;
}
function cardBackcard(tile, val) {
if (tile.innerHTML == "" && cardVal.length < 2) {
tile.style.background = '#FFF';
tile.innerHTML = val;
if (cardVal.length == 0) {
cardVal.push(val);
cardIDs.push(tile.id);
} else if (cardVal.length == 1) {
cardVal.push(val);
cardIDs.push(tile.id);
if (cardVal[0] == cardVal[1]) {
cardBackFace += 2;
cardVal = [];
cardIDs = [];
if (cardBackFace == cardArray.length) {
alert("Board cleared... generating new board");
document.getElementById('card_board').innerHTML = "";
newBoard();
}
} else {
function card2Back() {
var card_1 = document.getElementById(cardIDs[0]);
var card_2 = document.getElementById(cardIDs[1]);
card_1.style.background = 'url(cardQtion.jpg) no-repeat';
card_1.innerHTML = "";
card_2.style.background = 'url(cardQtion.jpg) no-repeat';
card_2.innerHTML = "";
cardVal = [];
cardIDs = [];
}
setTimeout(card2Back, 700);
}
}
}
}
</script>
<body>
<div id="card_board"></div>
<script>
newBoard();
</script>
</body>
You have some less than optimal code and frankly mine is only a refactor of that and has much that can be improved - study up.
Given that, here is the refactor:
I really dislike event in markup SO I moved that click handler invocation right into the code.
I saw two sets of JavaScript in your page why? I simply put them both in one.(see the last line of this).
Your array of images thing was not working and verbose so I used an array of names and created an array of images from that.
Insertion of an element is different than text so I used tile.appendChild(cardArray[cardIndex]); instead
Code:
// create an array of card images
var cardArray = [];
var cards = ['cardA.jpg', 'cardB.jpg', 'cardC.jpg', 'cardD.jpg', 'cardE.jpg', 'cardF.jpg'];
for (var i = 0; i < cards.length; i++) {
var im = new Image();
im.src = cards[i];
im.alt = cards[i];
cardArray.push(im);
cardArray.push(im);
}
var cardVal = [];
var cardIDs = [];
var cardBackFace = 0;
Array.prototype.cardMix = function() {
var i = this.length,
j, temp;
while (--i > 0) {
j = Math.floor(Math.random() * (i + 1));
temp = this[j];
this[j] = this[i];
this[i] = temp;
}
}
function newBoard() {
cardBackFace = 0;
var output = "";
cardArray.cardMix();
for (var i = 0; i < cardArray.length; i++) {
output += '<div id="card_' + i + '" class="cardcontainer" data-card="' + i + '"></div>';
}
document.getElementById('card_board').innerHTML = output;
var classname = document.getElementsByClassName("cardcontainer");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', cardBackcard, false);
}
}
function card2Back() {
var card_1 = document.getElementById(cardIDs[0]);
var card_2 = document.getElementById(cardIDs[1]);
card_1.style.background = "url('cardQtion.jpg') no-repeat";
card_1.innerHTML = "";
card_2.style.background = "url('cardQtion.jpg') no-repeat";
card_2.innerHTML = "";
cardVal = [];
cardIDs = [];
}
function cardBackcard() {
// these used to be in the HTML as parameters, I refactored to pass `this`
// and then use the attribute which is the index of the card it had
var tile = this;
//multiply by 1 to get number, could use parseInt but I did not
var cardIndex = this.getAttribute("data-card") *1;
if (!(tile.innerHTML == "" && cardVal.length < 2)) return;
tile.style.background = '#FFF';
tile.appendChild(cardArray[cardIndex]);
if (!(cardVal.length == 0 && cardVal[0] == cardVal[1])) return;
cardVal.push(cardIndex);
cardIDs.push(tile.id);
if (cardVal.length == 1) {
if (cardVal[0] == cardVal[1]) {
cardBackFace += 2;
cardVal = [];
cardIDs = [];
if (cardBackFace == cardArray.length) {
alert("Board cleared... generating new board");
document.getElementById('card_board').innerHTML = "";
newBoard();
}
} else {
setTimeout(card2Back, 700);
}
}
}
newBoard();

Make other nodes follow when dragging a node in Cytoscape.js

I'm new to cytoscape.js, I just want to make other nodes follow when dragging one node.
Appreciate your help
Write a listener, and update the other node positions appropriately in your callback:
eles.on()
node.position()
Here is how I did it. Note you have to save off the original positions at the grab event, and then update during the drag event.
function add_drag_listeners()
{
var all = cy.elements("node");
for (j = 0; j < all.length; j++)
{
cynode = all[j];
cynode.on("grab",handle_grab);
cynode.on("drag",handle_drag);
}
}
var grab_x = 0;
var grab_y = 0;
var drag_subgraph = [];
function handle_grab(evt)
{
grab_x = this.position().x ;
grab_y = this.position().y ;
var succ = this.successors();
drag_subgraph = [];
var succstr = "";
for (i = 0; i < succ.length; i++)
{
if (succ[i].isNode())
{
var old_x = succ[i].position().x;
var old_y = succ[i].position().y;
succstr += " " + succ[i].data("id");
drag_subgraph.push({old_x:old_x, old_y:old_y, obj:succ[i]});
}
}
}
function handle_drag(evt)
{
var new_x = this.position().x;
var new_y = this.position().y;
var delta_x = new_x - grab_x;
var delta_y = new_y - grab_y;
for (i = 0; i < drag_subgraph.length; i++)
{
var obj = drag_subgraph[i].obj;
var old_x = drag_subgraph[i].old_x;
var old_y = drag_subgraph[i].old_y;
var new_x = old_x + delta_x;
var new_y = old_y + delta_y;
obj.position({x:new_x, y:new_y});
}
}

Detect coherent neighbors / neighborhood in 2d array

Im having an arbitrary 2d array and each field has an id and a teamid (here illustrated as colors 1).
I want for every neighborhood an array with the ids
in it.
A neighborhood consists of fields with neighbors with the same teamid horizontally and vertically (not diagonally)
e.g.:
This is what i have:
array[0][0] = {id:1,teamId:1}
array[1][0] = {id:2,teamId:1}
array[2][0] = {id:3,teamId:0}
array[3][0] = {id:4,teamId:2}
array[4][0] = {id:5,teamId:2}
array[5][0] = {id:6,teamId:0}
array[0][1] = {id:7,teamId:1}
array[1][1] = {id:8,teamId:1}
array[2][1] = {id:9,teamId:1}
array[3][1] = {id:10,teamId:2}
array[4][1] = {id:11,teamId:2}
array[5][1] = {id:12,teamId:0}
//and so on..
This is what i want:
neighborhood[1] = [1,2,7,8,9,13,14]
neighborhood[2] = [4,5,10,11]
neighborhood[3] = [16,22,23,24,29,30]
neighborhood[4] = [25,31,32,37,38]
neighborhood[5] = [35,41]
I am not searching for the images, but for the array
neighborhood
thanks in advance!
You can use the logic from dots and block games. A block belongs to a player if he has surrounded it with the walls. So, you need for each cell also 4 walls except for the outer cells. To test if a cell is closed you can use 4 class variables:
var Block = function() {
this.isclosed=0;
this.left=0;
this.top=0;
this.right=0;
this.bottom=0;
return this;
}
Block.prototype = {
isClosed : function () {
if (this.isclosed==true) {
return false;
} else if (this.left && this.top && this.right && this.bottom) {
this.isclosed=true;
return true;
} else {
return this.left && this.top && this.right && this.bottom;
}
}
}
You can try my implementations of dots and blocks game # https://dotsgame.codeplex.com/.
The method for solving this issue is refered as Connected Component Labelling
A similar question was asked once before from which i have my solution:
// matrix dimensions
var row_count = 20;
var col_count = 20;
var numOfTeams = 2;
// the input matrix
var m = [];
// the labels, 0 means unlabeled
var label = [];
var source = document.getElementById("source");
for (var i = 0; i < row_count; i++) {
var row = source.insertRow(0);
m[i] = [];
label[i] = [];
for (var j = 0; j < col_count; j++) {
//m[i][j] = Math.round(Math.random());
m[i][j] = getRandomInt(0, numOfTeams + 1);
label[i][j] = 0;
var cell1 = row.insertCell(0);
cell1.innerHTML = m[i][j];
}
}
// direction vectors
var dx = [1, 0, -1, 0];
var dy = [0, 1, 0, -1];
function dfs(x, y, current_label, team) {
if (x < 0 || x == row_count) return; // out of bounds
if (y < 0 || y == col_count) return; // out of bounds
if (label[x][y] || team != m[x][y]) return; // already labeled or not marked with 1 in m
// mark the current cell
label[x][y] = current_label;
// recursively mark the neighbors
for (var direction = 0; direction < 4; ++direction) {
dfs(x + dx[direction], y + dy[direction], current_label, team);
}
}
function find_components() {
var component = 0;
for (var i = 0; i < row_count; ++i) {
for (var j = 0; j < col_count; ++j) {
if (!label[i][j] && m[i][j]) dfs(i, j, ++component, m[i][j]);
}
}
}
find_components();
var result = document.getElementById("result");
for (var i in label) {
var string = ""
var row = result.insertRow(0);
for (var j in label[i]) {
string += label[i][j] + " "
var cell1 = row.insertCell(0);
cell1.innerHTML = label[i][j];
}
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
table tr td {
min-width: 14px
}
<div style="float:left">
<table id="source"></table>
</div>
<div style="float:right">
<table id="result"></table>
</div>

Categories

Resources