我有一个连接4个点的sample
我想要的是有[S,T,A,R]的字母而不是连续的字母。用户单击“绘制”后,将使用用户想要的新坐标绘制[S、T、A、R]的其他点。
示例代码段:

for(var i=0;i<connectors.length;i++){
    var c=connectors[i];
    var s=anchors[c.start];
    var e=anchors[c.end];
    ctx.beginPath();
    ctx.moveTo(s.x,s.y);
    ctx.lineTo(e.x,e.y);
    ctx.stroke();
}

//draw lines
if (anchors.length>0 && anchors.length%4>0){
   ctx.strokeStyle='gray';
   var al = anchors.length-1;
   var almod4 = al%4;
   if (almod4==1 || almod4==2){
   //draw extra line
       ctx.beginPath();
       ctx.moveTo(anchors[al-1].x,anchors[al-1].y);
       ctx.lineTo(mouseX,mouseY);
       ctx.stroke();
   }
   ctx.beginPath();
   ctx.moveTo(anchors[al].x,anchors[al].y);
   ctx.lineTo(mouseX,mouseY);
   ctx.stroke();
}

最佳答案

要使它只有字母[S,T,A,R]可以有一个包含这些字母的字母数组,并让addAnchor()递增地使用该数组中的项(并再次执行mod Array.length以环绕到开头):

var letters = ["S", "T", "A", "R"];

function addAnchor(x,y){
    anchors.push({
        label:letters[nextLetter],
        x:x,
        y:y,
    });
    nextLetter = (nextLetter+1) % letters.length;
}

Fiddle Example
注意:清除画布后,您可能需要重置nextLetter的值。
对于只有一个集合,您拥有相同的数组,但是删除第一个元素,并且仅在数组不为空时添加节点:
function addAnchor(x,y){
    if(letters.length)
    {
        anchors.push({
            label:letters[0],
            x:x,
            y:y,
        });
        letters.shift();
    }
}

然后,您可以在单击“绘制”按钮时将字母添加回原来的位置(您可以像这样设置数组,也可以根据需要在数组中追加四个字母):
 $("#draw").click(function(){
    letters = ["S", "T", "A", "R"];
 });

Fiddle Example

09-26 23:45
查看更多