how to fill the DIV container with elements based on container's actual size? - layout

I have a DIV container somewhere on the page with min-width and min-height set to some values.
I am loading small panels (DIVs with display:inline-block) into it using callbacks and javascript.
Right now the number of panels is fixed, so that when the user maximizes the browser window, the size of the container increases, and white space appears at the end of last line.
I want to catch the container's size changes, and load more elements, as many as will fit without clipping into the container's new space.
I saw this on amazon.com. They have panels that display 4 products, but if the browser window is maximized, same panels will display more products filling all the available space in the container.
Scroll-bars must not appear, and no clipping of elements must be done.
Is there a script I could use, or sample code?
Thank you,
Andrei

Found a very nice solution to the problem.
Here's the code: (term 'display' here is used in the same sense as at the supermarket):
function updateDisplay() {
$(".s2", this).hide();
var x = $(".s2", this);
var prevPos = -1;
var nrows = 2;
for (var i = 0; i < x.length; i++) {
$(x[i]).toggle();
var curPos = $(x[i]).position().left;
if (curPos < prevPos) {
if (--nrows == 0) {
$(x[i]).toggle();
break;
}
}
prevPos = curPos;
}
}
function updateDisplays() {
$(".dcon").each(updateDisplay);
}
$(window).resize(updateDisplays);
$(document).ready(updateDisplays);
You can see it in action on the following pages:
www.megabit-mich.ru
www.sportolimpia.ru

Related

Painting individual pixels quickly in P5.js

I am trying to make an old TV static type effect in P5.js, and although I am able to make the effect work, the frame rate is quite low.
My approach is the following:
Loop through each pixel
Set the stroke to a random value
Call the point() function to paint the pixel
Initially, I was doing this in the draw function directly but it was very slow. I was getting less than 1 frame a second. So I switch to the following paint buffer approach:
const SCREEN_WIDTH = 480
const SCREEN_HEIGHT = 480
var ScreenBuffer;
function setup(){
createCanvas(SCREEN_WIDTH, SCREEN_HEIGHT);
ScreenBuffer = createGraphics(SCREEN_WIDTH,SCREEN_HEIGHT);
}
function draw(){
paintBuffer();
image(ScreenBuffer,0,0);
}
function paintBuffer(){
console.log("Painting Buffer")
for(var x = 0; x< SCREEN_WIDTH; x++){
for(var y = 0; y< SCREEN_HEIGHT; y++){
ScreenBuffer.stroke(Math.random() * 255)
ScreenBuffer.point(x,y)
}
}
}
Although I am getting a performance improvement, its nowhere near the 30 frames a second I want to be at. Is there a better way to do this?
The only way I can get reasonable performance is by filling up the screen with small squares instead with the following code:
for(var x = 0; x< SCREEN_WIDTH-10; x+=10){
for(var y = 0; y< SCREEN_HEIGHT-10; y+=10){
//ScreenBuffer.stroke(Math.random() * 255)
//ScreenBuffer.point(x,y)
ScreenBuffer.fill(Math.random() * 255);
ScreenBuffer.noStroke()
ScreenBuffer.rect(x,y,10,10)
}
}
But I would really like a pixel effect - ideally to fill the whole screen.
Believe it or not, it's actually the call to stroke() that's slowing down your sketch. You can get around this by setting the value of the pixels directly, using the set() function or accessing the pixels array directly.
More info can be found in the reference, but here's a simple example:
function setup() {
createCanvas(500, 500);
}
function draw() {
for (var i = 0; i < width; i++) {
for (var j = 0; j < height; j++) {
var c = random(255);
set(i, j, c);
}
}
updatePixels();
text(frameRate(), 20, 20);
}
Another approach you might consider is generating a few buffers that contain static images ahead of time, and then using those to draw your static. There's really no need to make the static completely dynamic, so do the work once and then just load from image files or buffers created using the createGraphics() function.

How do you associate DOM elements with tween.js?

