英文:
Problem with canvas size and aspect ratio
问题
#canvas {
width: 100vw;
aspect-ratio: 16/9;
border: 5px solid red;
}
* {
margin: 5px;
margin-left: 3%;
}
.canvas {
width: 80vw;
aspect-ratio: 16/9;
border: 3px solid red;
}
英文:
Basically I created a canvas with html and from the css I gave it a ratio of 16/9 and I put a width of 100ww, I also put a border, but the problem is that my canvas is bigger than what I see on the screen.
#canvas{
width: 100vw;
aspect-ratio: 16/9;
border: 5px solid red;
}
I had to reduce the size and padding to compensate.
*{
margin: 5px;
margin-left: 3%
}
.canvas{
width: 80vw;
aspect-ratio: 16/9
border: 3px solid red;
}
This works but I was expecting a full screen if you can say so
Screenshots:
答案1
得分: 1
以下是您要翻译的内容:
const canvas=document.querySelector("canvas")
canvas.width=window.innerWidth-canvas.offsetLeft
canvas.height=window.innerHeight-canvas.offsetTop
它将设置画布的大小与您的窗口一样,并且会补偿 HTML 中的任何其他元素。
此外,添加一个事件侦听器以在调整窗口大小时重置画布大小,如下所示:
addEventListener("resize", function(){
canvas.width = innerWidth
canvas.height = innerHeight
//插入需要调用的函数!!
})
您需要调用需要重置的任何函数,比如生成对象的函数。
英文:
For a dynamic solution to canvas size try this in your JS:
const canvas=document.querySelector("canvas")
canvas.width=window.innerWidth-canvas.offsetLeft
canvas.height=window.innerHeight-canvas.offsetTop
It'll set the canvas to the size of your window as well as compensate for any other elements in your HTML.
Also, add an event listener to reset the canvas size when you resize the window like below:
addEventListener("resize",function(){
canvas.width=innerWidth
canvas.height=innerHeight
//INSERT FUNCTIONS TO CALL HERE!!
})
You'll need to call any functions that need resetting like ones that generate objects.
答案2
得分: 0
你需要从你的画布宽度中减去边框,像这样:
body {
margin: 0;
overflow: hidden;
}
#canvas{
width: calc(100vw - 10px);
aspect-ratio: 16/9;
border: 5px solid red;
}
参见:https://codepen.io/kikosoft/pen/ZEmjRxW
请注意,我将body的边距设置为零。如果你的边距不为零,你也需要减去它。
英文:
You have to subtract the border from the width of your canvas, like this:
body {
margin: 0;
overflow: hidden;
}
#canvas{
width: calc(100vw - 10px);
aspect-ratio: 16/9;
border: 5px solid red;
}
See: https://codepen.io/kikosoft/pen/ZEmjRxW
Note that I set the margin of the body to zero. If you have a non-zero margin you also have to subtract that.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论