2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

アルファベットを二進数にしてSVGを作る遊び

2
Posted at

2023-08-15_20_23-asciiGlyphs.png

概要

各アルファベットをバイナリーにして、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に入れる

※8つの[0か1]を4×2の行列にして並べています
Screenshot 2023-08-17 at 15.31.49.png

参考コード

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.

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?