如何在JavaScript中獲取螢幕畫素深度?
在本教程中,我們將討論如何在JavaScript中獲取螢幕的畫素深度。JavaScript中有一個名為pixelDepth的屬性,藉助此屬性,我們可以快速返回螢幕顏色的畫素深度。此pixelDepth屬性以每畫素位數返回螢幕的顏色深度,並且此屬性是隻讀的(屬性的值可以訪問,但不能賦值。或者我們可以說它不能被賦值或覆蓋)。
基本上,我們返回的是用於儲存螢幕畫素的位數。可以顯示的顏色最大數量稱為顏色深度,有時也稱為“畫素深度”和“位深度”。現代顯示卡支援真彩色(24位顏色),這是逼真影像和影片所需的。
語法
讓我們看看使用JavaScript返回螢幕顏色畫素深度的語法:
let depth; // declaration of the depth type of int depth = screen.pixelDepth;
這裡我們定義了‘let’變數(我們也可以使用‘var’代替let),然後使用JavaScript的screen.pixelDepth屬性將螢幕的顏色深度賦給let變數。
注意 - 在 Internet Explorer 9 之前,不支援 pixelDepth 屬性。但是,pixelDepth 和 colorDepth 返回的結果相同。可以使用 colorDepth (screen.colourDepth) 屬性作為替代,因為它受所有瀏覽器支援。
演算法
我們已經看到了上面返回螢幕顏色畫素深度的語法,現在我們將逐步瞭解完整的步驟:
首先,我們將建立HTML程式碼的主體。
在主體中,我們將使用‘button’標籤建立一個按鈕。
在按鈕中,我們將定義‘onclick()’事件,該事件將呼叫我們將在script標籤中建立的函式。
在指令碼中,我們將建立一個變數來儲存從‘screen.pixelDepth’方法獲得的值。
使用‘document.write’方法列印螢幕的顏色畫素深度。
示例 1
我們已經看到了獲取螢幕畫素深度的步驟,現在讓我們將這些步驟實現到程式碼中,以便更好地理解:
<!DOCTYPE html> <html> <head> <script> function display(){ let cur = screen.pixelDepth; document.write("Pixel Depth of the screen is: " + cur); } </script> </head> <body> <h3>Click the below given button to return pixel depth of the screen in JavaScript</h3> <button onclick="display()"> Click me!! </button> </body> </html> <body> <p>Set the width of the columns</p> <button onclick="display()">Change Width</button> <div id="myID"> This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. This is Demo Text. </div> </body> </html>
在上面的程式碼中,我們首先定義了程式碼的主體,在其中我們使用<button>標籤建立了一個按鈕,單擊該按鈕將呼叫“display()”函式,該函式由‘onclick’事件定義。
我們在script標籤中定義了‘display’函式,它包含變數‘cur’,該變數將包含‘screen.pixelDepth’方法的返回值,最後它將列印到文件中。
注意 - 關於獲取螢幕深度的畫素方法,我們還有另外兩個與螢幕相關的 方法,它們是‘screen.width’和‘screen.height’。正如方法的語法所建議的那樣,這些函式分別用於獲取螢幕的寬度和高度。
示例 2
讓我們看看使用這些函式並獲取螢幕所有詳細資訊的程式碼:
<!DOCTYPE html> <html> <head> <script> function display(){ let height = screen.height; let width = screen.width; let pixel = screen.pixelDepth; document.write("Dimentions of the screen are: "); document.write("<br> Height is: " + height); document.write("<br> Width is: " + width); document.write("<br> depth is: " + pixel); } </script> </head> <body> <h3>Click the below given button to return pixel depth, screen width, and screen height in JavaScript</h3> <button onclick="display()"> Click me!! </button> </body> </html>
在上面的程式碼中,我們首先定義了程式碼的主體,在其中我們使用<button>標籤建立了一個按鈕,單擊該按鈕將呼叫“display()”函式,該函式由‘onclick’事件定義。
我們在script標籤中定義了‘display’函式,它包含變數‘height’,‘width’和‘’,它們將包含‘screen.height’,‘screen.width’和‘screen.pixelDepth’方法的返回值,最後它將這些值列印到文件中。
結論
在本教程中,我們學習瞭如何在JavaScript中獲取螢幕的畫素深度。JavaScript中有一個名為pixelDepth的屬性,藉助此屬性,我們可以快速返回螢幕顏色的畫素深度。此pixelDepth屬性以每畫素位數返回螢幕的顏色深度,並且此屬性是隻讀的。