画布尺寸和宽高比的问题

huangapple go评论76阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年7月23日 14:12:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76746847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定