簡體   English   中英

根據屏幕分辨率自動調整HTML5畫布的大小

[英]Automatically resize Html5 canvas with respect to the screen resolution

我創建了一個HTML5畫布游戲,其中涉及從兩個畫布中拖動和選擇對象(單詞)。 屏幕上還有兩個按鈕。 但是不幸的是,由於我輸入了在畫布上繪制單詞的坐標,因此我的程序在選擇單詞方面進行了硬編碼。 我的屏幕分辨率是1366 x768。 現在,無論何時更改分辨率,按鈕都會移動到其他位置,而鼠標永遠不會選擇拖動的單詞,而是選擇上方的其他單詞。 我現在很麻煩,請幫忙!

<html>
<head>
    <title>Word Search</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type = text/css href="style.css">
    <script type="text/javascript" src="keywords.js"></script>
    <script type="text/javascript" src="game.js"></script>
    <script type="text/javascript" src="highlight.js"></script>
    <script type="text/javascript" src="grid.js"></script>
    <script src="http://code.createjs.com/easeljs-0.7.0.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>

</head>
<body>
    <h1 id="heading">Find Keywords</h1>
    <h3 id="results">Drag through the lettered Squares..!</h3>
    <canvas id ='canvas1' height = 450 width="450" style= "border :1px solid black"> </canvas>
    <canvas id ='canvas2' height = 450 width="250" style= "border :1px solid black"></canvas>
    <input type='button' value="HIGHLIGHT ALL" id="button1" onclick="highlight();" />
    <input type='button' value="NEXT" id="button2" onclick="next();"/>


        <script> 
        var words =[];
        window.onload = function(){ 
                            begin();
                                  };

        function begin()
        {
            wordSearchPuzzle();
        }

        function wordSearchPuzzle()
        { 
        words.length=0;              
        words = getwords(8);
        var puz =wordfind(words);
        game(words,puz);   
        }

        function next()
         {

        var canvas = document.getElementById("canvas1");
        var ctx1 = canvas.getContext("2d");
        var canvas2 = document.getElementById("canvas2");
        var ctx2 = canvas2.getContext("2d");
        ctx1.clearRect(0, 0, canvas.width, canvas.height);
        ctx2.clearRect(0, 0, canvas2.width, canvas2.height);
        wordSearchPuzzle();

        }


        </script>

</body>
</html>

這是可能的,我已經完成了他的工作,使用了可以根據屏幕大小動態調整大小的畫布。

如果我沒記錯的話,我做了這樣的事情。

我將畫布放在div中,並給div設置了動態寬度,類似於style =“ width:30%”

我將畫布放置在該div內,然后將CSS綁在一起,以使畫布具有style =“ width:100%”

<div style="width:30%">
   <canvas id="can" style="width:100%"></canvas>
</div>

我綁定到窗口調整大小事件並讀取客戶端大小,以確定更改畫布的元素寬度和高度

window.resize = function(){
    var canvas = document.getElementById("can");
    canvas.width = canvas.clientWidth;
    canvas.height = //some value based on width
}

然后,您需要重新繪制畫布,因為調整大小會清除畫布中的所有內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM