根据屏幕分辨率自动调整Html5画布大小

时间:2014-06-11 18:37:13

标签: javascript css html5 canvas

我创建了一个HTML5画布游戏,其中包括从两个画布中拖动和选择对象(单词)。屏幕还有两个按钮。但不幸的是,我的程序在选择单词方面是硬编码的,因为我已经进入了在画布上绘制单词的坐标。我的屏幕分辨率是1366 x 768。现在,无论何时更改分辨率,按钮都会移动到其他位置,鼠标从不选择拖动的单词,而是选择其上方的其他单词。我现在遇到大麻烦,请帮忙!

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

1 个答案:

答案 0 :(得分:0)

这是可能的,我已经在过去使用了一个基于屏幕大小动态调整大小的画布。

如果我没记错的话,我做了类似的事。

我将画布放在div中,并给div一个动态宽度,类似style =“width:30%”

我将画布放在这个div中并绑定了css,给画布一个样式=“宽度: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
}

然后,您需要重新绘制画布,因为调整大小将清除所有内容的画布

相关问题