2017-04-11 45 views
2

我是新的jquery算法,我想问一下,当我点击鼠标时,我可以添加点或线。所以我知道我已经标记或不标注。我想用它来映射图像。 感谢当鼠标点击绘图时添加点

$(document).ready(function(e) { 
var coords = []; 
var temp; 
$('#map').click(function(e) { 
    var posX = $(this).offset().left, posY = $(this).offset().top; 
    var temp =((e.pageX - posX)+ ',' + (e.pageY - posY)); 
    coords.push(temp); 
    if(coords.length == 1){ 
     $('#coords').attr({ 
      "shape" : "rect", 
      /*"style" : "position:absolute; width: 2px; height: 2px; top: "posY"px; left: "posX"px; background: red;",*/ 
      "coords" : coords 
     }); 
    } 
    else { 
     $('#coords').attr({ 
      "shape" : "poly", 
      // "style" : "position:absolute; width: 100px; height: 100px; background: red;", 
      "coords" : coords 
     }); 
    }; 
    }); 

$('#ret').click(function(e){ 
    coords.pop(temp); 
    }); 

$('#del').click(function(e){ 
    coords.length=0; 
}); 

$('#show').click(function(e){ 
    console.log(coords); 
}); 
}); 

https://jsfiddle.net/senryu/tdt8we0k/

回答

4

可以实现它下面的方式。

$(document).ready(function() { 
 
     $("#maping").click(function(e) { 
 
     e.preventDefault(); 
 
     var x = e.pageX - this.offsetLeft; 
 
     var y = e.pageY - this.offsetTop; 
 
     var img = $('<img>'); 
 
     img.css('top', y); 
 
     img.css('left', x); 
 
     img.attr('width', 20); 
 
     img.attr('height', 20); 
 
     img.attr('src', 'http://www.clker.com/cliparts/q/p/u/5/b/3/green-leaf-icon-hi.png'); 
 
     img.appendTo('#maping'); 
 
    }) 
 
    });
#maping{ 
 
    background: pink; 
 
    width: 1000px; 
 
    height: 500px; 
 
    position: relative; 
 
} 
 
#maping img { 
 
    position: absolute; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div id="maping"> 
 

 
</div>

希望它能帮助。

+0

谢谢@Richard Parnaby-King我只是在编辑这个部分。 – Chirag