[英]Drawing arrows on a chess board in Javascript
我正在嘗試制作自己的國際象棋分析板,以便在教國際象棋時使用。 我目前擁有電路板,可以拖放的部件,以及清理電路板和設置不同電路板位置的方法。 我也可以點擊方塊來突出顯示它們。
我希望能夠從一個方格到另一個方格繪制箭頭以顯示攻擊和影響線,但不知道如何實現這一點。 我的電路板由<div>
標簽組成。 下面是一個簡短的例子(為了簡潔起見,偽代碼和實際代碼)。
//幾個CSS樣式來定義正方形的寬度,高度和顏色CSS樣式類“黑色正方形”CSS樣式類“淺色正方形”
//我的電路板由<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>
我可以將棋子放在棋盤上,移動它們,拿走其他棋子,清理棋盤,設置獨特的位置,並突出顯示各個方塊,但也希望能夠讓用戶點擊,拖動和繪制箭頭住在板上,同時仍然可以操縱板上的碎片。
我看着使用標簽,但根據我的閱讀和研究,似乎<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();
}
此代碼將根據鼠標按下和鼠標按下事件的方塊坐標獲取其開始和結束坐標。 然后,它將使用這些坐標來確定如何使用正確的旋轉繪制箭頭。
如果你問如何處理這個(有趣的)問題,我會這樣做。
divs
與一個容器div內的背景圖像(正文和箭頭的點)。 DOM
。 div
的大小) DIV
的坐標,以及第二個單擊的DIV
。 當你有這些坐標時,計算(使用畢達哥拉斯)你需要的箭頭的長度,以及你需要的旋轉聲音(這是一個棘手的部分,但我之前已經完成了所以如果你知道一些基本的話它當然可以完成數學)。 你實際上是在板上創建三角形。 這絕對不容易,但如果你喜歡數學,並考慮國際象棋,我想你會這很有趣。
順便說一句,這個問題當然可以用普通的JS來解決,但是使用jQuery可以減少工作量。 您還可以通過下載庫來離線使用jQuery。
要激活和禁用pointerEvents,我使用了此代碼。
//檢查是否按下了shift鍵
function disableImage(ev){
if(ev.shiftKey == 1){
var canvas = document.getElementById("arrowCanvas");
canvas.style.pointerEvents = "all";
}
}
function enableImage(){
var canvas = document.getElementById("arrowCanvas");
canvas.style.pointerEvents = "none";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.