How do you relate TWEEN.js to a DOM element to do some complicated (or simple) animation effects on this DOM element?
I got a demo on the Internet, you need to create a sophisticated animation (using three.js) and DOM (to show or hide the elements associated with a TWEEN.js to DOM elements, DOM elements) has been written in the inside of the HTML (just slow to show or hide the effect).
The implementation of the clickMeOk method has achieved animation effects, but I hope to perform another effect at the same time - the display or hiding of text descriptions (shown or hidden with animation)
var isMeTweening = false;
function clickMeOk() {
if (isMeTweening)
return;
isMeTweening = true;
var scale = mesh6.scale.x < 1 ? 1 : 0.001;
new TWEEN.Tween(mesh6.scale)
.to({ x: scale, y: scale, z: scale }, 2000)
.easing(TWEEN.Easing.Quartic.InOut)
.onComplete(function() {
isMeTweening = false;
}).start();
var opacity = mesh6.material.opacity > 0 ? 0 : 0.5;
new TWEEN.Tween(mesh6.material).to({ opacity: opacity }, 1800).easing(TWEEN.Easing.Quartic.InOut).start();
//Here you want to add DOM element animation (display or hide)
}
Thanks !
I think You should use CSS to make animations on DOM Elements.
https://www.w3schools.com/css/css3_animations.asp

Smartgwt addMember changes top of parent

I have several nested layouts (VLayouts and HLayouts), which are included inside a tab pane. In one of these layouts (VLayout), there is severall elements which are added or removed dynamically depending on a window of selection. The first time the user makes a selection, the pane moves up several pixels (and you will not see the upper part of the pane). The rest of times, the pain remains in the wrong place.
In summary, the first adding affects to the top of the pane, and the rest of adding/removing doesn't affect to it.
This only happens on Chrome. However, Firefox and IE work ok.
My code of adding is:
int total = itemsPanel.getMembers().length - 1;
while (total >=0) {
itemsPanel.removeMember(itemsPanel.getMember(total));
total--;
}
Record[] records = selectorWindow.getSelectedRows();
if (records != null) {
for (Record record : records) {
String name = record.getAttribute("keyRecord");
HLayout item = items.get(name);
itemsPanel.addMember(row);
}
}
if (itemsPanel != null) {
int r = 80;
if (Utils.isReducedHeight()) {
r = 120;
}
int visibleHeight = getVisibleHeight() - StyleUtils.HEADER_HEIGHT - r;
itemsPanel.setHeight(Math.max(1, Math.min(itemsPanel.getMembers().length * Utils.getRowHeight(), visibleHeight)));
int h = Math.min(itemsPanel.getHeight() + 10, visibleHeight);
containerItemsPanel.setHeight(h);
}
I'm using gwt 2.5.1 and smartgwt 3.0. Any idea?
Thanks in advance

How to avoid the overlapping of text elements on the TreeMap when child elements are opened in D3.js?

