Canvas在移动端的缩放模糊问题

由于移动端的缩放问题Canvas的css宽与高会被缩放而Canvas画板本身不变,导致图形出现模糊
获得缩放倍率

1
2
3
4
5
6
7
8
9
var canvas = document.getElementById("canvas"), 
context= canvas.getContext("2d"); // 屏幕的设备像素比
var devicePixelRatio = window.devicePixelRatio || 1; // 浏览器在渲染canvas之前存储画布信息的像素比
var backingStoreRatio = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;// canvas的实际渲染倍率
var ratio = devicePixelRatio / backingStoreRatio;

设定height与width的值

1
2
canvas.width = canvas.width * ratio;
canvas.height = canvas.height * ratio;

https://sanwen8.cn/p/42bobOb.html