移动端Retina屏boder 1px显示为2px或3px的解决方法
我们在开发移动端web项目时经常遇到设置border:1px,但是显示的边框却为2px或是3px粗细,这是因为设备像素比devicePixelRatio为2或3引起的。
何为“设备像素比devicePixelRatio”
所有非视网膜屏幕的iphone在垂直的时候,宽度为320物理像素。当你使用<meta name="viewport" content="width=device-width">的时候,会设置视窗布局宽度(不同于视觉区域宽度,不放大显示情况下,两者大小一致,见下图)为320px, 于是,页面很自然地覆盖在屏幕上。这样,非视网膜屏幕的iphone上,屏幕物理像素320像素,独立像素也是320像素,因此,window.devicePixelRatio等于1.
这样,在视网膜屏幕的iphone上,屏幕物理像素640像素,独立像素还是320像素,因此,window.devicePixelRatio等于2.
每个像素点实际上有4倍的普通像素点,如下示意(© smashingmagazine):
1个CSS像素点实际上有4个位图像素点,1个分成4个,显然不够分啊,只能颜色近似选取,于是,图片感觉就是模糊的(© smashingmagazine)!。这就是为什么使用两倍图。
在retina屏下面,如果你写了这样的meta <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
你将永远无法写出1px宽度的东西,除此之外,inline的SVG等元素,也会按照逻辑像素来渲染,整个页面的清晰度会打折;
百度糯米的实现:
1 @media only screen and (-webkit-min-device-pixel-ratio:2),only screen and (min-device-pixel-ratio:2) { 2 .normal-goods .good-content { 3 border: none; 4 background-image: -webkit-linear-gradient(90deg,#e0e0e0,#e0e0e0 50%,transparent 50%); 5 background-image: -moz-linear-gradient(90deg,#e0e0e0,#e0e0e0 50%,transparent 50%); 6 background-image: -o-linear-gradient(90deg,#e0e0e0,#e0e0e0 50%,transparent 50%); 7 background-image: linear-gradient(0,#e0e0e0,#e0e0e0 50%,transparent 50%); 8 background-size: 100% 1px; 9 background-repeat: no-repeat; 10 background-position: bottom 11 } 12 }
大众点评的实现:
1 .index-rec .home-tuan-list .cnt { 2 padding: 7px 10px 10px 0; 3 display: box; 4 display: -webkit-box; 5 display: -ms-flexbox; 6 height: 78px; 7 background-image: url(//www.dpfile.com/mod/app-m-style/1.7.2/css/img/repeat-x.png); 8 background-repeat: repeat-x; 9 background-position: 0 bottom; 10 background-size: auto 1px 11 }
微信WeUI的实现:
1 .weui_grid:before { 2 content: " "; 3 position: absolute; 4 right: 0; 5 top: 0; 6 width: 1px; 7 height: 100%; 8 border-right: 1px solid #D9D9D9; 9 color: #D9D9D9; 10 -webkit-transform-origin: 0 100%; 11 transform-origin: 0 100%; 12 -webkit-transform: scaleX(0.5); 13 transform: scaleX(0.5); 14 right: -1px; 15 }
1 .weui_grid:after { 2 content: " "; 3 position: absolute; 4 left: 0; 5 bottom: 0; 6 width: 100%; 7 height: 1px; 8 border-bottom: 1px solid #D9D9D9; 9 color: #D9D9D9; 10 -webkit-transform-origin: 0 100%; 11 transform-origin: 0 100%; 12 -webkit-transform: scaleY(0.5); 13 transform: scaleY(0.5); 14 }
阿里的实现:
js:
1 <script> 2 if (/iP(hone|od|ad)/.test(navigator.userAgent)) { // 就是放到html根节点上的 ios8现在普及率高了,可以省略 3 var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/), version = parseInt( 4 v[1], 10); 5 if (version >= 8) { 6 document.documentElement.classList.add('hairlines') 7 } 8 }; 9 </script>
css:
1 .r1bt { 2 border-top: 1px solid rgba(32,35,37,.15) 3 } 4 .r1bb { 5 border-bottom: 1px solid rgba(32,35,37,.15) 6 } 7 .r1bl { 8 border-left: 1px solid rgba(32,35,37,.15) 9 } 10 .r1br { 11 border-right: 1px solid rgba(32,35,37,.15) 12 } 13 .r1b { 14 border: 1px solid rgba(32,35,37,.15) 15 } 16 .hairlines .r1bt,.hairlines .r1bb,.hairlines .r1bl,.hairlines .r1br,.hairlines .r1b { 17 border-width: .5px!important 18 }
阿里的另一种实现:
1 /*Retian 1px border start */ 2 .retinabt,.retinabb,.retinabl,.retinabr,.retinab{position:relative;} 3 .retinabt:before,.retinabb:after{pointer-events:none;position:absolute;content:"";height:1px;background:rgba(32,35,37,.14);left:0;right:0;z-index:26;} 4 .retinabt:before{top:0;z-index:26;} 5 .retinabb:after{bottom:0;z-index:26;} 6 .retinabl:before,.retinabr:after{pointer-events:none;position:absolute;content:"";width:1px;background:rgba(32,35,37,.14);top:0;bottom:0} 7 .retinabl:before{left:0;z-index:26;} 8 .retinabr:after{right:0;z-index:26;} 9 .retinab:after{position:absolute;content:"";top:0;left:0;-webkit-box-sizing:border-box;box-sizing:border-box;width:100%;height:100%;border:1px solid rgba(32,35,37,.14);pointer-events:none;z-index:26;} 10 @media (-webkit-min-device-pixel-ratio:1.5),(min-device-pixel-ratio:1.5),(min-resolution:144dpi),(min-resolution:1.5dppx){ 11 .retinabt:before,.retinabb:after{-webkit-transform:scaleY(.5);transform:scaleY(.5) } 12 .retinabl:before,.retinabr:after{-webkit-transform:scaleX(.5);transform:scaleX(.5) } 13 .retinab:after{width:200%;height:200%;-webkit-transform:scale(.5);transform:scale(.5) } 14 .retinabt:before,.retinabl:before,.retinab:after{-webkit-transform-origin:0 0;transform-origin:0 0} 15 .retinabb:after,.retinabr:after{-webkit-transform-origin:100% 100%;transform-origin:100% 100%} 16 } 17 @media (-webkit-device-pixel-ratio:1.5){ 18 .retinabt:before,.retinabb:after{-webkit-transform:scaleY(.6666);transform:scaleY(.6666) } 19 .retinabl:before,.retinabr:after{-webkit-transform:scaleX(.6666);transform:scaleX(.6666)} 20 .retinab:after{width:150%;height:150%;-webkit-transform:scale(.6666);transform:scale(.6666) } 21 } 22 @media (-webkit-device-pixel-ratio:3){ 23 .retinabt:before,.retinabb:after{-webkit-transform:scaleY(.3333);transform:scaleY(.3333)} 24 .retinabl:before,.retinabr:after{-webkit-transform:scaleX(.3333);transform:scaleX(.3333)} 25 .retinab:after{width:300%;height:300%;-webkit-transform:scale(.3333);transform:scale(.3333)} 26 } 27 @media (-webkit-min-device-pixel-ratio:4),(min-device-pixel-ratio:4){ 28 .retinabt:before,.retinabb:after{-webkit-transform:scaleY(.25);transform:scaleY(.25)} 29 .retinabl:before,.retinabr:after{-webkit-transform:scaleX(.25);transform:scaleX(.25)} 30 .retinab:after{width:400%;height:400%;-webkit-transform:scale(.25);transform:scale(.25)} 31 } 32 /*Retina 1px border end */
美团的实现:
1 <script type="text/javascript"> 2 //根据屏幕大小及dpi调整缩放和大小 3 (function() { 4 var scale = 1.0; 5 var ratio = 1; 6 if (window.devicePixelRatio >= 2) { 7 scale *= 0.5; 8 ratio *= 2; 9 } 10 var text = '<meta name="viewport" content="initial-scale=' + scale + ', maximum-scale=' + scale +', minimum-scale=' + scale + ', width=device-width, user-scalable=no" />'; 11 document.write(text); 12 document.documentElement.style.fontSize = 50*ratio + "px"; 13 })(); 14 </script>
我们把美团的 拷贝过来使用,发现 安卓自带的浏览器(app内嵌h5不得不考虑)有的 不兼容 开始整体字体放大,应该是没有正确获取设备的实际宽度,(手头没有那么多安卓测试手机,主要是自带浏览器出现问题),不知到美团怎么处理的,我想到的用这个 target-densittydpi=device-dpi hack下;是可以的 或者加个 计时器 延迟 50毫秒 获取设备的正确实际宽度;
1 <meta name="viewport" content="target-densitydpi=device-dpi"> <!--安卓自带的 device-width 先不加 否则iphone 随进线条出现问题 --> 2 <script> 3 +function(win,doc,undefined) {//根据屏幕大小及dpi调整缩放和大小 4 var scale = 1.0,ratio = 1,dc=doc,viewporttexts=''; 5 if (win.devicePixelRatio && devicePixelRatio >= 1.5) { 6 ratio = devicePixelRatio; 7 scale = scale/(devicePixelRatio); 8 } 9 //var texts = '<meta name="viewport" content="initial-scale=' + scale + ', maximum-scale=' + scale +', minimum-scale=' + scale + ', width=device-width, user-scalable=no" />'; 10 // dc.write(texts); 11 viewporttexts = ' width=device-width, initial-scale=' + scale + ', maximum-scale=' + scale +', minimum-scale=' + scale + ',user-scalable=no'; 12 doc.querySelector('meta[name="viewport"]').setAttribute("content",viewporttexts); 13 14 console.log('111'); 15 dc.documentElement.style.fontSize =doc.getElementsByTagName("html")[0].style.fontSize=Math.ceil(50*ratio) + "px"; 16 }(window,document); 17 </script>
设计坞官网https://www.wode007.com/sites/73738.html
淘宝的实现:
1 ;(function(win, lib) { 2 var doc = win.document; 3 var docEl = doc.documentElement; 4 var metaEl = doc.querySelector('meta[name="viewport"]'); 5 var flexibleEl = doc.querySelector('meta[name="flexible"]'); 6 var dpr = 0; 7 var scale = 0; 8 var tid; 9 var flexible = lib.flexible || (lib.flexible = {}); 10 11 if (metaEl) { 12 console.warn('将根据已有的meta标签来设置缩放比例'); 13 var match = metaEl.getAttribute('content').match(/initial\-scale=([\d\.]+)/); 14 if (match) { 15 scale = parseFloat(match[1]); 16 dpr = parseInt(1 / scale); 17 } 18 } else if (flexibleEl) { 19 var content = flexibleEl.getAttribute('content'); 20 if (content) { 21 var initialDpr = content.match(/initial\-dpr=([\d\.]+)/); 22 var maximumDpr = content.match(/maximum\-dpr=([\d\.]+)/); 23 if (initialDpr) { 24 dpr = parseFloat(initialDpr[1]); 25 scale = parseFloat((1 / dpr).toFixed(2)); 26 } 27 if (maximumDpr) { 28 dpr = parseFloat(maximumDpr[1]); 29 scale = parseFloat((1 / dpr).toFixed(2)); 30 } 31 } 32 } 33 34 if (!dpr && !scale) { 35 var isAndroid = win.navigator.appVersion.match(/android/gi); 36 var isIPhone = win.navigator.appVersion.match(/iphone/gi); 37 var devicePixelRatio = win.devicePixelRatio; 38 if (isIPhone) { 39 // iOS下,对于2和3的屏,用2倍的方案,其余的用1倍方案 40 if (devicePixelRatio >= 3 && (!dpr || dpr >= 3)) { 41 dpr = 3; 42 } else if (devicePixelRatio >= 2 && (!dpr || dpr >= 2)){ 43 dpr = 2; 44 } else { 45 dpr = 1; 46 } 47 } else { 48 // 其他设备下,仍旧使用1倍的方案 49 dpr = 1; 50 } 51 scale = 1 / dpr; 52 } 53 54 docEl.setAttribute('data-dpr', dpr); 55 if (!metaEl) { 56 metaEl = doc.createElement('meta'); 57 metaEl.setAttribute('name', 'viewport'); 58 metaEl.setAttribute('content', 'initial-scale=' + scale + ', maximum-scale=' + scale + ', minimum-scale=' + scale + ', user-scalable=no'); 59 if (docEl.firstElementChild) { 60 docEl.firstElementChild.appendChild(metaEl); 61 } else { 62 var wrap = doc.createElement('div'); 63 wrap.appendChild(metaEl); 64 doc.write(wrap.innerHTML); 65 } 66 } 67 68 function refreshRem(){ 69 var width = docEl.getBoundingClientRect().width; 70 if (width / dpr > 540) { 71 width = 540 * dpr; 72 } 73 var rem = width / 10; 74 docEl.style.fontSize = rem + 'px'; 75 flexible.rem = win.rem = rem; 76 } 77 78 win.addEventListener('resize', function() { 79 clearTimeout(tid); 80 tid = setTimeout(refreshRem, 300); 81 }, false); 82 win.addEventListener('pageshow', function(e) { 83 if (e.persisted) { 84 clearTimeout(tid); 85 tid = setTimeout(refreshRem, 300); 86 } 87 }, false); 88 89 if (doc.readyState === 'complete') { 90 doc.body.style.fontSize = 12 * dpr + 'px'; 91 } else { 92 doc.addEventListener('DOMContentLoaded', function(e) { 93 doc.body.style.fontSize = 12 * dpr + 'px'; 94 }, false); 95 } 96 97 98 refreshRem(); 99 100 flexible.dpr = win.dpr = dpr; 101 flexible.refreshRem = refreshRem; 102 flexible.rem2px = function(d) { 103 var val = parseFloat(d) * this.rem; 104 if (typeof d === 'string' && d.match(/rem$/)) { 105 val += 'px'; 106 } 107 return val; 108 } 109 flexible.px2rem = function(d) { 110 var val = parseFloat(d) / this.rem; 111 if (typeof d === 'string' && d.match(/px$/)) { 112 val += 'rem'; 113 } 114 return val; 115 } 116 117 })(window, window['lib'] || (window['lib'] = {}));
用rem写1px 维护行方便;图片高度可以用rem固定高度,防止加载时出现高度自动网速加载慢导致的明显塌陷; 缺点: 动态控制 viewport retina下,无论美团还是淘宝用 rem始终还有许多细小的问题;在ios上浏览器打开仔细看还是看的出的,安卓上没看出来;
有时候retina下, viewport 缩放动态控制字体大小;<meta name="viewport" content="initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no"> 竖线或者奇数偶数行横线 或者动态添加显示的元素 之后的1px线条,有的1.1px 或者1.2px等等...拿手机仔细看下,观察iphone5 以及iphone6 safari以及其他浏览器对比下就知道,以下是截图出来问题的(只是示范一下 红色箭头的 border 线条 ),同样都是像素比 ratio=2 真机上细看还是明显的。
H5 Canvas Retina屏幕处理的1px的函数
1 /** 2 * HiDPI Canvas Polyfill (1.0.9) 3 * 4 * Author: Jonathan D. Johnson (http://jondavidjohn.com) 5 * Homepage: https://github.com/jondavidjohn/hidpi-canvas-polyfill 6 * Issue Tracker: https://github.com/jondavidjohn/hidpi-canvas-polyfill/issues 7 * License: Apache 2.0 8 */ 9 ;(function(prototype) { 10 11 var pixelRatio = (function(context) { 12 var backingStore = context.backingStorePixelRatio || 13 context.webkitBackingStorePixelRatio || 14 context.mozBackingStorePixelRatio || 15 context.msBackingStorePixelRatio || 16 context.oBackingStorePixelRatio || 17 context.backingStorePixelRatio || 1; 18 19 return (window.devicePixelRatio || 1) / backingStore; 20 })(prototype), 21 22 forEach = function(obj, func) { 23 for (var p in obj) { 24 if (obj.hasOwnProperty(p)) { 25 func(obj[p], p); 26 } 27 } 28 }, 29 30 ratioArgs = { 31 'fillRect': 'all', 32 'clearRect': 'all', 33 'strokeRect': 'all', 34 'moveTo': 'all', 35 'lineTo': 'all', 36 'arc': [0,1,2], 37 'arcTo': 'all', 38 'bezierCurveTo': 'all', 39 'isPointinPath': 'all', 40 'isPointinStroke': 'all', 41 'quadraticCurveTo': 'all', 42 'rect': 'all', 43 'translate': 'all', 44 'createRadialGradient': 'all', 45 'createLinearGradient': 'all' 46 }; 47 48 if (pixelRatio === 1) return; 49 50 forEach(ratioArgs, function(value, key) { 51 prototype[key] = (function(_super) { 52 return function() { 53 var i, len, 54 args = Array.prototype.slice.call(arguments); 55 56 if (value === 'all') { 57 args = args.map(function(a) { 58 return a * pixelRatio; 59 }); 60 } 61 else if (Array.isArray(value)) { 62 for (i = 0, len = value.length; i < len; i++) { 63 args[value[i]] *= pixelRatio; 64 } 65 } 66 67 return _super.apply(this, args); 68 }; 69 })(prototype[key]); 70 }); 71 72 // Stroke lineWidth adjustment 73 prototype.stroke = (function(_super) { 74 return function() { 75 this.lineWidth *= pixelRatio; 76 _super.apply(this, arguments); 77 this.lineWidth /= pixelRatio; 78 }; 79 })(prototype.stroke); 80 81 // Text 82 // 83 prototype.fillText = (function(_super) { 84 return function() { 85 var args = Array.prototype.slice.call(arguments); 86 87 args[1] *= pixelRatio; // x 88 args[2] *= pixelRatio; // y 89 90 this.font = this.font.replace( 91 /(\d+)(px|em|rem|pt)/g, 92 function(w, m, u) { 93 return (m * pixelRatio) + u; 94 } 95 ); 96 97 _super.apply(this, args); 98 99 this.font = this.font.replace( 100 /(\d+)(px|em|rem|pt)/g, 101 function(w, m, u) { 102 return (m / pixelRatio) + u; 103 } 104 ); 105 }; 106 })(prototype.fillText); 107 108 prototype.strokeText = (function(_super) { 109 return function() { 110 var args = Array.prototype.slice.call(arguments); 111 112 args[1] *= pixelRatio; // x 113 args[2] *= pixelRatio; // y 114 115 this.font = this.font.replace( 116 /(\d+)(px|em|rem|pt)/g, 117 function(w, m, u) { 118 return (m * pixelRatio) + u; 119 } 120 ); 121 122 _super.apply(this, args); 123 124 this.font = this.font.replace( 125 /(\d+)(px|em|rem|pt)/g, 126 function(w, m, u) { 127 return (m / pixelRatio) + u; 128 } 129 ); 130 }; 131 })(prototype.strokeText); 132 })(CanvasRenderingContext2D.prototype); 133 ;(function(prototype) { 134 prototype.getContext = (function(_super) { 135 return function(type) { 136 var backingStore, ratio, 137 context = _super.call(this, type); 138 139 if (type === '2d') { 140 141 backingStore = context.backingStorePixelRatio || 142 context.webkitBackingStorePixelRatio || 143 context.mozBackingStorePixelRatio || 144 context.msBackingStorePixelRatio || 145 context.oBackingStorePixelRatio || 146 context.backingStorePixelRatio || 1; 147 148 ratio = (window.devicePixelRatio || 1) / backingStore; 149 150 if (ratio > 1) { 151 this.style.height = this.height + 'px'; 152 this.style.width = this.width + 'px'; 153 this.width *= ratio; 154 this.height *= ratio; 155 } 156 } 157 158 return context; 159 }; 160 })(prototype.getContext); 161 })(HTMLCanvasElement.prototype);
viewport + REM的方式来实现:
在devicePixelRatio = 2 时,输出viewport
1 <meta name="viewport" content="initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no">
在devicePixelRatio = 3 时,输出viewport
1 <meta name="viewport" content="initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no">
代码:
1 <script type="text/javascript"> 2 (function() { 3 var value=1; 4 if (window.devicePixelRatio == 2) { 5 value=0.5; 6 }else if(window.devicePixelRatio == 3){ 7 value=0.333333333333333; 8 } 9 var text = '<meta name="viewport" content="initial-scale=' + value + ', maximum-scale=' + value +', minimum-scale=' + value + ', width=device-width, user-scalable=no" />'; 10 document.write(text); 11 })(); 12 </script>
同时通过设置对应viewport的rem基准值,这种方式就可以像以前一样轻松愉快的写1px了。
需要使用rem,我们需要设置根的font-size。