I created a Tree in D3.js based on Mike Bostock's Node-link Tree. The problem I have and that I also see in Mike's Tree is that the text label overlap/underlap the circle nodes when there isn't enough space rather than extend the links to leave some space.
As a new user I'm not allowed to upload images, so here is a link to Mike's Tree where you can see the labels of the preceding nodes overlapping the following nodes.
I tried various things to fix the problem by detecting the pixel length of the text with:
d3.select('.nodeText').node().getComputedTextLength();
However this only works after I rendered the page when I need the length of the longest text item before I render.
Getting the longest text item before I render with:
nodes = tree.nodes(root).reverse();
var longest = nodes.reduce(function (a, b) {
return a.label.length > b.label.length ? a : b;
});
node = vis.selectAll('g.node').data(nodes, function(d, i){
return d.id || (d.id = ++i);
});
nodes.forEach(function(d) {
d.y = (longest.label.length + 200);
});
only returns the string length, while using
d.y = (d.depth * 200);
makes every link a static length and doesn't resize as beautiful when new nodes get opened or closed.
Is there a way to avoid this overlapping? If so, what would be the best way to do this and to keep the dynamic structure of the tree?
There are 3 possible solutions that I can come up with but aren't that straightforward:
Detecting label length and using an ellipsis where it overruns child nodes. (which would make the labels less readable)
scaling the layout dynamically by detecting the label length and telling the links to adjust accordingly. (which would be best but seems really difficult
scale the svg element and use a scroll bar when the labels start to run over. (not sure this is possible as I have been working on the assumption that the SVG needs to have a set height and width).
So the following approach can give different levels of the layout different "heights". You have to take care that with a radial layout you risk not having enough spread for small circles to fan your text without overlaps, but let's ignore that for now.
The key is to realize that the tree layout simply maps things to an arbitrary space of width and height and that the diagonal projection maps width (x) to angle and height (y) to radius. Moreover the radius is a simple function of the depth of the tree.
So here is a way to reassign the depths based on the text lengths:
First of all, I use the following (jQuery) to compute maximum text sizes for:
var computeMaxTextSize = function(data, fontSize, fontName){
var maxH = 0, maxW = 0;
var div = document.createElement('div');
document.body.appendChild(div);
$(div).css({
position: 'absolute',
left: -1000,
top: -1000,
display: 'none',
margin:0,
padding:0
});
$(div).css("font", fontSize + 'px '+fontName);
data.forEach(function(d) {
$(div).html(d);
maxH = Math.max(maxH, $(div).outerHeight());
maxW = Math.max(maxW, $(div).outerWidth());
});
$(div).remove();
return {maxH: maxH, maxW: maxW};
}
Now I will recursively build an array with an array of strings per level:
var allStrings = [[]];
var childStrings = function(level, n) {
var a = allStrings[level];
a.push(n.name);
if(n.children && n.children.length > 0) {
if(!allStrings[level+1]) {
allStrings[level+1] = [];
}
n.children.forEach(function(d) {
childStrings(level + 1, d);
});
}
};
childStrings(0, root);
And then compute the maximum text length per level.
var maxLevelSizes = [];
allStrings.forEach(function(d, i) {
maxLevelSizes.push(computeMaxTextSize(allStrings[i], '10', 'sans-serif'));
});
Then I compute the total text width for all the levels (adding spacing for the little circle icons and some padding to make it look nice). This will be the radius of the final layout. Note that I will use this same padding amount again later on.
var padding = 25; // Width of the blue circle plus some spacing
var totalRadius = d3.sum(maxLevelSizes, function(d) { return d.maxW + padding});
var diameter = totalRadius * 2; // was 960;
var tree = d3.layout.tree()
.size([360, totalRadius])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 2) / a.depth; });
Now we can call the layout as usual. There is one last piece: to figure out the radius for the different levels we will need a cumulative sum of the radii of the previous levels. Once we have that we simply assign the new radii to the computed nodes.
// Compute cummulative sums - these will be the ring radii
var newDepths = maxLevelSizes.reduce(function(prev, curr, index) {
prev.push(prev[index] + curr.maxW + padding);
return prev;
},[0]);
var nodes = tree.nodes(root);
// Assign new radius based on depth
nodes.forEach(function(d) {
d.y = newDepths[d.depth];
});
Eh voila! This is maybe not the cleanest solution, and perhaps does not address every concern, but it should get you started. Have fun!

Win32 Text Drawing Puzzle

