window属性:devicePixelRatio

2018-04-03 10:54 更新

devicePixelRatio属性

该 Window 属性 devicePixelRatio 能够返回当前显示设备的物理像素分辨率与 CSS 像素分辨率的比率。此值也可以解释为像素大小的比率:一个 CSS 像素的大小与一个物理像素的大小的比值。简单地说,这告诉浏览器应该使用多少个屏幕的实际像素来绘制单个 CSS 像素。

这在处理标准显示与 HiDPI 或 Retina 显示之间的差异时很有用,它使用更多屏幕像素绘制相同对象,从而产生更清晰的图像。

当此值发生变化时(例如,如果用户将 window 拖到具有不同像素密度的显示器上),则无法通知该值。由于没有可用于检测像素密度变化的回调或事件,因此唯一的方法是定期检查其 devicePixelRatio 值是否已更改。不要经常这样做,否则会影响性能。

devicePixelRatio属性语法

value = window.devicePixelRatio;

devicePixelRatio属性值

devicePixelRatio 属性值为一个 double。

devicePixelRatio属性示例

一个 canvas 在视网膜屏幕上可能显得太模糊。使用  window.devicePixelRatio 以确定应该添加多少额外的像素密度以允许更清晰的图像。

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

// Set display size (css pixels).
var size = 200;
canvas.style.width = size + "px";
canvas.style.height = size + "px";

// Set actual size in memory (scaled to account for extra pixel density).
var scale = window.devicePixelRatio; // <--- Change to 1 on retina screens to see blurry canvas.
canvas.width = size * scale;
canvas.height = size * scale;

// Normalize coordinate system to use css pixels.
ctx.scale(scale, scale);

ctx.fillStyle = "#bada55";
ctx.fillRect(10, 10, 300, 300);
ctx.fillStyle = "#ffffff";
ctx.font = '18px Arial';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';

var x = size / 2;
var y = size / 2;

var textString = "I love MDN";
ctx.fillText(textString, x, y);

window属性:devicePixelRatio

规范

规范状态注释
CSS对象模型(CSSOM)视图模块
该规范中'Window.devicePixelRatio'的定义。
Working Draft
初始定义

浏览器兼容性

我们正在将兼容性数据转换为机器可读的JSON格式。

  • 电脑端
特征Chrome
Edge
Firefox(Gecko)
Internet Explorer
Opera
Safari
基本支持支持支持支持:49支持:11支持:41支持:9.1 
  • 移动端

特征Android WebviewChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本支持支持支持支持??支持支持:9.3
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号