[英]d3 Javascript - Draw polygon
我有一個SVG畫布,我希望它能夠單擊點並繪制多邊形。 我有以下代碼可以做到這一點:
var clicks = [];
function polyClick(){
var x = event.clientX;
var y = event.clientY;
var point = document.getElementById("num").value;
clicks.push.apply(clicks, [x,y]);
drawPoly(clicks)
function drawPoly(params){
d3.select(".p").remove();
mySVG.append("svg:polygon")
.style("fill", "red")
.style("stroke-width", "1")
.classed("p", true)
.attr("points", params + " "); //This LINE
}
}
標有“ This LINE”的行為我提供了正確的x和y坐標,但格式為“ 21,50,60,70,90,100”。 我需要的是將數組中的坐標添加為集合,例如“ 21,50 60,70 90,100”。 關於如何刪除每個坐標之間的逗號的任何想法嗎?
獎金:有人能確切告訴我這行是什么嗎?
drawPoly(clicks)
function drawPoly(params)
我發現建議將數組值用作函數的參數,但我不完全了解它是如何工作的。 在函數聲明之前,我正在使用“ drawPoly”。
感謝您提供的所有幫助!
函數定義在編譯期間進行處理,而表達式(如函數調用)在執行期間進行處理。 這就是為什么在JavaScript中函數定義和函數調用順序無關緊要的原因。
代碼說明:
function drawPoly(params){
d3.select(".p").remove(); //'p' is the class name of polygon. This line deletes the polygon if exists.
mySVG.append("svg:polygon") //Appends a new polygon with the calculated position attributes.
.style("fill", "red")
.style("stroke-width", "1")
.classed("p", true) //Sets classname as p
.attr("points", params);
}
該代碼似乎適用於當前的坐標格式。 以下是工作代碼段。
通過單擊3個以上的點作為多邊形的坐標來進行嘗試。
var mySVG = d3.select("#container").append("svg").attr({ width: 500, height: 200 }); mySVG.on('click', polyClick); var clicks = []; function polyClick() { var x = event.clientX; var y = event.clientY; clicks.push.apply(clicks, [x, y]); drawPoly(clicks) function drawPoly(params) { d3.select(".p").remove(); mySVG.append("svg:polygon") .style("fill", "red") .style("stroke-width", "1") .classed("p", true) .attr("points", params + " "); } }
svg { background-color: black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> <div id="container"> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.