概要
各アルファベットをバイナリーにして、2x8の行列に変換し暗号のようなシェイプを作るといった遊びです。
※上記の画像は以下のプロセスを応用して作成しています。
プロセス
1.文字列からアスキーコードを取得する
const x = "YES"
const ascii = x.split("").map((char) => char.charCodeAt(0))
//ascii = [89, 69, 83]
2. アスキーコードを8桁の二進数に変換する
const binary8 = ascii.map((n) => n.toString(2).padStart(8, "0"))
//binary8 = ["01011001", "01000101", "01010011"]
3.二進数のアスキーコードを以下画像のような行列に変換する
また、値が"1"の場合のみvector=[x, y]として変数vectorsに入れる
参考コード
const clms = 2
const rows = 4
const charStep = 10
const vectors = []
binary8.forEach((binary, i) => {
for(let row=0; row<rows; row++){
for(let clm=0; clm<clms; clm++){
const x = (clm * charStep / 2) + charStep * i
const y = charStep / 2 * row
const fill = binary[clm+row*clms] === "0" ? "null" : "pink"
svg.circle(charStep/4).move(x, y).fill(fill).stroke("pink")
////////////////////////////////
//値が"1"の場合のみvector=[x, y]として変数vectorsに入れる
if(binary[clm+row*clms] === "0"){
vectors.push([x, y])
}
////////////////////////////////
}
}
})
}
4.vectors内のベクターを、距離が近い順に並べ替える
//Heuristic approach
function sortVectorsByDistance(vectors){
const sortedVectors = [vectors.pop()]
while(vectors.length){
const from = sortedVectors[sortedVectors.length - 1]
let shortestDist = Infinity
let shortestIndex = 0
for(let i=0; i<vectors.length; i++){
const dist = calcVectorDistance(from, vectors[i])
if(dist < shortestDist){
shortestIndex = i
shortestDist = dist
}
}
sortedVectors.push(...vectors.splice(shortestIndex, 1))
}
return sortedVectors
}
5.並べ替えたvectorsを結んでシェイプを形成する
const sortedVectors = sortVectorsByDistance(vectors)
for(let i=0; i<sortedVectors.length; i++){
const nextIndex = (i+1) % sortedVectors.length
const from = sortedVectors[i]
const to = sortedVectors[nextIndex]
svg.line(...from, ...to).stroke("pink")
svg.circle(charStep / 10).center(...from).fill("pink")
}
結果 (Hello)
See the Pen Ascii, Binary and SVG by FrontendKanazawa (@jikkensya) on CodePen.

