Show me a Javascript implementation of webkitConvertPointFromPageToNode - math

The webkitConvertPointFromPageToNode(in Node node, in WebKitPoint p) method is awesome; give it a DOM node and a point in page-coordinates (say, the mouse cursor position) and it will give a coordinate back to you in that node's local coordinate system. Unfortunately, it's currently only available in webkit.
# Choose a node into which we'll map the mouse coordinates
node = $('#subjectElement').get(0)
handleMouseMove = (e) ->
# Convert the mouse position to a Point
mousePoint = new WebKitPoint(e.pageX, e.pageY)
# Convert the mouse point into node coordinates using WebKit
nodeCoords = webkitConvertPointFromPageToNode(node, mousePoint)
# Attach a handler to track the mouse position
$(document).on 'mousemove', handleMouseMove
I've thrown my entire math-brain at the problem, but no matter how close I get, my implementation falls apart with one extra level of composition, or the application of 3D perspective.
It's time for a convertPointFromPageToNode polyfill that works as well as the WebKit implementation, in 3D. #4esn0k gave one a shot, but it only solves the 2D case.
Can you write one that makes this JSFiddle work?
http://jsfiddle.net/steveluscher/rA27K/

This seems like an amazing question, but there is an ALMOST duplicate right here: How to get the MouseEvent coordinates for an element that has CSS3 Transform? but nobody is looking at my answer there and this seems to be much more general so I'll post it again here, with a few modifications to make it more clear:
Basically, it works by doing this: split the element you are trying to find relative coordinates for, and split it into 9 smaller elements. Use document.elementFromPoint to find if the coordinate is over that mini-element. If it is, split that element into 9 more elements, and keep doing this until a pretty accurate coordinate is possible. Then use getBoundingClientRect to find the on-screen coordinates of that mini-element. BOOM!
jsfiddle: http://jsfiddle.net/markasoftware/rA27K/8/
Here is the JavaScript function:
function convertPointFromPageToNode(elt,coords){
///the original innerHTML of the element
var origHTML=elt.innerHTML;
//now clear it
elt.innerHTML='';
//now save and clear bad styles
var origPadding=elt.style.padding=='0px'?'':elt.style.padding;
var origMargin=elt.style.margin=='0px'?'':elt.style.margin;
elt.style.padding=0;
elt.style.margin=0;
//make sure the event is in the element given
if(document.elementFromPoint(coords.x,coords.y)!==elt){
//reset the element
elt.innerHTML=origHTML;
//and styles
elt.style.padding=origPadding;
elt.style.margin=origMargin;
//we've got nothing to show, so return null
return null;
}
//array of all places for rects
var rectPlaces=['topleft','topcenter','topright','centerleft','centercenter','centerright','bottomleft','bottomcenter','bottomright'];
//function that adds 9 rects to element
function addChildren(elt){
//loop through all places for rects
rectPlaces.forEach(function(curRect){
//create the element for this rect
var curElt=document.createElement('div');
//add class and id
curElt.setAttribute('class','offsetrect');
curElt.setAttribute('id',curRect+'offset');
//add it to element
elt.appendChild(curElt);
});
//get the element form point and its styling
var eltFromPoint=document.elementFromPoint(coords.x,coords.y);
var eltFromPointStyle=getComputedStyle(eltFromPoint);
//Either return the element smaller than 1 pixel that the event was in, or recurse until we do find it, and return the result of the recursement
return Math.max(parseFloat(eltFromPointStyle.getPropertyValue('height')),parseFloat(eltFromPointStyle.getPropertyValue('width')))<=1?eltFromPoint:addChildren(eltFromPoint);
}
//this is the innermost element
var correctElt=addChildren(elt);
//find the element's top and left value by going through all of its parents and adding up the values, as top and left are relative to the parent but we want relative to teh wall
for(var curElt=correctElt,correctTop=0,correctLeft=0;curElt!==elt;curElt=curElt.parentNode){
//get the style for the current element
var curEltStyle=getComputedStyle(curElt);
//add the top and left for the current element to the total
correctTop+=parseFloat(curEltStyle.getPropertyValue('top'));
correctLeft+=parseFloat(curEltStyle.getPropertyValue('left'));
}
//reset the element
elt.innerHTML=origHTML;
//restore element styles
elt.style.padding=origPadding;
elt.style.margin=origMargin;
//the returned object
var returnObj={
x: correctLeft,
y: correctTop
}
return returnObj;
}
IMPORTANT!!! You must also include this CSS for it to work:
.offsetrect{
position: absolute;
opacity: 0;
height: 33.333%;
width: 33.333%;
}
#topleftoffset{
top: 0;
left: 0;
}
#topcenteroffset{
top: 0;
left: 33.333%;
}
#toprightoffset{
top: 0;
left: 66.666%;
}
#centerleftoffset{
top: 33.333%;
left: 0;
}
#centercenteroffset{
top: 33.333%;
left: 33.333%;
}
#centerrightoffset{
top: 33.333%;
left: 66.666%;
}
#bottomleftoffset{
top: 66.666%;
left: 0;
}
#bottomcenteroffset{
top: 66.666%;
left: 33.333%;
}
#bottomrightoffset{
top: 66.666%;
left: 66.666%;
}
ALSO: I modified a little of your css by giving the "grandfather" div an id and referencing to it in your css using #div1 instead of div because my code generates divs, and your div styles were also applying to the ones my code uses and messed it up
ONE LAST THING: I don't know CoffeeScript so I adjusted your code to make it pure JavaScript. Sorry about that.

