之所以模糊是在浏览器上生成的图片是1x的非矢量图,所以在retina屏幕上会出现模糊的问题(手机版的浏览器无此问题),以下是我整理的一段代码。
原理很简单,先算出 ratio 值(2,3等)然后根据 ratio 值对 canvas 的 width 和 height 调整,并且一定要对
canvas.getContext("2d")
获取的对象进行 scale(ratio, ratio) 相同的倍数,否则图片会被拉小。
function reviseRatio(canvas, width, height)
{
var context = canvas.getContext("2d");
var backingStoreRatio = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
var devicePixelRatio = window.devicePixelRatio || 1;
// canvas的实际渲染倍率
var ratio = devicePixelRatio / backingStoreRatio;
if (ratio > 1)
{
canvas.width = width * ratio;
canvas.height = height * ratio;
context.scale(ratio, ratio);
}
else
{
canvas.width = width;
canvas.height = height;
}
canvas.style.width = width;
canvas.style.height = height;
}
{
var context = canvas.getContext("2d");
var backingStoreRatio = context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
var devicePixelRatio = window.devicePixelRatio || 1;
// canvas的实际渲染倍率
var ratio = devicePixelRatio / backingStoreRatio;
if (ratio > 1)
{
canvas.width = width * ratio;
canvas.height = height * ratio;
context.scale(ratio, ratio);
}
else
{
canvas.width = width;
canvas.height = height;
}
canvas.style.width = width;
canvas.style.height = height;
}
直接调用方法
reviseRatio(canvas, 100, 80);
即可修正参数。
其中, canvas 是需要修正的canvas的dom对象,100是显示的宽度,80是高度(会渲染出一个 200 * 160 的canvas的图片)