Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

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

Copy link
Copy link
@wingmeng

Description

@wingmeng
Issue body actions

如何为 <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;

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.