2017-09-27 135 views
0

我想使HTML Canvas元素的寬度=瀏覽器窗口寬度,height =瀏覽器窗口高度。以下是我使用的代碼。使HTML Canvas適合屏幕

HTML:

<body> 
     <canvas id="gameCanvas"></canvas> 
    <body /> 

JS:

function Main() { 
    this.canvas; 
    this.context; 
    this.canvasWidth; 
    this.canvasheight; 

    this.screenWidth; 
    this.screenHeight; 

    this.boxWidth; 
    this.boxHeight; 

    //This function is used to gather all required startup data 
    this.initalize = function (canvas) { 
     this.canvas = canvas; 
     this.context = this.canvas[0].getContext('2d'); 

    } 

    //This function is used to size the canvas to the screen size 
    this.sizeCanvas = function() { 
     this.canvas.css("width", this.screenWidth + "px"); 
     this.canvas.css("height", this.screenHeight + "px"); 
     this.canvas[0].width = this.screenWidth; 
     this.canvas[0].height = this.screenHeight; 


    } 

    //This function is used to draw a stickman 
    this.drawStickMan = function (x, y) { 
     var headRadius = 0; 
     if (this.boxWidth < this.boxHeight) { 
      headRadius = this.boxWidth; 

     } else { 
      headRadius = this.boxHeight; 

     } 

     this.context.beginPath(); 
     this.context.arc(x + this.boxWidth, y + this.boxHeight, headRadius, 0, 2 * Math.PI); 
     this.context.stroke(); 
     console.log("run" + this.boxHeight); 

    } 

    //This function is run on page load, and when the screen resizes 
    this.resize = function() { 
     this.screenWidth = screen.width; 
     this.screenHeight = screen.height; 
     this.sizeCanvas(); 

     this.canvasWidth = this.canvas[0].width; 
     this.canvasheight = this.canvas[0].height; 

     this.boxWidth = this.canvasWidth/16; 
     this.boxHeight = this.canvasheight/32; 
     this.drawStickMan(100, 100); 

    } 

} 

JS運行上面的類:無論

//This function is used to run the game 
$(document).ready(function() { 
    var main = new Main(); 
    main.initalize($("#gameCanvas")); 
    main.resize(); 

    //run whenever screen size changes 
    $(window).resize(function() { 
     main.resize(); 
    }); 

}); 

我似乎什麼,我無法得到畫布,以適應整個屏幕。我不確定畫布不適合的原因。我相信問題出在sizeCanvas函數中。

+0

'position:absolute;頂部:0;左:0;寬度:100%;身高:100%;' – Martijn

+2

[試試這個答案,或許可以解決你的問題](https://stackoverflow.com/a/3078427/6002328) –

+0

@NagyIstván這是一個完美的解決方案。 – holycatcrusher

回答

1

試試這個爲你的CSS:

body { 
    margin: 0; 
} 

#gameCanvas { 
    width: 100vw; 
    height: 100vh; 
} 
1

試試這個:

html, body { 
    height: 100%; 
} 

#gameCanvas { 
    width: 100%; 
    height: 100%; 
} 

的100%必須從html元素篩選下來,否則它不會填滿屏幕的高度。