I have written some TypeScript code which does some transformations:
jsidea core library. Its not stable yet (pre alpha).
You can use it like that:
Create you transform instance:
var transformer = jsidea.geom.Transform.create(yourElement);
The box model you want to transform to (default:"border"):
var toBoxModel = "border";
The box model where your input coordinates coming from (default:"border"):
var fromBoxModel = "border";
Tranform your global coordinates (here {x:50, y:100, z: 0}) to local space. The resulting point has 4 components: x, y, z and w.
var local = transformer.globalToLocal(50, 100, 0, toBoxModel, fromBoxModel);
I have implemented some other functions like localToGlobal and localToLocal.
If you want to give a try, just download the release build and use the jsidea.min.js.

I have this issue and started trying to compute the matrix.
I started a library around it: https://github.com/ombr/referentiel
$('.referentiel').each ->
ref = new Referentiel(this)
$(this).on 'click', (e)->
input = [e.pageX, e.pageY]
p = ref.global_to_local(input)
$pointer = $('.pointer', this)
$pointer.css('left', p[0]-1)
$pointer.css('top', p[1]-1)
What do you think ?

Related

Create a circular or triangular shaped board

I'm trying to create a game board ( similar to a chess board) for a game in react, and I would like to arrenge the cells (rectangular divs, that take they're value from a state array) in different shapes ( circle, triangle, oval etc) thus creating a board of that shape.
I only know how to arrange divs with CSS flex or grid and that is always rectangular formation (as far as I know)
How can I achieve this?
Any help will be appreciated, thanks!
To dynamically position elements, you need to arrange them in code. We can do that by creating the elements in code, then setting their position programmatically. I'm working off this jsfiddle
First, the HTML:
<div id="my_container" />
It couldn't get simpler. We just want somewhere we can put our elements. Now, for minimal styling, we've got:
#my_container {
position: relative;
width: 200px;
height: 200px;
background-color: powderblue
}
.cell {
background-color: red;
width: 5px;
height: 5px;
position: absolute;
}
I've added colors so that you can see the elements in the generated output, but they're not necessary. What is necessary is those position lines. Making the #container div relative lets it behave nicely with whatever it's placed in, and making each of the .cell divs absolute causes them to be placed on absolute coordinates relative to their parent, which means we can put them where we want. Ok, what's next?
The cells. I assume your cells already exist, but since I don't have them, I've created code to build these cells, shown below:
const container = document.getElementById("my_container");
const number_of_cells = 30;
const cells = [];
for (var i = 0; i < number_of_cells; i++)
{
const newDiv = document.createElement("div");
newDiv.classList.add("cell");
container.appendChild(newDiv)
cells.push(newDiv);
}
The goal here is to put the cells as children of #my_container and also create an array of all the cells. (I think maybe this step is redundant but I don't care...It makes the next step easier.)
function PositionCells(cells, x, y, radius)
{
const incr_angle = (2*Math.PI)/cells.length;
for (let i = 0; i < cells.length; i++) {
var new_x = x+radius * Math.cos(incr_angle * i);
var new_y = y+radius * Math.sin(incr_angle * i);
cells[i].style.left = new_x+'px';
cells[i].style.top = new_y+'px';
}
}
PositionCells(cells, 50,50,30);
Basically what I've done is written a function to position all the cells in an ordered, programmatic way. If you want other shapes, you can pretty easily do the math to come up with where to position them.
And that's it!

