'How to plot x,y coordinates of item on a image in html
I need to place/plot a pin(Small image to point the parts of person) on a image(For example: A image of person).
I am getting x,y,height,width values from server for a specific pin and i am creating one div element for each pin and assigning x,y,height,width values.
In Javascript, i am calculating view scale value in below mentioned way and multiply view scale with x,y,width,height and assign it into pin div element.
const screenwidth = screen.width;
const screenheight = screen.height;
viewscale = Math.min(screenwidth / mainImagewidth, screenheight / mainImageheight);
I am not able to place the pin on exact position of main image. Please help me if someone has idea of this logic.
Update:
Please find below the explanation through image.
Red Color rectangle is the screen. Green is the main image, let's say human image. Black color rectangle is a pin to describe a part in human image. I am getting x,y coordinates for this black colored rect pin from server.
Solution 1:[1]
Assuming I've understood this correctly, here's a possible demo solution:
First, define a config for your pin:
const pinConfig = {
width: 45,
height: 45,
offsetLeft: 40,
offsetTop: 75
};
Define a simple key/value map for getting the correct size type (width or height) when given an offset type (left or top):
const offsetTypeToSizeDimensionMap = {
left: 'width',
top: 'height'
};
Use a simple fn that calculates offset position relative to size. size / 2
because we need to compensate for the size of the pin, so positioning is based on the center of the element.
const calcRelativeOffsetPos = (offsetPos, size) => offsetPos - (size / 2);
Here's a style attribute string generating fn, accepts an object (our pinConfig
above, basically):
const generateStylesString = (stylesConfig) => {
return Object.keys(stylesConfig).map((styleProp) => {
if (styleProp.includes('offset')){
const stylePropName = styleProp.split('offset')[1].toLowerCase();
const relativeSizeTypeByOffsetType = offsetTypeToSizeDimensionMap[stylePropName];
const calculatedRelativeOffsetPos = calcRelativeOffsetPos(stylesConfig[styleProp], stylesConfig[relativeSizeTypeByOffsetType]);
return stylePropName + ': ' + calculatedRelativeOffsetPos + 'px; ';
}
return styleProp + ': ' + stylesConfig[styleProp] + 'px; ';
}).join('');
};
Finally, set style
attr to .child-parent
node:
document.querySelector('.child-image').setAttribute('style', generateStylesString(pinConfig));
Here's an example on Codepen: https://codepen.io/Inlesco/pen/xLwjLy?editors=1010
If you need the React way, it's easy - just concat the generated inline styles string to a JSX element when mapping out the elements and that's it.
Feel free to provide feedback, so we can improve this :)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |