Ste*_*ard 5 html javascript chess canvas
我正在尝试制作自己的国际象棋分析板,以便在教授国际象棋时使用。我目前有棋盘,可以拖放的棋子,以及清除棋盘和设置不同棋盘位置的方法。我还可以单击方块以突出显示它们。
我希望能够将箭头从一个方格绘制到另一个方格以显示攻击线和影响线,但不知道如何实现这一点。我的板子是由<div>标签组成的。下面是一个简短的例子(为简洁起见,伪代码和实际代码)。
// 几个 CSS 样式来定义正方形的宽度、高度和颜色 CSS 样式类 "dark square" CSS 样式类 "light square"
//我的板子是由<div>标签组成的
<div id="board">
<div id="a1" class="lightsquare"></div>
<div id="a2" class="darksquare"></div>
<div id="a3" class="lightsquare"></div>
//second rank
<div id="b1" class="darksquare"></div>
<div id="b2" class="lightsquare"></div>
<div id="b3" class="darksquare"></div>
//third rank
<div id="c1" class="lightsquare"></div>
<div id="c2" class="darksquare"></div>
<div id="c3" class="lightsquare"></div>
</div>
Run Code Online (Sandbox Code Playgroud)
我可以将棋子放在棋盘上,移动它们,拿走其他棋子,清除棋盘,设置独特的位置,并突出显示各个方块就好了,但也希望能够让用户点击、拖动和绘制箭头生活在棋盘上,同时仍然能够操纵棋盘上的棋子。
我曾考虑使用该标签,但根据我的阅读和研究,该<canvas>标签似乎并不是为满足我的需求而设计的。
有没有人对如何在 JavaScript 中做到这一点有任何想法?我还没有学会使用 JQuery,我宁愿避免使用 JQuery,因为我不想下载额外的文件或必须在互联网上使用这个程序。
经过一个月的摸索,我终于找到了解决方案。尽管我付出了很多努力使用 < div > 标签和图像来解决这个问题,但我永远无法让箭头在旋转时正确定位。因此,我回去尝试 <canvas> 标签,最终找到了一个有效的解决方案。
function drawArrow(fromx, fromy, tox, toy){
//variables to be used when creating the arrow
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var headlen = 10;
var angle = Math.atan2(toy-fromy,tox-fromx);
//starting path of the arrow from the start square to the end square and drawing the stroke
ctx.beginPath();
ctx.moveTo(fromx, fromy);
ctx.lineTo(tox, toy);
ctx.strokeStyle = "#cc0000";
ctx.lineWidth = 22;
ctx.stroke();
//starting a new path from the head of the arrow to one of the sides of the point
ctx.beginPath();
ctx.moveTo(tox, toy);
ctx.lineTo(tox-headlen*Math.cos(angle-Math.PI/7),toy-headlen*Math.sin(angle-Math.PI/7));
//path from the side point of the arrow, to the other side point
ctx.lineTo(tox-headlen*Math.cos(angle+Math.PI/7),toy-headlen*Math.sin(angle+Math.PI/7));
//path from the side point back to the tip of the arrow, and then again to the opposite side point
ctx.lineTo(tox, toy);
ctx.lineTo(tox-headlen*Math.cos(angle-Math.PI/7),toy-headlen*Math.sin(angle-Math.PI/7));
//draws the paths created above
ctx.strokeStyle = "#cc0000";
ctx.lineWidth = 22;
ctx.stroke();
ctx.fillStyle = "#cc0000";
ctx.fill();
}
Run Code Online (Sandbox Code Playgroud)
此代码将根据鼠标按下和鼠标松开事件时的方块坐标来获取其开始和结束坐标。然后,它将使用这些坐标来确定如何以正确的旋转来绘制箭头。