JavaScript Canvasのサイズを変更するサンプル

環境
Google Chrome 111.0.5563.147
Windows 10 Home 64bit

構文
1.canvas要素の取得
<canvas class="canvas"></canvas>

2.Canvasのサイズはwidth、heightにて変更します
let canvas = document.querySelector('.canvas’);
canvas.width = 横幅;
canvas.height = 高さ;

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<canvas class="canvas"></canvas>
<script>
let canvas = document.querySelector('.canvas');
let context = canvas.getContext('2d');
let y = -50;
function move(callback) {
// 描画をクリアする
context.clearRect(0, 0, canvas.width, canvas.height);
// y(位置)の増加
if (y <= canvas.width) {
y = y + 1;
} else {
y = -50;
}
// 描画
context.beginPath();
context.fillStyle = 'red';
context.fillRect(y, 50, 50, 50);
// moveを呼び出す
window.requestAnimationFrame(move);
}
// callback関数を呼び出す
window.requestAnimationFrame(move);
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <canvas class="canvas"></canvas> <script> let canvas = document.querySelector('.canvas'); let context = canvas.getContext('2d'); let y = -50; function move(callback) { // 描画をクリアする context.clearRect(0, 0, canvas.width, canvas.height); // y(位置)の増加 if (y <= canvas.width) { y = y + 1; } else { y = -50; } // 描画 context.beginPath(); context.fillStyle = 'red'; context.fillRect(y, 50, 50, 50); // moveを呼び出す window.requestAnimationFrame(move); } // callback関数を呼び出す window.requestAnimationFrame(move); </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<canvas class="canvas"></canvas>

<script>
let canvas = document.querySelector('.canvas');
let context = canvas.getContext('2d');

let y = -50;
function move(callback) {
  // 描画をクリアする
  context.clearRect(0, 0, canvas.width, canvas.height);

  // y(位置)の増加
  if (y <= canvas.width) {
    y = y + 1;
  } else {
    y = -50;
  }

  // 描画
  context.beginPath();
  context.fillStyle = 'red';
  context.fillRect(y, 50, 50, 50);


  // moveを呼び出す
  window.requestAnimationFrame(move);
}

// callback関数を呼び出す
window.requestAnimationFrame(move);
</script>

</body>
</html>

結果
Canvasのサイズ(幅と高さ)を描画します。

JavaScript

Posted by arkgame