简体   繁体   中英

HTML: How To Resize A Canvas Tag To the Size Of The Window

I have done much research, but I have come up empty handed on what would apear to be the most trivial of tasks:

If I have a canvas element that takes up the whole screen and is the only visible HTML, then how do I resize it to be the size of the window with it still being editable???

If you think this is simple then you try to do it. So, what is an example of how to do this? Do I have a broken browser and it's as simple as 100% size, or is it much much more complicated?

Also, if there is a script in your answer then please keep it to just plain javascript without jquery because i'm certain that if it can also be done in jquery then it can be done in good old plain javascript.

You need to remove the default 5px margin from the body like so.

<body style="margin:0px;">
    <canvas width="100%" height="100%">
Your browser doesn't support the HTML5 canvas
    </canvas>
</body>

try using css:

<canvas style="width: 100%; height: 100%;"></canvas>

also, be sure to make all of the parent elements 100% width and height:

<style>
html, body {
    height: 100%;
    width: 100%;
}
</style>

be sure to place the style tag between your <head> and </head> , you can also leave the canvas element itself alone and just add this to your head instead of the above code:

<style>
html, body {
    height: 100%;
    width: 100%;
}

canvas {
    height: 100%;
    width: 100%; 
}
</style>

Edit

From your example: ctx.fillRect(0, 0, canvas.height, canvas.width);

Has to be: ctx.fillRect(x, y, width, height);

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillRect

https://jsfiddle.net/zymobh3x/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM