LoginSignup
0
1

More than 3 years have passed since last update.

JavaScript canvasで線を引く

Last updated at Posted at 2021-04-11
index.html
<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <canvas id="sample" width="500" height="2000"></canvas>
  <script src="main.js"></script>
</body>
</html>
main.js
const draw = () => {
  const xValue = 10;
  const yValue = 60;
  const xMove = 200;
  const textXaxis = 40;
  const textYaxis = 20;
  const canvas = document.getElementById('sample');
  const ctx = canvas.getContext('2d');
  const width = canvas.getAttribute('width');
  const height = canvas.getAttribute('height');

  ctx.clearRect(0, 0, width, height);
  ctx.font = "20px arial";
  ctx.fillText('Shuffle Alphabet', textXaxis, textYaxis);

  const aTozArray = range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x));
  const array = Array.from({length: aTozArray.length}, (v, i) => i);
  const randomArray = shuffle(array);

  ctx.beginPath();
  for (let i = 0; i < aTozArray.length; i++) {
    ctx.fillText(aTozArray[i], xValue, yValue * (i + 1));
    ctx.fillText(aTozArray[i], xValue + xMove, yValue * (i + 1));
    ctx.moveTo(xValue, yValue * (i + 1));
    ctx.lineTo(xValue + xMove, yValue * (parseInt(randomArray[i], 10) + 1));
  }
  ctx.stroke();
}

const shuffle = (array) => {
  for(let i = array.length - 1; i > 0; i--){
    let r = Math.floor(Math.random() * (i + 1));
    let tmp = array[i];
    array[i] = array[r];
    array[r] = tmp;
  }
  return array
}

const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));

draw()

shuffle_aphabet.gif

参考記事

0
1
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
0
1