在使用canvas绘制与svg不同,svg基于矢量图直接绘制dom元素,放大缩小不会不会失真,而canvas基于位图依赖分辨率,放大图片边缘会出现模糊。因此需要作一些处理让其高清展示。
canvas高清绘制
代码如下:
const canvas = document.getElementById('canves')
const ctx = canvas.getContext('2d')
const getPixelRation = (context) =>{
return window.devicePixelRatio || 1
}
const ratio = getPixelRation()
const oldWidth = canvas.width
const oldHeight = canvas.height
console.log(ratio)
canvas.width = oldWidth * ratio
canvas.height = oldHeight * ratio
canvas.style.width = oldWidth + 'px'
canvas.style.height = oldHeight + 'px'
ctx.scale(ratio, ratio)
核心逻辑:
-
window.devicePixelRatio用来获取设备的物理像素分辨率与CSS像素分辨率之比
-
canvas.width设置为画布初始宽度 * 设备的物理像素分辨率与CSS像素分辨率之比
-
canvas.style.width设置为画布初始宽度
canvas.width 与 canvas.style.width 有什么区别呢?
-
canvas.width:决定canvas中有多少个像素
-
canvas.style.width:是canvas展示的样式大小
-
因此将canvas中的像素与设备分辨率保持一致,这样画布中的像素点增加,图像清晰度也就提高了
-
但是图片会大小会改变,因此要将图片放大相同的倍数