解决用H5 Canvas绘制的图片或文字在高清屏下模糊的问题
背景:项目地图页面上有海量点,每个点都有不同的指标数值,而且很多点根据分类还用不同的图片作为背景。因此考虑用H5 Canvas加载图标png并把数值画上去,然后把canvas导出图片url并应用到点标记上。
1、常规绘制:
代码:
var image = new Image(); image.src='../../assets/img/pollution/pollution-province-excellent.png'; image.onload =()=>{ var canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; var ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); ctx.fillStyle = '#fff'; ctx.font='14px Arial'; ctx.fillText('35', 25, 30); var image1 = new Image(); image1.src = canvas.toDataURL(); var containerNode = document.querySelector('#div1'); containerNode.append(canvas); };
数字显然很模糊。
2、根据设备像素比devicePixelRatio来绘制:
(参考MDN官网Canvas API说明:https://developer.mozilla.org/zh-CN/docs/Web/API/Window/devicePixelRatio)
代码:
var image = new Image(); image.src='../../assets/img/pollution/pollution-province-excellent.png'; image.onload =()=>{ var canvas = document.createElement('canvas'); const {width, height} = image; canvas.style.width = width+'px'; canvas.style.height = height+'px'; //var scale = window.devicePixelRatio;
var scale = 2; //我为什么用2,而不用devicePixelRatio数值?因为我的电脑Win10系统设置了自定义缩放比大于devicePixelRatio但小于2(200%) canvas.width = Math.floor(width*scale); canvas.height = Math.floor(height*scale); var ctx = canvas.getContext('2d'); ctx.scale(scale, scale);//scale>1表示放大,反之表示缩小。即绘制原先1px现在是绘制scale个pixel
//注意绘制内容在scale之后开始 ctx.drawImage(image, 0, 0); ctx.fillStyle = '#ffffff'; ctx.font='14px Arial'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; var x = canvas.width/2; var y = canvas.height/2; ctx.fillText('35', x/scale, y/scale);//为什么x/y还除以scale,因为画布实际放大了scale倍,所以x,y绘制的像素也放大了scale,所以再除以scale var image1 = new Image(); image1.src = canvas.toDataURL(); var containerNode = document.querySelector('#div2'); containerNode.append(canvas); };
2次绘制的效果对比: