我的网址类似于 http://weburl/mine/dot.html?gid=4&x=266y=647&x=191y=355&x=100y=893
来自上述 URL。我需要通过获取 x
和 y
值在屏幕上绘制点。
根据上面的示例,有 3 个这样的值。
x=266 y=647
x=191 y=355
x=100 y=893
这个问题有两个部分:
1.) 如何分解 URL 中的值并将其放入数组中以构造图像? (因为上面的 URL 中有多个 x
值)
2.) 如何在图像上绘制点? fiddle added.
注意:以下是点的 CSS
。
position: 'absolute',
top: ev.pageY + 'px',
left: ev.pageX + 'px',
width: '10px',
height: '10px',
background: '#000000'
最佳答案
1)
// for str use window.location.search.replace("?", "");
var str = 'gid=4&x=266y=647&x=191y=355&x=100y=893';
var data = str.match(/(x|y)=(\d+)/g), pointsX = [], pointsY = [];
for(var i = 0; i < data.length; i++)
{
var tmp = data[i].split('=');
if (tmp[0] == 'x')
pointsX.push(tmp[1]);
else
pointsY.push(tmp[1]);
}
2) 在图像上方放置一个带有背景或边框的div或使用html5 + canvas http://jsfiddle.net/dh0swt43/
var str = 'gid=4&x=20y=30&x=40y=50&x=100y=100';
var data = str.match(/(x|y)=(\d+)/g), pointsX = [], pointsY = [];
for(var i = 0; i < data.length; i++)
{
var tmp = data[i].split('=');
if (tmp[0] == 'x')
pointsX.push(tmp[1]);
else
pointsY.push(tmp[1]);
}
for(var i = 0; i < pointsX.length; i++)
{
var div = document.createElement('div');
div.className = 'dot';
div.style.left = pointsX[i] + 'px';
div.style.top = pointsY[i] + 'px';
document.getElementById('wrapper').appendChild(div);
}
.dot {
height: 2px;
width: 2px;
position: absolute;
border: 2px solid red;
z-index: 10;
}
<div style='position:relative' id='wrapper'>
<img src='http://bestclipartblog.com/clipart-pics/earth-clip-art-3.jpg'>
</div>
关于javascript - 向图像添加点 - 初学者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26133534/