creative-account
@creative-account

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

divとcanvasのサイズ

東方(Project)のような弾幕シューティングゲームを作っています。
javascriptでcanvasを生成するときにつまずきました。
解決方法を教えてください。

また、これよりもっといい方法を知ってるよって方は教えてください

以下経緯

ゲームのサイズを画面のサイズに応じて3種類に変えたいと思っています。
ただ、3つの場合それぞれにプログラムを書くのは大変なので、
if文で画面のサイズ応じて100%、75%、50%にしたいと思っています。
そうすると、canvasごと中身が縮むと聞いたので。

で、cssの%は親要素基準なので、親要素であるdivのサイズを1280x960にしようとしたら、
それが反映されません。

コード

Style.css
#container{
    width: 1280;
    height: 960;
};
script.js
//ページが読み込まれた際にisSmartPhone関数を実行
document.addEventListener("DOMContentLoaded", function () {
  //スマホ判定
  isSmartPhone();
});

//スマホかパソコンの判定
function isSmartPhone() {
  if (navigator.userAgent.match(/iPhone|Android.+Mobile|iPad/)) {
    //パソコンでお楽しみください。
    var paragraph = document.createElement("p");
    paragraph.innerHTML = "パソコンでお楽しみください";
    document.body.appendChild(paragraph);
  }else{
    drawCanvas();
  }
};

//画面サイズに応じてcanvas要素をbody直下に生成
function drawCanvas(){
  if (window.screen.availWidth >= 1280 && window.screen.availHeight >= 960){
    const container = document.getElementById('container');
    const canvas = document.createElement('canvas');
    canvas.style.width = '100%';
    canvas.style.height = '100%';
    canvas.style.backgroundColor = 'red';
    container.appendChild(canvas);
    alert("1280x960");
  }else if (window.screen.availWidth >= 960 && window.screen.availHeight >= 720){
    const container = document.getElementById('container');
    const canvas = document.createElement('canvas');
    canvas.style.width = '75%';
    canvas.style.height = '75%';
    canvas.style.backgroundColor = 'blue';
    container.appendChild(canvas);
    alert("960x720");
  }else if (window.screen.availWidth >= 640 && window.screen.availHeight >= 480){
    const container = document.getElementById('container');
    const canvas = document.createElement('canvas');
    canvas.style.width = '50%';
    canvas.style.height = '50%';
    canvas.style.backgroundColor = 'black';
    container.appendChild(canvas);
    alert("640x480");
  };
};

東方.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">
        <link rel="stylesheet" href="Style.css">
        <title>弾幕</title>
    </head>
    <body>
        <div id="container"></div>
        <script src="script.js"></script>
    </body>
</html>

例)

def greet
  puts Hello World
end

自分で試したこと

かっこ、コメントアウトの閉じ忘れ、
!importantをつける。

文が分かりにくい時は説明します。ごめんなさい

0

1Answer

末尾にpxを付けると解決しませんか?

#container{
    width: 1280px;
    height: 960px;
};

1Like

Comments

  1. ごめんなさい…きずきませんでした
    こんな初歩的なミスで…orz
    次からはよく気を付けます。
    ありがとうございました。

Your answer might help someone💌