简体   繁体   中英

How do I determine the resolution of a computer screen in javascript?

I noticed that the <canvas> element can have different scales. For instance, if I set the CSS width and height to 100px, but have the javascript set the element's width and height to 200px, the element is sized down so everything printed on it is 1/2 the size. (Or 2x the resolution)

I have a retina screen Macbookpro, so in development, I set the scaling to 2x so the images and objects look clear and crisp on my screen.

I have heard that other screens can have a 1.2x resolution (CSS pixels vs Actual pixels)

Is there a way to find out what the resolution/scaling is of the device's screen so I can make my canvas as crisp and as clean as possible to the user?

If it helps at all, I'm trying to make a game in javascript using canvas as my graphics output.

These properties will give your dimensions:

window.screen.availHeight

window.screen.availWidth

For pixel depth, use this property:

window.devicePixelRatio

For application in canvas, a helpful script and explanation is given here .

After searching around using different terms, I was able to find the answer that I was looking for.

The window object has a variable called window.devicePixelRatio . This lets us know the ratio of pixels to the device's screen pixels. On my retina screen, this variable gives me a 2 . With this, I can set the canvas to the correct scaling so it looks clean and crisp on any screen.

Source: http://www.html5rocks.com/en/tutorials/canvas/hidpi/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM