我有这个sample连接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;
}
请注意,当 Canvas 被清除时,您可能希望重置 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"];
});
关于javascript - 如何在 HTML Canvas 中不使用 charcode 静态声明字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32492338/