如何在HTML画布中静态声明字母而不使用字符码

How to statically declare letters without using charcode in HTML Canvas

本文关键字:字符 声明 HTML 静态 布中      更新时间:2023-09-26

我有这个连接4个点的样本。

我想要的是字母[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;
}
<<p> 小提琴例子/strong>

注意,当画布被清除时,您可能需要重置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"];
 });
<<p> 小提琴例子/strong>