Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第 83 期(W3C标准-canvas):canvas 画布尺寸 #86

Open
wingmeng opened this issue Aug 11, 2019 · 0 comments
Open

第 83 期(W3C标准-canvas):canvas 画布尺寸 #86

wingmeng opened this issue Aug 11, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Aug 11, 2019

如何为 <canvas> 设置尺寸?首先是最常见的方式,通过 canvas 的 width、height 属性来设置:

<canvas width="333" height="222" id="canvas1"></canvas>

如果是对 canvas 了解不足的小伙伴,可能会说出以下方式:

<!-- 通过外联或页级 CSS 设置宽高 -->
<style>
#canvas1 {
  width: 333px;
  height: 222px;
}
</style>
<canvas id="canvas1"></canvas>
<!-- 通过行内 CSS 设置宽高 -->
<canvas id="canvas1" style="width: 333px; height: 222px"></canvas>

如果按照上述设置了画布尺寸,你会发现在绘图时发生了变形失真,例如代码中明明绘制了一个圆形,最终渲染出来却不是正圆。这是因为,canvas 是有默认尺寸的,缺省宽高为 300×150px,如果在 CSS 中为其定义宽高,实际上是把宽高为 300×150px 的画布进行了拉伸,因此会导致绘图变形。

所以我们在为 canvas 设置尺寸时,推荐的方式是通过 canvas 标签的 width、height 属性来设置画布宽高,也可以使用 JS 来设置画布宽高(如下)。

const canvas1 = document.getElementById('canvas1');

// 注意:尺寸不能带单位,否则会报错
canvas1.width = 333;
canvas1.height = 222;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant