我正在創建一個基于十六進制的地圖生成器,作為其中的一部分,我正在嘗試 - 在客戶端 - 繪制“河流”,穿過服務器端計算的六角形中心的線條有河流。
這是相關的變數(它可以從服務器端獲取 django 插入的值我已經測驗過它一切正常)
// The optional populators
const rivers = {{ rivers |safe}};
const cities = {{ cities |safe}};
const roads = {{roads |safe}};
// Constants for our angles and scales, starting with scale 5
const a = Math.PI/3;
var r = 5;
這是繪制河流的功能
// Function that draws Rivers
function DrawRivers(){
// For each river in the rivers
for (var river of rivers) {
// Set up point tracking
let x_coord = r river[0][0] * (r (r * Math.cos(a)));
let y_coord = r river[0][1] * (r (r*Math.sin(a)));
if (river[0][0] % 2 == 1) {
y_off = y_coord;
} else { // If it's an even number of tiles in the row it'll be the lower part
y_off = y_coord r * Math.sin(a);
}
ctx.beginPath();
ctx.lineWidth = r;
ctx.strokeStyle = "#000000";
ctx.moveTo(x_coord, Math.round(y_off))
// For each point in the river
for (var river_hex of river){
let x_coord = r river[0][0] * (r (r * Math.cos(a)));
let y_coord = r river[0][1] * (r (r*Math.sin(a)));
if (river[0][0] % 2 == 1) {
y_off = y_coord;
} else { // If it's an even number of tiles in the row it'll be the lower part
y_off = y_coord r * Math.sin(a);
}
ctx.lineTo(x_coord, Math.round(y_off))
}
ctx.closePath();
ctx.stroke();
}
}
但是,當我運行此代碼時,線條不會繪制。我已經逐步完成了代碼,一切似乎都有效;代碼沒有任何點沒有所需的變數,只是在呼叫 ctx.stroke() 命令時它實際上并沒有畫線。
其他人可以看到我哪里出錯了嗎?因為我真的不能...
uj5u.com熱心網友回復:
在您的內部回圈“對于河流中的每個點”中,您只使用river[0]
,而不是river_hex
(可能是復制粘貼錯誤),因此您最終繪制了一個點。
您可以通過將十六進制到螢屏坐標計算移動到單獨的函式并使用老式 for 回圈來簡化代碼(并減少復制粘貼錯誤;-)),這樣您就不需要處理首先moveTo
分開。
const rivers = [
[
[0, 0],
[1, 0],
[1, 1],
[1, 2],
[1, 3],
[1, 4],
[2, 4],
[3, 5],
[4, 5],
],
];
const a = Math.PI / 3;
var r = 15;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
function convertCoordinate(hex) {
const [hexX, hexY] = hex;
const x_coord = r hexX * (r (r * Math.cos(a)));
let y_coord = r hexY * (r (r * Math.sin(a)));
if (hexX % 2 !== 1) {
// If it's an even number of tiles in the row it'll be the lower part
y_coord = r * Math.sin(a);
}
return [x_coord, y_coord];
}
// Function that draws Rivers
function DrawRivers() {
// For each river in the rivers
for (var river of rivers) {
ctx.lineWidth = r;
ctx.strokeStyle = '#000000';
ctx.beginPath();
// For each point in the river
for (let i = 0; i < river.length; i ) {
const [x, y] = convertCoordinate(river[i]);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
// Not quite sure if a river should be closed...
// ctx.closePath();
ctx.stroke();
}
}
DrawRivers();
canvas {
border: 1px solid orange;
}
<canvas id="canvas" width="500" height="500"></canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/508382.html
標籤:javascript html 帆布
上一篇:將第一個元素設定為在加載時顯示,然后在單擊另一個React時隱藏
下一篇:圓形剪輯路徑