-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
101 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,93 @@ | ||
--- | ||
layout: doc | ||
--- | ||
|
||
# 绘制图片不清晰问题 | ||
|
||
## 问题原因和解决 | ||
|
||
`canvas`其实本质上也是一张图片,不管在`canvas`中绘制图片还是绘制其他图形,都是一样的道理 | ||
|
||
首先要明确,`图片/canvas`有以下两种尺寸 | ||
|
||
- **原始尺寸** | ||
|
||
> 例如:这样设置 | ||
```javascript | ||
canvas.width = 600 | ||
canvas.height = 600 | ||
// 或者 | ||
img.naturalWidth | ||
img.naturalHeight | ||
``` | ||
|
||
- **样式尺寸** | ||
|
||
> 例如:在`css`中设置样式 | ||
```css | ||
#canvas { | ||
width: 600px; | ||
height: 600px; | ||
} | ||
``` | ||
|
||
|
||
图片的清晰与否还和`当前页面的缩放倍率`有关 | ||
|
||
> `缩放倍率`可以通过`window.devicePixelRatio`获取 | ||
:::tip | ||
这三者之间有个公式如下: | ||
> **原始尺寸 = 样式尺寸 * 缩放倍率** | ||
::: | ||
|
||
|
||
> 比如`canvas`要呈现在页面上的大小为`200*200`,称之为`显示尺寸` | ||
> 此时我们设置`canvas`元素的`样式尺寸 = 200(显示尺寸)`,但是其实浏览器渲染的时候,会乘以`缩放倍率` | ||
> 而如果我们没有设置`canvas`的原始尺寸或者设置的不符合上面的公式的时候,渲染的图片就不清晰 | ||
> 所以也要设置canvas的原始尺寸为`显示尺寸 * 缩放倍率` | ||
> 然后将canvas进行缩放,因为如果不缩放,画出来的图形就会很小,缩放的倍数就是缩放倍率的值 | ||
|
||
> 解决方法如下: | ||
:::tip | ||
1. 设置`canvas`的`样式尺寸 = 显示尺寸` | ||
```css | ||
#canvas { | ||
width: 200px; | ||
height: 200px; | ||
} | ||
``` | ||
2. 设置`canvas`的`原始尺寸 = 显示尺寸 * 像素比` | ||
```javascript | ||
const dpr = window.devicePixelRatio || 1 | ||
canvas.width = 200 * dpr | ||
canvas.height = 200 * dpr | ||
``` | ||
3. 经历`步骤2`后,画布大小变大了,那么画布也要进行对应的缩放,不然绘制出来的图形会很小 | ||
```javascript | ||
const ctx = canvas.getContext("2d") | ||
ctx.scale(dpr, dpr) | ||
``` | ||
::: | ||
|
||
> 完整代码如下:假设页面上要显示的尺寸为`200*200` | ||
```javascript | ||
const displaySize = 200 | ||
const canvas = document.querySelector("#canvas-optimize") | ||
const dpr = window.devicePixelRatio || 1 | ||
canvas.width = displaySize * dpr | ||
canvas.height = displaySize * dpr | ||
// 或者在css中直接设置样式也可以 | ||
canvas.style.cssText += `width: ${displaySize}px;height: ${displaySize}px` | ||
const ctx = canvas.getContext('2d') | ||
ctx.scale(dpr, dpr) | ||
``` | ||
|
||
## 查看效果 | ||
- [效果预览](https://mx52jing.github.io/Notes/canvas-related/slove-blurry-images/index.html) |