Ich möchte es so machen, dass das HTML-Canvas-Element eine Breite = zum Browserfenster Breite und Höhe = das Browserfenster Höhe hat. Unten ist der Code, den ich verwende.Machen Sie HTML Canvas fit Bildschirm
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, die die obige Klasse läuft:
//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();
});
});
Egal, was ich tun kann ich nicht scheinen, um die Leinwand zu bekommen zu passen der gesamte Bildschirm. Ich bin mir nicht sicher, warum die Leinwand nicht passt. Ich glaube, dass das Problem in der sizeCanvas
Funktion ist.
'Position: absolut; oben: 0; links: 0; Breite: 100%; Höhe: 100%; ' – Martijn
[versuchen Sie diese Antwort, vielleicht Ihr Problem zu lösen] (https://Stackoverflow.com/a/3078427/6002328) –
@ Nagy István, das ist eine perfekte Lösung. – holycatcrusher