How to display an image progressively by chunks?

I'm trying to make a loading animation for a website : an image full of candles, each candle's appearing as the website loads. My mains objectives are :
Use minimal bandwidth
Maximize the picture quality
Create transition between each parts of the picture
So,
I tried to use the Photoshop legacy Export for Web features but the alpha layer (transparency) that I want to use in PNG is then tessellated, they are also subtle noise on some images.
I thought about using a video with embedded transitions but even a VP9 video is bigger than the PNG trick.
Using JPEG as well doesn't look great as I can't use transparency and the sum of all pictures are bigger than the PNG trick.
So that's why I wanted to know if someone had any idea how to do such thing ! I would be please to add more information about this if asked !
Edit
Here's the first picture of the sequence (without any edit to add transparency) :
And here's the last, there's 19 images total :
If you want to light each candle individually, I wouldn't know how to do that without using too many images, hence too much bandwidth. I can therefore not provide a solution that perfectly suits your requirements. I will, however, suggest an interim solution that might work until someone comes up with something better.
Idea:
Group the 30+ candles into three chunks, as they seem to be arranged in roughly three rows.
Although a bit tricky, the rock geometry does lend itself to be cut out accordingly as well.
Breakdown:
Create four pictures / layers:
All dark
One row lit
Two rows lit
All rows lit
Use JPG, as small as possible (maybe 1280px in width, ~70% quality)
Instead of using img, use one div with CSS background-image per layer
Place all layers on top of each other (layer 4 on top) with position: absolute
Use JavaScript to fade in another layer whenever a third of your page has loaded
The reason for using background-image is that you can easily use CSS to stretch the div containers to 100% width and height (assuming that the whole thing is supposed to be full screen) and make the images adapt to any resolution and aspect ratio easily. Upscaling a 1280px wide JPG to 1920px usually looks pretty okay, but you will have to play with image size and JPG quality to hit the sweet spot. With my suggested setup (see above), all four images should end up being about 400 to 500 KB combined.
Example:
Note that this is a rough mockup based on your first and last frame - you can surely do much better with the original material at hand.
var timer = new Array(3);
var fader = new Array(3);
var layer = new Array(3);
function fade() {
for (var i=0; i<3; ++i) {
layer[i] = document.getElementById("s" + (i+1));
layer[i].style.opacity = 0.0;
clearTimeout(timer[i]);
clearInterval(fader[i]);
start(i);
}
}
function start(i) {
timer[i] = setTimeout(function() {
fader[i] = setInterval(opacity, 20, i);
}, (2000*i));
}
function opacity(i) {
var style = window.getComputedStyle(layer[i], null);
var opacity = parseFloat(style.getPropertyValue("opacity"));
if (opacity >= 1) {
clearInterval(fader[i]);
} else {
layer[i].style.opacity = (opacity + 0.01);
}
}
.container {
position: relative;
width: 600px;
height: 417px;
}
.candles {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
opacity: 0.0;
background-size: 100%;
background-repeat: no-repeat;
background-position: center center;
}
#s0 {
background-image: url(http://i.imgur.com/ZQqeebI.jpg);
opacity: 1.0;
}
#s1 {
background-image: url(http://i.imgur.com/ah7UP3x.jpg);
}
#s2 {
background-image: url(http://i.imgur.com/zLgBA5x.jpg);
}
#s3 {
background-image: url(http://i.imgur.com/ar4w18n.jpg);
}
button {
width: 600px;
padding: 0.4em;
}
<div class="container">
<div id="s0" class="candles"></div>
<div id="s1" class="candles"></div>
<div id="s2" class="candles"></div>
<div id="s3" class="candles"></div>
</div>
<button onclick="fade()">Fade</button>
Here is an external link to the fiddle.