I've got a little text drawing puzzle under Win32. I'm trying to draw some instructions for users of my application at the top of the window.
Please refer to the following window (I've changed the background color on the text so you can see the boundaries)
(source: billy-oneal.com)
I'm currently using DrawTextEx to draw the text to my window, but the problem is that it does not fill the entire RECTangle that I give it. Not drawing that area is just fine, until the window resizes:
(source: billy-oneal.com)
When the text is re wrapped due to the window sizing, because DrawTextEx doesn't clear it's background, these artifacts are leftover.
I tried using FillRect to fill in the area behind the text drawing call, which does eliminate the visual artifacts, but then causes the text to flicker constantly, as it is completely erased and then completely redrawn to the display.
Any ideas on how one might get the area not containing text to be drawn with the background color?
EDIT: I'd like to avoid having to double buffer the form if at app possible.
EDIT2: I solved the problem by only redrawing the text when I detect that the wrapping changes during a resize.
Use double buffering?
Draw everything to a bitmap and draw the bitmap to the window. Flickering is commonly a double buffering issue.
There are many possible solutions and without seeing your code, it's hard to tell which method would be best so I'd suggest taking a look at this article on flicker free drawing
SetBkMode + SetBkColor ?
Well since nobody seems to know what to do about it, I implemented it this way:
std::vector<std::wstring> wrapString(HDC hDC, const std::wstring& text, const RECT& targetRect, HFONT font)
{
std::vector<std::wstring> result;
RECT targetRectangle;
CopyRect(&targetRectangle, &targetRect);
//Calculate the width of the bounding rectangle.
int maxWidth = targetRectangle.right - targetRectangle.left;
//Draw the lines one at a time
std::wstring currentLine;
for(std::wstring::const_iterator it = text.begin(); it != text.end(); currentLine.push_back(*it), it++)
{
if(*it == L'\r' || *it == L'\n')
{ //Hard return
while(it != text.end() && (*it == L'\r' || *it == L'\n')) it++;
result.push_back(currentLine);
currentLine.clear();
}
else
{ //Check for soft return
SIZE sizeStruct;
GetTextExtentPoint32(hDC, currentLine.c_str(), static_cast<int>(currentLine.length()), &sizeStruct);
if (sizeStruct.cx > maxWidth)
{
std::wstring::size_type lineLength = currentLine.find_last_of(L' ');
if (lineLength == currentLine.npos)
{ //Word is longer than a line.
for(;it != text.end() && !iswspace(*it);it++) currentLine.push_back(*it);
}
else
{ //Clip word to line.
//Backtrack our scan of the source text.
it -= currentLine.length() - lineLength - 1;
//Remove the clipped word
currentLine.erase(lineLength);
}
result.push_back(currentLine);
currentLine.clear();
}
}
}
//Last remaining text.
result.push_back(currentLine);
return result;
}
void DrawInstructionsWithFilledBackground(HDC hDC, const std::wstring& text, RECT& targetRectangle, HFONT font, COLORREF backgroundColor)
{
//Set up our background color.
int dcIdx = SaveDC(hDC);
HBRUSH backgroundBrush = CreateSolidBrush(backgroundColor);
SelectObject(hDC, backgroundBrush);
SelectObject(hDC, font);
SetBkColor(hDC, backgroundColor);
std::vector<std::wstring> lines(wrapString(hDC, text, targetRectangle, font));
for(std::vector<std::wstring>::const_iterator it = lines.begin(); it!=lines.end(); it++)
{
RECT backgroundRect = targetRectangle;
DrawText(hDC, const_cast<LPWSTR>(it->c_str()), static_cast<int>(it->length()), &backgroundRect, DT_CALCRECT | DT_NOCLIP | DT_SINGLELINE);
backgroundRect.left = backgroundRect.right;
backgroundRect.right = targetRectangle.right;
if (backgroundRect.right >= backgroundRect.left)
FillRect(hDC, &backgroundRect, backgroundBrush);
ExtTextOut(hDC, targetRectangle.left, targetRectangle.top, ETO_OPAQUE, NULL, it->c_str(), static_cast<UINT>(it->length()), NULL);
targetRectangle.top += backgroundRect.bottom - backgroundRect.top;
}
instructionsWrap = lines;
//Restore the DC to it's former glory.
RestoreDC(hDC, dcIdx);
DeleteObject(backgroundBrush);
}
Get/Calculate the rect used by the DrawText call and clip it with something like ExcludeClipRect before calling FillRect

Resources