Keeping css attributes in an iterated dart template

I'm working on a Dart project where the user is able to add new custom elements at the click of a button. Each custom element is a div containing a table. The divs are resizeable by the user. My problem is that after a new element is added to the list of elements held by my dart file, the sizes of all the divs are automatically reset. Is there any way to add new elements to the template while keeping the attributes of the old ones the same?
Here is my CSS code that deals with the main divs in my custom element:
#superDivContainer {
border: 2px solid black;
resize: both;
display: inline-block;
}
#tableContainer {
height: 125px;
overflow: scroll;
}
Thanks in advance for the help!
When you change the backing list, the template reiterates, destroying all the old elements and recreating them from scratch, so all user resize information is lost.
When you add a new item to the list, you can store all the sizing information of the old elements and then after the item is added set the new elements size:
// Stores size information
List<List> sizes = [];
void add() {
// Store the old sizes
sizes.clear();
ElementList divs = queryAll(".superDivContainer");
for(int i = 0; i < divs.toList().length; i++) {
Element div = divs[i];
sizes.add([div.style.width, div.style.height]);
}
// Add the new item
yourList.add("new");
// Set the sizes of the new elements
Timer timer = new Timer(new Duration(milliseconds: 1), () {
divs = queryAll(".superDivContainer");
for(int i = 0; i < divs.toList().length && i < sizes.length; i++) {
Element div = divs[i];
div.style.width = sizes[i][0];
div.style.height = sizes[i][1];
}
});
}
Two notes:
I changed superDivContainer to be a class instead of an id since it seems that you are applying it to multiple elements; you will need to change your CSS reflect that
The 1 millisecond timer gets around the fact that there is a tiny delay until the new elements are added and accessible

CSS positioning with JavaScript-generated divs not working how I expected

First off, I must apologize. CSS positioning has always been the bane of my existence and this is likely something simple that I'm just completely missing...
Anyway, I have a JS script that's generating divs. Each div is within the parent #container which is absolute positioned. CSS below:
#container{
position: absolute;
}
#container div{
position: relative;
}
The function creating the divs is:
function newLine(){
var id_num = ++line;
var _new;
var i;
for(i = 0; i < width; i++){
_new = document.createElement('div');
_new.innerHTML = randomChar();
_new.id = id_num;
_new.style.left = i*10+'px';
_new.style.top = 0;
document.getElementById('container').appendChild(_new);
}
}
Everything above is properly initialized. The left positioning works perfectly. The only issue is the vertical positioning. Instead of all the row displaying next to each other, they're progressively increasing away from the top of the div. I'm sure this is something trivial that I'm completely looking over, but I'm stumped... Help would be very much appreciated!
The rows as position: relative - this lays them out statically and then moves them the specified number of pixels. You want to use absolute positioning.

fixed vertical positioning of css within an iframe

I am trying to get my bottom header to stick to the bottom of the screen inside of my iframe application and have it always appear in view for the user even when the page is scrolling. I have no control over the outer iframe as it is on a different domain. The header itself must be inside of the iframe as I have no control outside the iframe. The iframe always expands to the height of its contents so that it has no scrollbars, but the bar still has to be visible in the viewport at all times.
Another thing to note: The iframe height should be the same height as its contents so their is no need for scroll bars
Chrome has a bug that doesn't fix elements with position:fixed if:
a) you use CSS3 transform in any element, and/or
b) you have a child element positioned outside the box of it's parent element
Oddly enough, the bug was reported back in 2009 and it's still open: https://code.google.com/p/chromium/issues/detail?id=20574
You might want to play around with position: fixed;
#element {
position: fixed;
z-index: 1000;
bottom: 0;
}
EDIT:
I'm sorry, I think I miss understood your post. If I'm reading it correctly you want to create a header bar similar to blogger but to keep it always in view of the user when he/she scrolls.
What you can do is create a container div, and then you can nest both your header and iframe inside that container. You can then play around with the positioning, although I'm not sure if the exact behavior that you're looking for is possible without some javascript.
EDIT 2:
After playing around a bit, I got something that I think might help (if I understand your problem correctly).
http://digitaldreamer.net/media/examples/iframe-site.html
http://digitaldreamer.net/media/examples/iframe.html
I had to look for a long time for a possible solution, and I think I have found one that is using the Intersection Observer API to detect the scrolled position of the iframe within the parent document without needing to access the parent document DOM.
I'm creating a bunch of hidden 100px high elements in the iframe. These are positioned absolutely underneath each other so that together they fill the height of the whole iframe document. An intersection observer then observes the intersection between the (top-level document) viewport and each of the hidden elements and calculates the scroll position of the iframe based on the values it returns. A ResizeObserver creates additional hidden elements if the height of the body increases.
This approach assumes that your iframe is always minimum 100px high. If you expect a smaller height, you need to adjust the hidden container height. The reason is that once a hidden container is 100% visible, the intersection observer does not emit the callback while the parent document is being scrolled (since the intersection ratio stays at 1). This is also the reason why I need a lot of small containers rather than observing the intersection with the iframe body itself.
const CONTAINER_HEIGHT = 100;
const threshold = [...Array(CONTAINER_HEIGHT + 1).keys()].map((i) => i / CONTAINER_HEIGHT);
/**
* Registers an intersection handler that detects the scrolled position of the current
* iframe within the browser viewport and calls a handler when it is first invoked and
* whenever the scrolled position changes. This allows to position elements within the
* iframe in a way that their position stays sticky in relation to the browser window.
* #param handler Is invoked when the function is first called and whenever the scroll
* position changes (for example due to the user scrolling the parent document). The
* "top" parameter is the number of pixels from the top of the browser viewport to the
* top of the iframe (if the top of the iframe is above the top of the browser viewport)
* or 0 (if the top of the iframe is below the top of the browser viewport). Positioning
* an element absolutely at this top position inside the iframe will simulate a sticky
* positioning at the top edge of the browser viewport.
* #returns Returns a callback that unregisters the handler.
*/
function registerScrollPositionHandler(handler: (top: number) => void): () => void {
const elementContainer = document.createElement('div');
Object.assign(elementContainer.style, {
position: 'absolute',
top: '0',
bottom: '0',
width: '1px',
pointerEvents: 'none',
overflow: 'hidden'
});
document.body.appendChild(elementContainer);
const elements: HTMLDivElement[] = [];
let intersectionObserver: IntersectionObserver | undefined = undefined;
const resizeObserver = new ResizeObserver(() => {
intersectionObserver = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (entry.intersectionRatio > 0 && (entry.intersectionRect.top > entry.boundingClientRect.top || entry.target === elements[0])) {
handler(entry.intersectionRect.top);
}
}
}, { threshold });
const count = Math.ceil(document.documentElement.offsetHeight / CONTAINER_HEIGHT);
for (let i = 0; i < count; i++) {
if (!elements[i]) {
elements[i] = document.createElement('div');
Object.assign(elements[i].style, {
position: 'absolute',
top: `${i * CONTAINER_HEIGHT}px`,
height: `${CONTAINER_HEIGHT}px`,
width: '100%'
});
elementContainer.appendChild(elements[i]);
intersectionObserver.observe(elements[i]);
}
}
});
resizeObserver.observe(document.documentElement);
return () => {
resizeObserver.disconnect();
intersectionObserver?.disconnect();
elementContainer.remove();
};
}
This example code should create a toolbar that is sticky at the top of the browser viewport:
<div style="position: absolute; top: 0; left: 0; bottom: 0; right: 0; overflow: hidden; pointer-events: none; z-index: 90">
<div id="toolbar" style="position: absolute; top: 0; left: 0; right: 0; pointer-events: auto; transition: top 0.3s">
Line 1<br/>Line 2<br/>Line 3<br/>Line 4<br/>Line 5<br/>Line 6<br/>Line 7<br/>Line 8<br/>Line 9<br/>Line 10
</div>
</div>
<script>
registerScrollPositionHandler((top) => {
document.querySelector('#toolbar').style.top = `${top}px`;
});
</script>
Note that other than what you asked for, this will position the toolbar at the top of the viewport rather than at the bottom. Positioning at the bottom should also be possible, but is slightly more complex. If anyone requires a solution for this, please let me know in the comments and I will invest the time to adjust my answer.

Resources