{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076301,"cells":{"text":{"kind":"string","value":"export const Path = 'gallery/';\n\nexport const Gallery = {\n images: [\n {\n name: 'Darth Vader',\n alt: 'A Black Clad warrior lego toy',\n url: 'gallery/myLittleVader.jpg',\n credit:\n 'legOfenris, published under a Attribution-NonCommercial-NoDerivs 2.0 Generic license.',\n },\n\n {\n name: 'Snow Troopers',\n alt: 'Two lego solders in white outfits walking across an icy plain',\n url: 'gallery/snowTroopers.jpg',\n credit:\n 'legOfenris, published under a Attribution-NonCommercial-NoDerivs 2.0 Generic license.',\n },\n\n {\n name: 'Bounty Hunters',\n alt: 'A group of bounty hunters meeting, aliens and humans in costumes.',\n url: 'gallery/bountyHunters.jpg',\n credit:\n 'legOfenris, published under a Attribution-NonCommercial-NoDerivs 2.0 Generic license.',\n },\n ],\n};\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076302,"cells":{"text":{"kind":"string","value":"html,\nbody {\n margin: 0;\n padding: 0;\n font-size: 10px;\n font-family: sans-serif;\n}\n\nh1 {\n text-indent: 100%;\n white-space: nowrap;\n overflow: hidden;\n height: 197px;\n background: url(star-wars-logo.jpg) no-repeat center;\n}\n\nsection {\n max-width: 640px;\n margin: 0 auto;\n}\n\nfigure {\n width: 100%;\n margin: 0;\n}\n\nimg {\n width: 100%;\n box-shadow: 2px 2px 1px black;\n}\n\ncaption {\n display: block;\n margin: 0 auto 1rem;\n width: 70%;\n font-size: 1.2rem;\n line-height: 1.5;\n padding: 5px;\n background: #ccc;\n box-shadow: 1px 1px 1px black;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076303,"cells":{"text":{"kind":"string","value":"const addResourcesToCache = async (resources) => {\n const cache = await caches.open('v1');\n await cache.addAll(resources);\n};\n\nconst putInCache = async (request, response) => {\n const cache = await caches.open('v1');\n await cache.put(request, response);\n};\n\nconst cacheFirst = async ({ request, preloadResponsePromise, fallbackUrl }) => {\n // First try to get the resource from the cache\n const responseFromCache = await caches.match(request);\n if (responseFromCache) {\n return responseFromCache;\n }\n\n // Next try to use the preloaded response, if it's there\n const preloadResponse = await preloadResponsePromise;\n if (preloadResponse) {\n console.info('using preload response', preloadResponse);\n putInCache(request, preloadResponse.clone());\n return preloadResponse;\n }\n\n // Next try to get the resource from the network\n try {\n const responseFromNetwork = await fetch(request.clone());\n // response may be used only once\n // we need to save clone to put one copy in cache\n // and serve second one\n putInCache(request, responseFromNetwork.clone());\n return responseFromNetwork;\n } catch (error) {\n const fallbackResponse = await caches.match(fallbackUrl);\n if (fallbackResponse) {\n return fallbackResponse;\n }\n // when even the fallback response is not available,\n // there is nothing we can do, but we must always\n // return a Response object\n return new Response('Network error happened', {\n status: 408,\n headers: { 'Content-Type': 'text/plain' },\n });\n }\n};\n\nconst enableNavigationPreload = async () => {\n if (self.registration.navigationPreload) {\n // Enable navigation preloads!\n await self.registration.navigationPreload.enable();\n }\n};\n\nself.addEventListener('activate', (event) => {\n event.waitUntil(enableNavigationPreload());\n});\n\nself.addEventListener('install', (event) => {\n event.waitUntil(\n addResourcesToCache([\n './',\n './index.html',\n './style.css',\n './app.js',\n './image-list.js',\n './star-wars-logo.jpg',\n './gallery/bountyHunters.jpg',\n './gallery/myLittleVader.jpg',\n './gallery/snowTroopers.jpg',\n ])\n );\n});\n\nself.addEventListener('fetch', (event) => {\n event.respondWith(\n cacheFirst({\n request: event.request,\n preloadResponsePromise: event.preloadResponse,\n fallbackUrl: './gallery/myLittleVader.jpg',\n })\n );\n});\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076304,"cells":{"text":{"kind":"string","value":"# simple service worker\n\nService Worker test repository. This is a simple demo showing basic service worker features. The demo can be seen on [our GitHub pages](https://mdn.github.io/dom-examples/service-worker/simple-service-worker/).\n\nYou can learn more about how this works by reading [using service workers](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers).\nIn particular, read [\"Why is my service worker failing to register?\"](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API/Using_Service_Workers#Why_is_my_service_worker_failing_to_register)\nif you are having problems getting your code to do anything. You need to change the paths relative to where you are serving your files!\n\n## Running locally\n\nTo get this code running locally on your computer as-is, you need to do the following:\n\n1. Ensure that you have Nodejs installed. The best way to do this is either using [`nvm`](https://github.com/nvm-sh/nvm) or [`nvm-windows`](https://github.com/coreybutler/nvm-windows).\n2. Clone the repo in a location on your machine.\n3. Start a local server in the root of this directory using [`lite-server`](https://www.npmjs.com/package/lite-server). `npx lite-server .`\n4. When the server starts, the `index.html`` page will open in your default browser.\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076305,"cells":{"text":{"kind":"string","value":"\n\n \n \n Popover API examples\n \n \n

MDN Popover API examples

\n\n

\n This set of examples demonstrates usage of the\n Popover API\n (also see the\n specification).\n

\n\n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076306,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Nested popovers example\n \n \n \n \n \n
\n \n
\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076307,"cells":{"text":{"kind":"string","value":"const subcontainer = document.querySelector(\".subcontainer\");\nconst mainpopover = document.getElementById(\"mainpopover\");\nconst subpopover = document.getElementById(\"subpopover\");\n\n// Events to show/hide the subpopover when the mouse moves over and out\nsubcontainer.addEventListener(\"mouseover\", () => {\n subpopover.showPopover();\n});\n\nsubcontainer.addEventListener(\"mouseout\", () => {\n if (subpopover.matches(\":popover-open\")) {\n subpopover.hidePopover();\n }\n});\n\n// Event to make the subpopover keyboard-accessible\nsubcontainer.addEventListener(\"focusin\", () => {\n subpopover.showPopover();\n});\n\n// Events to hide the popover menus when an option is selected in either of them\nmainpopover.addEventListener(\"click\", () => {\n if (subpopover.matches(\":popover-open\")) {\n subpopover.hidePopover();\n }\n\n if (mainpopover.matches(\":popover-open\")) {\n mainpopover.hidePopover();\n }\n});\n\nsubpopover.addEventListener(\"click\", () => {\n subpopover.hidePopover();\n mainpopover.hidePopover();\n});\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076308,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Multiple manual popovers example\n \n \n \n \n \n
\n \n \n\n
Popover content #1
\n
Popover content #2
\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076309,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Toast popovers example\n \n \n \n \n \n \n\n

Successes: 0. Failures: 0.

\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076310,"cells":{"text":{"kind":"string","value":"const successToastBtn = document.getElementById(\"success-toast-btn\");\nconst failureToastBtn = document.getElementById(\"failure-toast-btn\");\nconst counter = document.querySelector(\"p\");\n\nlet successCount = 0;\nlet failCount = 0;\n\nfunction makeToast(result) {\n // Create an element and make it into a popover\n const popover = document.createElement(\"article\");\n popover.popover = \"manual\";\n popover.classList.add(\"toast\");\n popover.classList.add(\"newest\");\n\n let msg;\n\n // Give the toast an appropriate text content, class for styling, and update\n // the relevant count, depending on whether it was a success or a failure\n if (result === \"success\") {\n msg = \"Action was successful!\";\n popover.classList.add(\"success\");\n successCount++;\n } else if (result === \"failure\") {\n msg = \"Action failed!\";\n popover.classList.add(\"failure\");\n failCount++;\n } else {\n return;\n }\n\n // Give the toast its text content, and add it to the DOM\n popover.textContent = msg;\n document.body.appendChild(popover);\n\n // Show the popover\n popover.showPopover();\n\n // Update the counter paragraph\n updateCounter();\n\n // Remove the toast again after 4 seconds\n setTimeout(() => {\n popover.hidePopover();\n popover.remove();\n }, 4000);\n\n // When a new toast appears, run the movetoastsUp() function\n popover.addEventListener(\"toggle\", (event) => {\n if (event.newState === \"open\") {\n moveToastsUp();\n }\n });\n}\n\nfunction moveToastsUp() {\n const toasts = document.querySelectorAll(\".toast\");\n\n toasts.forEach((toast) => {\n // If the toast is the one that has just appeared, we don't want it to move up.\n if (toast.classList.contains(\"newest\")) {\n toast.style.bottom = `5px`;\n toast.classList.remove(\"newest\");\n } else {\n // Move up all the other toasts by 50px to make way for the new one\n const prevValue = toast.style.bottom.replace(\"px\", \"\");\n const newValue = parseInt(prevValue) + 50;\n toast.style.bottom = `${newValue}px`;\n }\n });\n}\n\nfunction updateCounter() {\n // Update the counter paragraph with the new count each time a new toast is generated\n counter.textContent = `Successes: ${successCount}. Failures: ${failCount}.`;\n}\n\n// Handlers to wire up the buttons to the makeToast() function\nsuccessToastBtn.addEventListener(\"click\", () => {\n makeToast(\"success\");\n});\n\nfailureToastBtn.addEventListener(\"click\", () => {\n makeToast(\"failure\");\n});\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076311,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Blur background example\n \n \n \n \n
\n

Popover heading

\n

\n This here is some very important content that we want to draw your\n attention to before you light dismiss it. Read it all, do not delay!\n

\n
\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076312,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Basic declarative popover example\n \n \n \n \n
Popover content
\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076313,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Toggle help UI example\n \n \n \n \n \n\n

Click the above button or press \"h\" to get help with using our awesome app.

\n\n
\n

Help!

\n\n

You can use the following commands to control the app

\n\n
    \n
  • Press C to order cheese
  • \n
  • Press T to order tofu
  • \n
  • Press B to order bacon
  • \n
    \n
  • Say \"Service\" to summon the robot waiter to take your order
  • \n
  • Say \"Escape\" to engage the ejector seat
  • \n
\n
\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076314,"cells":{"text":{"kind":"string","value":"function supportsPopover() {\n return HTMLElement.prototype.hasOwnProperty(\"popover\");\n}\n\nconst popover = document.getElementById(\"mypopover\");\nconst toggleBtn = document.getElementById(\"toggleBtn\");\n\nconst keyboardHelpPara = document.getElementById(\"keyboard-help-para\");\n\nconst popoverSupported = supportsPopover();\n\nif (popoverSupported) {\n popover.popover = \"auto\";\n toggleBtn.popoverTargetElement = popover;\n toggleBtn.popoverTargetAction = \"toggle\";\n\n document.addEventListener(\"keydown\", (event) => {\n if (event.key === \"h\") {\n popover.togglePopover();\n }\n });\n} else {\n toggleBtn.style.display = \"none\";\n keyboardHelpPara.style.display = \"none\";\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076315,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Popover positioning example\n \n \n \n \n \n
\n

Popover heading

\n

Popover content

\n
\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076316,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Multiple auto popovers example\n \n \n \n \n \n\n
Popover content #1
\n
Popover content #2
\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076317,"cells":{"text":{"kind":"string","value":"\n\n\n \n Abort APi example\n \n\n\n\n
\n

Simple offline video player

\n
\n \n \n

\n
\n
\n

Sintel © copyright Blender Foundation | www.sintel.org.

\n
\n
\n\n\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076318,"cells":{"text":{"kind":"string","value":"\n\n\n matchMedia test file\n \n\n\n

matchMedia test

\n\n

\n \n\n\n\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076319,"cells":{"text":{"kind":"string","value":"\n\n\nUsing Drag and Drop API to copy and move elements\n\n\n\n\n\n

Drag and Drop: Copy and Move elements with DataTransfer

\n
\n Select this element and drag to the Copy Drop Zone.\n
\n
Copy Drop Zone
\n
\n Select this element and drag to the Move Drop Zone.\n
\n
Move Drop Zone
\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076320,"cells":{"text":{"kind":"string","value":"\n\n\nUsing Drag and Drop API to copy and move elements\n\n\n\n\n\n

Drag and Drop: Copy and Move elements with DataTransferItemList interface

\n
\n Select this element and drag to the Copy Drop Zone.\n
\n
Copy Drop Zone
\n
\n Select this element and drag to the Move Drop Zone.\n
\n
Move Drop Zone
\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076321,"cells":{"text":{"kind":"string","value":"\n\nFeature tests for DnD interfaces\n\n\n\n\n

Log support of DnD objects' methods and properties

\n
\n

\n Select this element, drag it to the Drop Zone and then release the mouse. The console log will contain data about the DnD interfaces supported.

\n
\n
Drop Zone
\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076322,"cells":{"text":{"kind":"string","value":"\n\n\n Demo: Drag and Drop files\n \n \n\n\n

Drag and drop files

\n \n
\n

Drag one or more files to this Drop Zone ...

\n
\n\n \n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076323,"cells":{"text":{"kind":"string","value":"Examples:\n\n* [Copy and Move elements with DataTransfer](https://mdn.github.io/dom-examples/drag-and-drop/copy-move-DataTransfer.html) interface. This Web app should work on all browsers that support HTML Drag and Drop.\n* [Copy and Move elements with DataTransferItemList](http://mdn.github.io/dom-examples/drag-and-drop/copy-move-DataTransferItemList.html) interface. This Web app will only work with browsers that support the DnD [DataTransferItem](https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem) and [DataTransferItemList](https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList) interfaces.\n* [DnD Feature Check](http://mdn.github.io/dom-examples/drag-and-drop/DnD-support.html). This app logs to the console whether or not the browser supports the DnD interfaces ([DragEvent](https://developer.mozilla.org/en-US/docs/Web/API/DragEvent), [DataTransfer](https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer), [DataTransferItem](https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItem) and [DataTransferItemList](https://developer.mozilla.org/en-US/docs/Web/API/DataTransferItemList)).\n* [File Drag and Drop](http://mdn.github.io/dom-examples/drag-and-drop/File-drag.html). Select one or more files in a File Manager and drag them to this app's drop zone.\n\nExternal DnD Demos:\n\n* [Drag and Drop File](https://jsbin.com/hiqasek/edit?html,js,output); jsbin\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076324,"cells":{"text":{"kind":"string","value":"\n\n\n\nTouch Events tutorial\n\n\n\n\n\n\n

Multi-touch interaction

\n \n
Tap, Hold or Swipe me 1
\n
Tap, Hold or Swipe me 2
\n
Tap, Hold or Swipe me 3
\n
Tap, Hold or Swipe me 4
\n\n \n \n \n

\n \n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076325,"cells":{"text":{"kind":"string","value":"\n\n \n \n \n Basic View Transitions API demo\n\n \n \n \n \n \n \n \n

Basic View Transitions API demo

\n \n
\n
\n \n
\n
\n
\n \n
\n
\n
\n
\n\n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076326,"cells":{"text":{"kind":"string","value":"/* resets */\n\nfigure {\n margin: 0\n}\n\n/* layout */\n\nbody {\n width: 70%;\n max-width: 700px;\n\n margin: 0 auto;\n}\n\nmain {\n display: flex;\n}\n\nimg {\n border: 1px solid #999;\n}\n\n.thumbs img {\n display: block;\n margin: 10px;\n border-radius: 7px;\n opacity: 0.7;\n}\n\na {\n outline: 0;\n}\n\n.thumbs a:hover img, .thumbs a:focus img {\n opacity: 1;\n}\n\n.thumbs img:first-child {\n margin-top: 0px;\n}\n\n.gallery-view img {\n max-width: 100%;\n margin-right: 10px;\n border-radius: 7px;\n}\n\nfooter, figcaption {\n position: absolute;\n padding: 5px 10px;\n background-color: rgba(255,255,255,0.5);\n}\n\nfooter {\n bottom: 3px;\n left: 3px;\n}\n\nfigure {\n position: relative;\n}\n\nfigcaption {\n top: 0px;\n right: -2px;\n border: 1px solid #999;\n border-radius: 0 7px 0 7px;\n}\n\n/* text */\n\nh1, figcaption, a {\n font-family: 'Roboto Slab', serif;\n}\n\nh1 {\n text-align: center;\n}\n\n/* media queries */\n\n@media (max-width: 980px) {\n body {\n width: 90%;\n }\n}\n\n@media (max-width: 700px) {\n body {\n width: 98%;\n }\n\n main {\n flex-direction: column;\n }\n\n .thumbs {\n display: flex;\n align-items: space-between;\n justify-content: space-between;\n }\n\n .thumbs img {\n margin: 0 0 10px 0;\n }\n}\n\n/* View Transitions CSS */\n\n::view-transition-old(root),\n::view-transition-new(root) {\n animation-duration: 0.5s;\n}\n\nfigcaption {\n view-transition-name: figure-caption;\n}\n\n/* Simple final style */\n\n::view-transition-old(figure-caption),\n::view-transition-new(figure-caption) {\n height: 100%;\n}\n\n/* Alternative custom animation style */\n\n/* @keyframes grow-x {\n from { transform: scaleX(0); }\n to { transform: scaleX(1); }\n}\n\n@keyframes shrink-x {\n from { transform: scaleX(1); }\n to { transform: scaleX(0); }\n}\n\n::view-transition-old(figure-caption),\n::view-transition-new(figure-caption) {\n height: auto;\n right: 0;\n left: auto;\n transform-origin: right center;\n}\n\n::view-transition-old(figure-caption) {\n animation: 0.25s linear both shrink-x;\n}\n\n::view-transition-new(figure-caption) {\n animation: 0.25s 0.25s linear both grow-x;\n} */"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076327,"cells":{"text":{"kind":"string","value":"const imageData = [\n {\n 'name': 'Jungle coast',\n 'file': 'jungle-coast',\n },\n {\n 'name': 'Bird in the tree',\n 'file': 'tree-bird',\n },\n {\n 'name': 'A view from the sky',\n 'file': 'view-from-the-sky',\n },\n {\n 'name': 'The view across the water',\n 'file': 'watery-view',\n }\n]\n\nconst thumbs = document.querySelector('.thumbs');\nconst galleryImg = document.querySelector('.gallery-view img');\nconst galleryCaption = document.querySelector('.gallery-view figcaption');\n\nfunction init() {\n imageData.forEach(data => {\n const img = document.createElement('img');\n const a = document.createElement('a');\n a.href = \"#\";\n a.title = `Click to load ${data.name} in main gallery view`;\n img.alt = data.name;\n img.src = `images/${ data.file }_th.jpg`;\n a.appendChild(img);\n thumbs.appendChild(a);\n \n a.addEventListener('click', updateView);\n a.addEventListener('keypress', updateView);\n }) \n \n galleryImg.src = `images/${ imageData[0].file }.jpg`;\n galleryCaption.textContent = imageData[0].name;\n}\n\nfunction updateView(event) {\n // Handle the difference in whether the event is fired on the or the \n const targetIdentifier = event.target.firstChild || event.target;\n\n const displayNewImage = () => {\n const mainSrc = `${targetIdentifier.src.split(\"_th.jpg\")[0]}.jpg`;\n galleryImg.src = mainSrc;\n galleryCaption.textContent = targetIdentifier.alt;\n };\n \n // Fallback for browsers that don't support View Transitions:\n if (!document.startViewTransition) {\n displayNewImage();\n return;\n }\n\n // With View Transitions:\n const transition = document.startViewTransition(() => displayNewImage());\n}\n\ninit();"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076328,"cells":{"text":{"kind":"string","value":"\n\n\n\n \n Web Animations API implicit keyframes\n \n\n\n\n
\n\n
\n\n \n\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076329,"cells":{"text":{"kind":"string","value":"\n\n\n\n \n Web Animations API replace indefinite animations\n \n\n\n\n

Click, tap, or press the space bar to start the animation (disabled by default to protect those who suffer migraines when experiencing such animations).

\n
\n\n
\n\n \n\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076330,"cells":{"text":{"kind":"string","value":"# Web animations API demos\n\nSome simple demos to show Web Animations API features.\n\n## Implicit to/from keyframes\nThat is, when you write an animation, you can leave out the end state of the animation from the keyframes, and the browser will infer it, if it can. For example:\n\n```\nlet rotate360 = [\n { transform: 'rotate(360deg)' }\n];\n``` \n\n[See the demo live](https://mdn.github.io/dom-examples/web-animations-api/implicit-keyframes.html). \n\n\n## Automatically removing filling animations\nIt is possible to trigger a large number of animations on the same element. If they are indefinite (i.e., forwards-filling), this can result in a huge animations list, which could create a memory leak. For this reason, we’ve implemented the part of the Web Animations spec that automatically removes overriding forward filling animations, unless the developer explicitly specifies to keep them.\n\n[See a live demo of this](https://mdn.github.io/dom-examples/web-animations-api/replace-indefinite-animations.html). \n\nThe related JavaScript features are as follows:\n\n* `animation.commitStyles()` — run this method to commit the end styling state of an animation to the element being animated, even after that animation has been removed. It will cause the end styling state to be written to the element being animated, in the form of properties inside a style attribute.\n* `animation.onremove` — allows you to run an event handler that fires when the animation is removed (i.e., put into an active replace state).\n* `animation.persist()` — when you explicitly want animations to be retained, then invoke persist().\n* `animation.replaceState` — returns the replace state of the animation. This will be active if the animation has been removed, or persisted if persist() has been invoked.\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076331,"cells":{"text":{"kind":"string","value":"@font-face {\n font-family: 'zillaslab';\n src: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/858/ZillaSlab.woff2') format('woff2');\n}\n\n:root {\n\t--black: hsl(0, 0%, 16%);\n\t--white: hsl(0,0%,97%);\n\t--blue: hsl(198, 100%, 66%);\n\t--teal: hsl(198, 43%, 42%);\n\t--lightYellow: hsl(43, 100%, 92%);\n\t--grey: hsl(0, 0%, 80%);\n\t--unit: 1.2rem;\n}\n\nbody {\n\tpadding: var(--unit);\n\tbackground-color: var(--white);\n\tfont-family: 'Arial', sans-serif; font-size: 100%;\n\tcolor: var(--black); line-height: 1.3;\n}\n\n/* page partials */\nfooter {\n\tpadding: var(--unit);\n\tmargin-top: calc(var(--unit)*2);\n\tborder-top: 1px solid var(--grey);\n}\nfooter p {\n\tmargin: 0px; text-align: center;\n}\n\n/* base styles */\nh1, h2 {\n\tfont-family: \"zillaslab\", serif;\n}\n\nh2 {\n\tpadding: calc(var(--unit)/2);\n\tbackground-color: var(--black);\n\tcolor: var(--white); font-weight: normal;\n}\n\np {}\n\na {\n\tborder: 1px solid var(--teal);\n\tborder-width: 0px 0px 1px 0px;\n\tcolor: var(--teal);\n\ttext-decoration: none;\n}\na:hover {\n\tborder-width: 1px 0px 0px 0px;\n}\n\nnav ul {\n\tdisplay: flex; justify-content: space-between;\n\tmargin: 0px; padding: 0px;\n\tlist-style: none;\n}\nnav li {margin: 0px; padding: 0px;}\n\ndl {display: flex; flex-wrap: wrap;}\ndt, dd {padding: 2%; box-sizing: border-box;}\ndt {width: 30%; font-weight: bold; text-align: right;}\ndd {width: 66%; margin: 0px;}\n\ncode {\n\tbackground-color: var(--lightYellow);\n\tfont-family:monospace; font-size:110%;\n\tletter-spacing:0.5px;\n}\n\npre {\n\tpadding: var(--unit);\n\tbackground-color: var(--grey);\n\tborder-left: 4px solid var(--teal);\n\twhite-space: pre-wrap;\n\toverflow-wrap: break-word;\n\ttab-size: 4; font-size: 86%;\n}\n\npre code {\n\tbackground: none;\n}"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076332,"cells":{"text":{"kind":"string","value":"\n\n\n \n Wake Lock Demo\n\t\n\t\n\t\n\t\n\n\t\n\n\t\n\n\n\n\t
\n\t\t

Wake Lock Demo

\n\t
\n\n\t

The button below changes depending on whether wake lock is active or not.

\n\n\t\n\n\t
\n\t\t

Wake Lock Status

\n\t\t

\n\t
\n\t\n\t

Wake lock will automatically release if if the tab becomes inactive.

\n\t

To re-activate the wake lock automatically when the tab becomes active again, check this box:

\n\n\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076333,"cells":{"text":{"kind":"string","value":"console.clear();\n\n// status paragraph\nconst statusElem = document.querySelector('#status p');\n// toggle button\nconst wakeButton = document.querySelector('[data-status]');\n// checkbox\nconst reaquireCheck = document.querySelector('#reaquire');\n\n// change button and status if wakelock becomes aquired or is released\nconst changeUI = (status = 'acquired') => {\n const acquired = status === 'acquired' ? true : false;\n wakeButton.dataset.status = acquired ? 'on' : 'off';\n wakeButton.textContent = `Turn Wake Lock ${acquired ? 'OFF' : 'ON'}`;\n statusElem.textContent = `Wake Lock ${acquired ? 'is active!' : 'has been released.'}`;\n}\n\n// test support\nlet isSupported = false;\n\nif ('wakeLock' in navigator) {\n isSupported = true;\n statusElem.textContent = 'Screen Wake Lock API supported 🎉';\n} else {\n wakeButton.disabled = true;\n statusElem.textContent = 'Wake lock is not supported by this browser.';\n}\n\nif (isSupported) {\n // create a reference for the wake lock\n let wakeLock = null;\n\n // create an async function to request a wake lock\n const requestWakeLock = async () => {\n try {\n wakeLock = await navigator.wakeLock.request('screen');\n\n // change up our interface to reflect wake lock active\n changeUI();\n\n // listen for our release event\n wakeLock.onrelease = function(ev) {\n console.log(ev);\n }\n wakeLock.addEventListener('release', () => {\n // if wake lock is released alter the button accordingly\n changeUI('released');\n });\n\n } catch (err) {\n // if wake lock request fails - usually system related, such as battery\n wakeButton.dataset.status = 'off';\n wakeButton.textContent = 'Turn Wake Lock ON';\n statusElem.textContent = `${err.name}, ${err.message}`;\n\n }\n } // requestWakeLock()\n\n // if we click our button\n wakeButton.addEventListener('click', () => {\n // if wakelock is off request it\n if (wakeButton.dataset.status === 'off') {\n requestWakeLock()\n } else { // if it's on release it\n wakeLock.release()\n .then(() => {\n wakeLock = null;\n })\n }\n })\n\n const handleVisibilityChange = () => {\n if (wakeLock !== null && document.visibilityState === 'visible') {\n requestWakeLock();\n }\n }\n\n reaquireCheck.addEventListener('change', () => {\n if (reaquireCheck.checked) {\n document.addEventListener('visibilitychange', handleVisibilityChange);\n } else {\n document.removeEventListener('visibilitychange', handleVisibilityChange);\n }\n });\n\n} // isSupported\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076334,"cells":{"text":{"kind":"string","value":"# MDN WebGL examples\n\nThis folder is home to examples for the MDN Web Docs content about\nthe [WebGL API](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API),\nwhich is used for 2D and 3D graphics on the web.\n\nSpecifically, each of these examples pairs with an article in the MDN\n[WebGL tutorial](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial).\n\n## The examples\n\n- [Sample 1](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample1/)\n- [Sample 2](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample2/)\n- [Sample 3](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample3/)\n- [Sample 4](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample4/)\n- [Sample 5](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample5/)\n- [Sample 6](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample6/)\n- [Sample 7](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample7/)\n- [Sample 8](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample8/)\n\n### Additional example\n\n- [Tetrahedron](https://mdn.github.io/dom-examples/webgl-examples/tutorial/tetrahedron/)\n\n## Installing and testing\n\nIf you choose to fork or clone these examples to experiment with them,\nbe aware that WebGL requires that any textures or other binary data\nbe loaded from a secure context, which means you can't just use most\nof these samples from a `file:///` URL. Instead, you need to run a\nlocal web server, or post them to a secure server online.\n\nSee our article [How do you set up a local testing server?](https://developer.mozilla.org/en-US/docs/Learn/Common_questions/set_up_a_local_testing_server) if you need help getting one set up. Alternatively, if you have [Nodejs](https://github.com/nvm-sh/nvm) installed, you can also look at [`https-localhost`](https://www.npmjs.com/package/https-localhost).\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076335,"cells":{"text":{"kind":"string","value":"function initBuffers(gl) {\n const positionBuffer = initPositionBuffer(gl);\n\n const colorBuffer = initColorBuffer(gl);\n\n const indexBuffer = initIndexBuffer(gl);\n\n return {\n position: positionBuffer,\n color: colorBuffer,\n indices: indexBuffer,\n };\n}\n\nfunction initPositionBuffer(gl) {\n // Create a buffer for the square's positions.\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n const positions = [\n // Front face\n -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,\n\n // Back face\n -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,\n\n // Top face\n -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,\n\n // Bottom face\n -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,\n\n // Right face\n 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,\n\n // Left face\n -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,\n ];\n\n // Now pass the list of positions into WebGL to build the\n // shape. We do this by creating a Float32Array from the\n // JavaScript array, then use it to fill the current buffer.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n return positionBuffer;\n}\n\nfunction initColorBuffer(gl) {\n const faceColors = [\n [1.0, 1.0, 1.0, 1.0], // Front face: white\n [1.0, 0.0, 0.0, 1.0], // Back face: red\n [0.0, 1.0, 0.0, 1.0], // Top face: green\n [0.0, 0.0, 1.0, 1.0], // Bottom face: blue\n [1.0, 1.0, 0.0, 1.0], // Right face: yellow\n [1.0, 0.0, 1.0, 1.0], // Left face: purple\n ];\n\n // Convert the array of colors into a table for all the vertices.\n\n var colors = [];\n\n for (var j = 0; j < faceColors.length; ++j) {\n const c = faceColors[j];\n // Repeat each color four times for the four vertices of the face\n colors = colors.concat(c, c, c, c);\n }\n\n const colorBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n return colorBuffer;\n}\n\nfunction initIndexBuffer(gl) {\n const indexBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);\n\n // This array defines each face as two triangles, using the\n // indices into the vertex array to specify each triangle's\n // position.\n\n const indices = [\n 0,\n 1,\n 2,\n 0,\n 2,\n 3, // front\n 4,\n 5,\n 6,\n 4,\n 6,\n 7, // back\n 8,\n 9,\n 10,\n 8,\n 10,\n 11, // top\n 12,\n 13,\n 14,\n 12,\n 14,\n 15, // bottom\n 16,\n 17,\n 18,\n 16,\n 18,\n 19, // right\n 20,\n 21,\n 22,\n 20,\n 22,\n 23, // left\n ];\n\n // Now send the element array to GL\n\n gl.bufferData(\n gl.ELEMENT_ARRAY_BUFFER,\n new Uint16Array(indices),\n gl.STATIC_DRAW\n );\n\n return indexBuffer;\n}\n\nexport { initBuffers };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076336,"cells":{"text":{"kind":"string","value":"function drawScene(gl, programInfo, buffers, cubeRotation) {\n gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque\n gl.clearDepth(1.0); // Clear everything\n gl.enable(gl.DEPTH_TEST); // Enable depth testing\n gl.depthFunc(gl.LEQUAL); // Near things obscure far things\n\n // Clear the canvas before we start drawing on it.\n\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Create a perspective matrix, a special matrix that is\n // used to simulate the distortion of perspective in a camera.\n // Our field of view is 45 degrees, with a width/height\n // ratio that matches the display size of the canvas\n // and we only want to see objects between 0.1 units\n // and 100 units away from the camera.\n\n const fieldOfView = (45 * Math.PI) / 180; // in radians\n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n // note: glmatrix.js always has the first argument\n // as the destination to receive the result.\n mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);\n\n // Set the drawing position to the \"identity\" point, which is\n // the center of the scene.\n const modelViewMatrix = mat4.create();\n\n // Now move the drawing position a bit to where we want to\n // start drawing the square.\n mat4.translate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to translate\n [-0.0, 0.0, -6.0]\n ); // amount to translate\n\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation, // amount to rotate in radians\n [0, 0, 1]\n ); // axis to rotate around (Z)\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation * 0.7, // amount to rotate in radians\n [0, 1, 0]\n ); // axis to rotate around (Y)\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation * 0.3, // amount to rotate in radians\n [1, 0, 0]\n ); // axis to rotate around (X)\n\n // Tell WebGL how to pull out the positions from the position\n // buffer into the vertexPosition attribute.\n setPositionAttribute(gl, buffers, programInfo);\n\n setColorAttribute(gl, buffers, programInfo);\n\n // Tell WebGL which indices to use to index the vertices\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);\n\n // Tell WebGL to use our program when drawing\n gl.useProgram(programInfo.program);\n\n // Set the shader uniforms\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix\n );\n\n {\n const vertexCount = 36;\n const type = gl.UNSIGNED_SHORT;\n const offset = 0;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n}\n\n// Tell WebGL how to pull out the positions from the position\n// buffer into the vertexPosition attribute.\nfunction setPositionAttribute(gl, buffers, programInfo) {\n const numComponents = 3;\n const type = gl.FLOAT; // the data in the buffer is 32bit floats\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set of values to the next\n // 0 = use type and numComponents above\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);\n}\n\n// Tell WebGL how to pull out the colors from the color buffer\n// into the vertexColor attribute.\nfunction setColorAttribute(gl, buffers, programInfo) {\n const numComponents = 4;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexColor,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);\n}\n\nexport { drawScene };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076337,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGL Demo\n \n \n \n\n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076338,"cells":{"text":{"kind":"string","value":"import { initBuffers } from \"./init-buffers.js\";\nimport { drawScene } from \"./draw-scene.js\";\n\nlet cubeRotation = 0.0;\nlet deltaTime = 0;\n\nmain();\n\n//\n// start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n // Initialize the GL context\n const gl = canvas.getContext(\"webgl\");\n\n // Only continue if WebGL is available and working\n if (gl === null) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Set clear color to black, fully opaque\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n // Clear the color buffer with specified clear color\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Vertex shader program\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec4 aVertexColor;\n\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying lowp vec4 vColor;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vColor = aVertexColor;\n }\n `;\n\n // Fragment shader program\n\n const fsSource = `\n varying lowp vec4 vColor;\n\n void main(void) {\n gl_FragColor = vColor;\n }\n `;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attributes our shader program is using\n // for aVertexPosition, aVertexColor and also\n // look up uniform locations.\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, \"aVertexPosition\"),\n vertexColor: gl.getAttribLocation(shaderProgram, \"aVertexColor\"),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(\n shaderProgram,\n \"uProjectionMatrix\"\n ),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, \"uModelViewMatrix\"),\n },\n };\n\n // Here's where we call the routine that builds all the\n // objects we'll be drawing.\n const buffers = initBuffers(gl);\n\n let then = 0;\n\n // Draw the scene repeatedly\n function render(now) {\n now *= 0.001; // convert to seconds\n deltaTime = now - then;\n then = now;\n\n drawScene(gl, programInfo, buffers, cubeRotation);\n cubeRotation += deltaTime;\n\n requestAnimationFrame(render);\n }\n requestAnimationFrame(render);\n}\n\n//\n// Initialize a shader program, so WebGL knows how to draw our data\n//\nfunction initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\n `Unable to initialize the shader program: ${gl.getProgramInfoLog(\n shaderProgram\n )}`\n );\n return null;\n }\n\n return shaderProgram;\n}\n\n//\n// creates a shader of the given type, uploads the source and\n// compiles it.\n//\nfunction loadShader(gl, type, source) {\n const shader = gl.createShader(type);\n\n // Send the source to the shader object\n\n gl.shaderSource(shader, source);\n\n // Compile the shader program\n\n gl.compileShader(shader);\n\n // See if it compiled successfully\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(\n `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`\n );\n gl.deleteShader(shader);\n return null;\n }\n\n return shader;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076339,"cells":{"text":{"kind":"string","value":"function initBuffers(gl) {\n const positionBuffer = initPositionBuffer(gl);\n\n const textureCoordBuffer = initTextureBuffer(gl);\n\n const indexBuffer = initIndexBuffer(gl);\n\n return {\n position: positionBuffer,\n textureCoord: textureCoordBuffer,\n indices: indexBuffer,\n };\n}\n\nfunction initPositionBuffer(gl) {\n // Create a buffer for the square's positions.\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n const positions = [\n // Front face\n -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,\n\n // Back face\n -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,\n\n // Top face\n -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,\n\n // Bottom face\n -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,\n\n // Right face\n 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,\n\n // Left face\n -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,\n ];\n\n // Now pass the list of positions into WebGL to build the\n // shape. We do this by creating a Float32Array from the\n // JavaScript array, then use it to fill the current buffer.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n return positionBuffer;\n}\n\nfunction initColorBuffer(gl) {\n const faceColors = [\n [1.0, 1.0, 1.0, 1.0], // Front face: white\n [1.0, 0.0, 0.0, 1.0], // Back face: red\n [0.0, 1.0, 0.0, 1.0], // Top face: green\n [0.0, 0.0, 1.0, 1.0], // Bottom face: blue\n [1.0, 1.0, 0.0, 1.0], // Right face: yellow\n [1.0, 0.0, 1.0, 1.0], // Left face: purple\n ];\n\n // Convert the array of colors into a table for all the vertices.\n\n var colors = [];\n\n for (var j = 0; j < faceColors.length; ++j) {\n const c = faceColors[j];\n // Repeat each color four times for the four vertices of the face\n colors = colors.concat(c, c, c, c);\n }\n\n const colorBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n return colorBuffer;\n}\n\nfunction initIndexBuffer(gl) {\n const indexBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);\n\n // This array defines each face as two triangles, using the\n // indices into the vertex array to specify each triangle's\n // position.\n\n const indices = [\n 0,\n 1,\n 2,\n 0,\n 2,\n 3, // front\n 4,\n 5,\n 6,\n 4,\n 6,\n 7, // back\n 8,\n 9,\n 10,\n 8,\n 10,\n 11, // top\n 12,\n 13,\n 14,\n 12,\n 14,\n 15, // bottom\n 16,\n 17,\n 18,\n 16,\n 18,\n 19, // right\n 20,\n 21,\n 22,\n 20,\n 22,\n 23, // left\n ];\n\n // Now send the element array to GL\n\n gl.bufferData(\n gl.ELEMENT_ARRAY_BUFFER,\n new Uint16Array(indices),\n gl.STATIC_DRAW\n );\n\n return indexBuffer;\n}\n\nfunction initTextureBuffer(gl) {\n const textureCoordBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);\n\n const textureCoordinates = [\n // Front\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Back\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Top\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Bottom\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Right\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Left\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n ];\n\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array(textureCoordinates),\n gl.STATIC_DRAW\n );\n\n return textureCoordBuffer;\n}\n\nexport { initBuffers };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076340,"cells":{"text":{"kind":"string","value":"function drawScene(gl, programInfo, buffers, texture, cubeRotation) {\n gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque\n gl.clearDepth(1.0); // Clear everything\n gl.enable(gl.DEPTH_TEST); // Enable depth testing\n gl.depthFunc(gl.LEQUAL); // Near things obscure far things\n\n // Clear the canvas before we start drawing on it.\n\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Create a perspective matrix, a special matrix that is\n // used to simulate the distortion of perspective in a camera.\n // Our field of view is 45 degrees, with a width/height\n // ratio that matches the display size of the canvas\n // and we only want to see objects between 0.1 units\n // and 100 units away from the camera.\n\n const fieldOfView = (45 * Math.PI) / 180; // in radians\n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n // note: glmatrix.js always has the first argument\n // as the destination to receive the result.\n mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);\n\n // Set the drawing position to the \"identity\" point, which is\n // the center of the scene.\n const modelViewMatrix = mat4.create();\n\n // Now move the drawing position a bit to where we want to\n // start drawing the square.\n mat4.translate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to translate\n [-0.0, 0.0, -6.0]\n ); // amount to translate\n\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation, // amount to rotate in radians\n [0, 0, 1]\n ); // axis to rotate around (Z)\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation * 0.7, // amount to rotate in radians\n [0, 1, 0]\n ); // axis to rotate around (Y)\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation * 0.3, // amount to rotate in radians\n [1, 0, 0]\n ); // axis to rotate around (X)\n\n // Tell WebGL how to pull out the positions from the position\n // buffer into the vertexPosition attribute.\n setPositionAttribute(gl, buffers, programInfo);\n\n setTextureAttribute(gl, buffers, programInfo);\n\n // Tell WebGL which indices to use to index the vertices\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);\n\n // Tell WebGL to use our program when drawing\n gl.useProgram(programInfo.program);\n\n // Set the shader uniforms\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix\n );\n\n // Tell WebGL we want to affect texture unit 0\n gl.activeTexture(gl.TEXTURE0);\n\n // Bind the texture to texture unit 0\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n // Tell the shader we bound the texture to texture unit 0\n gl.uniform1i(programInfo.uniformLocations.uSampler, 0);\n\n {\n const vertexCount = 36;\n const type = gl.UNSIGNED_SHORT;\n const offset = 0;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n}\n\n// Tell WebGL how to pull out the positions from the position\n// buffer into the vertexPosition attribute.\nfunction setPositionAttribute(gl, buffers, programInfo) {\n const numComponents = 3;\n const type = gl.FLOAT; // the data in the buffer is 32bit floats\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set of values to the next\n // 0 = use type and numComponents above\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);\n}\n\n// Tell WebGL how to pull out the colors from the color buffer\n// into the vertexColor attribute.\nfunction setColorAttribute(gl, buffers, programInfo) {\n const numComponents = 4;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexColor,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);\n}\n\n// tell webgl how to pull out the texture coordinates from buffer\nfunction setTextureAttribute(gl, buffers, programInfo) {\n const num = 2; // every coordinate composed of 2 values\n const type = gl.FLOAT; // the data in the buffer is 32-bit float\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set to the next\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);\n gl.vertexAttribPointer(\n programInfo.attribLocations.textureCoord,\n num,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);\n}\n\nexport { drawScene };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076341,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGL Demo\n \n \n \n\n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076342,"cells":{"text":{"kind":"string","value":"import { initBuffers } from \"./init-buffers.js\";\nimport { drawScene } from \"./draw-scene.js\";\n\nlet cubeRotation = 0.0;\nlet deltaTime = 0;\n\nmain();\n\n//\n// start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n // Initialize the GL context\n const gl = canvas.getContext(\"webgl\");\n\n // Only continue if WebGL is available and working\n if (gl === null) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Set clear color to black, fully opaque\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n // Clear the color buffer with specified clear color\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Vertex shader program\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec2 aTextureCoord;\n\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying highp vec2 vTextureCoord;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vTextureCoord = aTextureCoord;\n }\n`;\n\n // Fragment shader program\n\n const fsSource = `\n varying highp vec2 vTextureCoord;\n\n uniform sampler2D uSampler;\n\n void main(void) {\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n }\n`;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attributes our shader program is using\n // for aVertexPosition, aVertexColor and also\n // look up uniform locations.\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, \"aVertexPosition\"),\n textureCoord: gl.getAttribLocation(shaderProgram, \"aTextureCoord\"),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(\n shaderProgram,\n \"uProjectionMatrix\"\n ),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, \"uModelViewMatrix\"),\n uSampler: gl.getUniformLocation(shaderProgram, \"uSampler\"),\n },\n };\n\n // Here's where we call the routine that builds all the\n // objects we'll be drawing.\n const buffers = initBuffers(gl);\n\n // Load texture\n const texture = loadTexture(gl, \"cubetexture.png\");\n // Flip image pixels into the bottom-to-top order that WebGL expects.\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n\n let then = 0;\n\n // Draw the scene repeatedly\n function render(now) {\n now *= 0.001; // convert to seconds\n deltaTime = now - then;\n then = now;\n\n drawScene(gl, programInfo, buffers, texture, cubeRotation);\n cubeRotation += deltaTime;\n\n requestAnimationFrame(render);\n }\n requestAnimationFrame(render);\n}\n\n//\n// Initialize a shader program, so WebGL knows how to draw our data\n//\nfunction initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\n `Unable to initialize the shader program: ${gl.getProgramInfoLog(\n shaderProgram\n )}`\n );\n return null;\n }\n\n return shaderProgram;\n}\n\n//\n// creates a shader of the given type, uploads the source and\n// compiles it.\n//\nfunction loadShader(gl, type, source) {\n const shader = gl.createShader(type);\n\n // Send the source to the shader object\n\n gl.shaderSource(shader, source);\n\n // Compile the shader program\n\n gl.compileShader(shader);\n\n // See if it compiled successfully\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(\n `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`\n );\n gl.deleteShader(shader);\n return null;\n }\n\n return shader;\n}\n\n//\n// Initialize a texture and load an image.\n// When the image finished loading copy it into the texture.\n//\nfunction loadTexture(gl, url) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n // Because images have to be downloaded over the internet\n // they might take a moment until they are ready.\n // Until then put a single pixel in the texture so we can\n // use it immediately. When the image has finished downloading\n // we'll update the texture with the contents of the image.\n const level = 0;\n const internalFormat = gl.RGBA;\n const width = 1;\n const height = 1;\n const border = 0;\n const srcFormat = gl.RGBA;\n const srcType = gl.UNSIGNED_BYTE;\n const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue\n gl.texImage2D(\n gl.TEXTURE_2D,\n level,\n internalFormat,\n width,\n height,\n border,\n srcFormat,\n srcType,\n pixel\n );\n\n const image = new Image();\n image.onload = () => {\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n level,\n internalFormat,\n srcFormat,\n srcType,\n image\n );\n\n // WebGL1 has different requirements for power of 2 images\n // vs non power of 2 images so check if the image is a\n // power of 2 in both dimensions.\n if (isPowerOf2(image.width) && isPowerOf2(image.height)) {\n // Yes, it's a power of 2. Generate mips.\n gl.generateMipmap(gl.TEXTURE_2D);\n } else {\n // No, it's not a power of 2. Turn off mips and set\n // wrapping to clamp to edge\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n }\n };\n image.src = url;\n\n return texture;\n}\n\nfunction isPowerOf2(value) {\n return (value & (value - 1)) === 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076343,"cells":{"text":{"kind":"string","value":"function initBuffers(gl) {\n const positionBuffer = initPositionBuffer(gl);\n\n const textureCoordBuffer = initTextureBuffer(gl);\n\n const indexBuffer = initIndexBuffer(gl);\n\n const normalBuffer = initNormalBuffer(gl);\n\n return {\n position: positionBuffer,\n normal: normalBuffer,\n textureCoord: textureCoordBuffer,\n indices: indexBuffer,\n };\n}\n\nfunction initPositionBuffer(gl) {\n // Create a buffer for the square's positions.\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n const positions = [\n // Front face\n -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,\n\n // Back face\n -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,\n\n // Top face\n -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,\n\n // Bottom face\n -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,\n\n // Right face\n 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,\n\n // Left face\n -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,\n ];\n\n // Now pass the list of positions into WebGL to build the\n // shape. We do this by creating a Float32Array from the\n // JavaScript array, then use it to fill the current buffer.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n return positionBuffer;\n}\n\nfunction initColorBuffer(gl) {\n const faceColors = [\n [1.0, 1.0, 1.0, 1.0], // Front face: white\n [1.0, 0.0, 0.0, 1.0], // Back face: red\n [0.0, 1.0, 0.0, 1.0], // Top face: green\n [0.0, 0.0, 1.0, 1.0], // Bottom face: blue\n [1.0, 1.0, 0.0, 1.0], // Right face: yellow\n [1.0, 0.0, 1.0, 1.0], // Left face: purple\n ];\n\n // Convert the array of colors into a table for all the vertices.\n\n var colors = [];\n\n for (var j = 0; j < faceColors.length; ++j) {\n const c = faceColors[j];\n // Repeat each color four times for the four vertices of the face\n colors = colors.concat(c, c, c, c);\n }\n\n const colorBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n return colorBuffer;\n}\n\nfunction initIndexBuffer(gl) {\n const indexBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);\n\n // This array defines each face as two triangles, using the\n // indices into the vertex array to specify each triangle's\n // position.\n\n const indices = [\n 0,\n 1,\n 2,\n 0,\n 2,\n 3, // front\n 4,\n 5,\n 6,\n 4,\n 6,\n 7, // back\n 8,\n 9,\n 10,\n 8,\n 10,\n 11, // top\n 12,\n 13,\n 14,\n 12,\n 14,\n 15, // bottom\n 16,\n 17,\n 18,\n 16,\n 18,\n 19, // right\n 20,\n 21,\n 22,\n 20,\n 22,\n 23, // left\n ];\n\n // Now send the element array to GL\n\n gl.bufferData(\n gl.ELEMENT_ARRAY_BUFFER,\n new Uint16Array(indices),\n gl.STATIC_DRAW\n );\n\n return indexBuffer;\n}\n\nfunction initTextureBuffer(gl) {\n const textureCoordBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);\n\n const textureCoordinates = [\n // Front\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Back\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Top\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Bottom\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Right\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Left\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n ];\n\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array(textureCoordinates),\n gl.STATIC_DRAW\n );\n\n return textureCoordBuffer;\n}\n\nfunction initNormalBuffer(gl) {\n const normalBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);\n\n const vertexNormals = [\n // Front\n 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n\n // Back\n 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0,\n\n // Top\n 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,\n\n // Bottom\n 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0,\n\n // Right\n 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,\n\n // Left\n -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0,\n ];\n\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array(vertexNormals),\n gl.STATIC_DRAW\n );\n\n return normalBuffer;\n}\n\nexport { initBuffers };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076344,"cells":{"text":{"kind":"string","value":"function drawScene(gl, programInfo, buffers, texture, cubeRotation) {\n gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque\n gl.clearDepth(1.0); // Clear everything\n gl.enable(gl.DEPTH_TEST); // Enable depth testing\n gl.depthFunc(gl.LEQUAL); // Near things obscure far things\n\n // Clear the canvas before we start drawing on it.\n\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Create a perspective matrix, a special matrix that is\n // used to simulate the distortion of perspective in a camera.\n // Our field of view is 45 degrees, with a width/height\n // ratio that matches the display size of the canvas\n // and we only want to see objects between 0.1 units\n // and 100 units away from the camera.\n\n const fieldOfView = (45 * Math.PI) / 180; // in radians\n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n // note: glmatrix.js always has the first argument\n // as the destination to receive the result.\n mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);\n\n // Set the drawing position to the \"identity\" point, which is\n // the center of the scene.\n const modelViewMatrix = mat4.create();\n\n // Now move the drawing position a bit to where we want to\n // start drawing the square.\n mat4.translate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to translate\n [-0.0, 0.0, -6.0]\n ); // amount to translate\n\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation, // amount to rotate in radians\n [0, 0, 1]\n ); // axis to rotate around (Z)\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation * 0.7, // amount to rotate in radians\n [0, 1, 0]\n ); // axis to rotate around (Y)\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation * 0.3, // amount to rotate in radians\n [1, 0, 0]\n ); // axis to rotate around (X)\n\n const normalMatrix = mat4.create();\n mat4.invert(normalMatrix, modelViewMatrix);\n mat4.transpose(normalMatrix, normalMatrix);\n\n // Tell WebGL how to pull out the positions from the position\n // buffer into the vertexPosition attribute.\n setPositionAttribute(gl, buffers, programInfo);\n\n setTextureAttribute(gl, buffers, programInfo);\n\n // Tell WebGL which indices to use to index the vertices\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);\n\n setNormalAttribute(gl, buffers, programInfo);\n\n // Tell WebGL to use our program when drawing\n gl.useProgram(programInfo.program);\n\n // Set the shader uniforms\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.normalMatrix,\n false,\n normalMatrix\n );\n\n // Tell WebGL we want to affect texture unit 0\n gl.activeTexture(gl.TEXTURE0);\n\n // Bind the texture to texture unit 0\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n // Tell the shader we bound the texture to texture unit 0\n gl.uniform1i(programInfo.uniformLocations.uSampler, 0);\n\n {\n const vertexCount = 36;\n const type = gl.UNSIGNED_SHORT;\n const offset = 0;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n}\n\n// Tell WebGL how to pull out the positions from the position\n// buffer into the vertexPosition attribute.\nfunction setPositionAttribute(gl, buffers, programInfo) {\n const numComponents = 3;\n const type = gl.FLOAT; // the data in the buffer is 32bit floats\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set of values to the next\n // 0 = use type and numComponents above\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);\n}\n\n// Tell WebGL how to pull out the colors from the color buffer\n// into the vertexColor attribute.\nfunction setColorAttribute(gl, buffers, programInfo) {\n const numComponents = 4;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexColor,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);\n}\n\n// tell webgl how to pull out the texture coordinates from buffer\nfunction setTextureAttribute(gl, buffers, programInfo) {\n const num = 2; // every coordinate composed of 2 values\n const type = gl.FLOAT; // the data in the buffer is 32-bit float\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set to the next\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);\n gl.vertexAttribPointer(\n programInfo.attribLocations.textureCoord,\n num,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);\n}\n\n// Tell WebGL how to pull out the normals from\n// the normal buffer into the vertexNormal attribute.\nfunction setNormalAttribute(gl, buffers, programInfo) {\n const numComponents = 3;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexNormal,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexNormal);\n}\n\nexport { drawScene };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076345,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGL Demo\n \n \n \n\n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076346,"cells":{"text":{"kind":"string","value":"import { initBuffers } from \"./init-buffers.js\";\nimport { drawScene } from \"./draw-scene.js\";\n\nlet cubeRotation = 0.0;\nlet deltaTime = 0;\n\nmain();\n\n//\n// start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n // Initialize the GL context\n const gl = canvas.getContext(\"webgl\");\n\n // Only continue if WebGL is available and working\n if (gl === null) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Set clear color to black, fully opaque\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n // Clear the color buffer with specified clear color\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Vertex shader program\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec3 aVertexNormal;\n attribute vec2 aTextureCoord;\n\n uniform mat4 uNormalMatrix;\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying highp vec2 vTextureCoord;\n varying highp vec3 vLighting;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vTextureCoord = aTextureCoord;\n\n // Apply lighting effect\n\n highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);\n highp vec3 directionalLightColor = vec3(1, 1, 1);\n highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));\n\n highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);\n\n highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);\n vLighting = ambientLight + (directionalLightColor * directional);\n }\n`;\n\n // Fragment shader program\n\n const fsSource = `\n varying highp vec2 vTextureCoord;\n varying highp vec3 vLighting;\n\n uniform sampler2D uSampler;\n\n void main(void) {\n highp vec4 texelColor = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);\n }\n`;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attributes our shader program is using\n // for aVertexPosition, aVertexColor and also\n // look up uniform locations.\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, \"aVertexPosition\"),\n vertexNormal: gl.getAttribLocation(shaderProgram, \"aVertexNormal\"),\n textureCoord: gl.getAttribLocation(shaderProgram, \"aTextureCoord\"),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(\n shaderProgram,\n \"uProjectionMatrix\"\n ),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, \"uModelViewMatrix\"),\n normalMatrix: gl.getUniformLocation(shaderProgram, \"uNormalMatrix\"),\n uSampler: gl.getUniformLocation(shaderProgram, \"uSampler\"),\n },\n };\n\n // Here's where we call the routine that builds all the\n // objects we'll be drawing.\n const buffers = initBuffers(gl);\n\n // Load texture\n const texture = loadTexture(gl, \"cubetexture.png\");\n // Flip image pixels into the bottom-to-top order that WebGL expects.\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n\n let then = 0;\n\n // Draw the scene repeatedly\n function render(now) {\n now *= 0.001; // convert to seconds\n deltaTime = now - then;\n then = now;\n\n drawScene(gl, programInfo, buffers, texture, cubeRotation);\n cubeRotation += deltaTime;\n\n requestAnimationFrame(render);\n }\n requestAnimationFrame(render);\n}\n\n//\n// Initialize a shader program, so WebGL knows how to draw our data\n//\nfunction initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\n `Unable to initialize the shader program: ${gl.getProgramInfoLog(\n shaderProgram\n )}`\n );\n return null;\n }\n\n return shaderProgram;\n}\n\n//\n// creates a shader of the given type, uploads the source and\n// compiles it.\n//\nfunction loadShader(gl, type, source) {\n const shader = gl.createShader(type);\n\n // Send the source to the shader object\n\n gl.shaderSource(shader, source);\n\n // Compile the shader program\n\n gl.compileShader(shader);\n\n // See if it compiled successfully\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(\n `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`\n );\n gl.deleteShader(shader);\n return null;\n }\n\n return shader;\n}\n\n//\n// Initialize a texture and load an image.\n// When the image finished loading copy it into the texture.\n//\nfunction loadTexture(gl, url) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n // Because images have to be downloaded over the internet\n // they might take a moment until they are ready.\n // Until then put a single pixel in the texture so we can\n // use it immediately. When the image has finished downloading\n // we'll update the texture with the contents of the image.\n const level = 0;\n const internalFormat = gl.RGBA;\n const width = 1;\n const height = 1;\n const border = 0;\n const srcFormat = gl.RGBA;\n const srcType = gl.UNSIGNED_BYTE;\n const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue\n gl.texImage2D(\n gl.TEXTURE_2D,\n level,\n internalFormat,\n width,\n height,\n border,\n srcFormat,\n srcType,\n pixel\n );\n\n const image = new Image();\n image.onload = () => {\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n level,\n internalFormat,\n srcFormat,\n srcType,\n image\n );\n\n // WebGL1 has different requirements for power of 2 images\n // vs non power of 2 images so check if the image is a\n // power of 2 in both dimensions.\n if (isPowerOf2(image.width) && isPowerOf2(image.height)) {\n // Yes, it's a power of 2. Generate mips.\n gl.generateMipmap(gl.TEXTURE_2D);\n } else {\n // No, it's not a power of 2. Turn off mips and set\n // wrapping to clamp to edge\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n }\n };\n image.src = url;\n\n return texture;\n}\n\nfunction isPowerOf2(value) {\n return (value & (value - 1)) === 0;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076347,"cells":{"text":{"kind":"string","value":"function initBuffers(gl) {\n const positionBuffer = initPositionBuffer(gl);\n\n const textureCoordBuffer = initTextureBuffer(gl);\n\n const indexBuffer = initIndexBuffer(gl);\n\n const normalBuffer = initNormalBuffer(gl);\n\n return {\n position: positionBuffer,\n normal: normalBuffer,\n textureCoord: textureCoordBuffer,\n indices: indexBuffer,\n };\n}\n\nfunction initPositionBuffer(gl) {\n // Create a buffer for the square's positions.\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n const positions = [\n // Front face\n -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,\n\n // Back face\n -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,\n\n // Top face\n -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,\n\n // Bottom face\n -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,\n\n // Right face\n 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,\n\n // Left face\n -1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,\n ];\n\n // Now pass the list of positions into WebGL to build the\n // shape. We do this by creating a Float32Array from the\n // JavaScript array, then use it to fill the current buffer.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n return positionBuffer;\n}\n\nfunction initColorBuffer(gl) {\n const faceColors = [\n [1.0, 1.0, 1.0, 1.0], // Front face: white\n [1.0, 0.0, 0.0, 1.0], // Back face: red\n [0.0, 1.0, 0.0, 1.0], // Top face: green\n [0.0, 0.0, 1.0, 1.0], // Bottom face: blue\n [1.0, 1.0, 0.0, 1.0], // Right face: yellow\n [1.0, 0.0, 1.0, 1.0], // Left face: purple\n ];\n\n // Convert the array of colors into a table for all the vertices.\n\n var colors = [];\n\n for (var j = 0; j < faceColors.length; ++j) {\n const c = faceColors[j];\n // Repeat each color four times for the four vertices of the face\n colors = colors.concat(c, c, c, c);\n }\n\n const colorBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n return colorBuffer;\n}\n\nfunction initIndexBuffer(gl) {\n const indexBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);\n\n // This array defines each face as two triangles, using the\n // indices into the vertex array to specify each triangle's\n // position.\n\n const indices = [\n 0,\n 1,\n 2,\n 0,\n 2,\n 3, // front\n 4,\n 5,\n 6,\n 4,\n 6,\n 7, // back\n 8,\n 9,\n 10,\n 8,\n 10,\n 11, // top\n 12,\n 13,\n 14,\n 12,\n 14,\n 15, // bottom\n 16,\n 17,\n 18,\n 16,\n 18,\n 19, // right\n 20,\n 21,\n 22,\n 20,\n 22,\n 23, // left\n ];\n\n // Now send the element array to GL\n\n gl.bufferData(\n gl.ELEMENT_ARRAY_BUFFER,\n new Uint16Array(indices),\n gl.STATIC_DRAW\n );\n\n return indexBuffer;\n}\n\nfunction initTextureBuffer(gl) {\n const textureCoordBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);\n\n const textureCoordinates = [\n // Front\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Back\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Top\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Bottom\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Right\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n // Left\n 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,\n ];\n\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array(textureCoordinates),\n gl.STATIC_DRAW\n );\n\n return textureCoordBuffer;\n}\n\nfunction initNormalBuffer(gl) {\n const normalBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);\n\n const vertexNormals = [\n // Front\n 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,\n\n // Back\n 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0,\n\n // Top\n 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,\n\n // Bottom\n 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0,\n\n // Right\n 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,\n\n // Left\n -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0,\n ];\n\n gl.bufferData(\n gl.ARRAY_BUFFER,\n new Float32Array(vertexNormals),\n gl.STATIC_DRAW\n );\n\n return normalBuffer;\n}\n\nexport { initBuffers };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076348,"cells":{"text":{"kind":"string","value":"function drawScene(gl, programInfo, buffers, texture, cubeRotation) {\n gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque\n gl.clearDepth(1.0); // Clear everything\n gl.enable(gl.DEPTH_TEST); // Enable depth testing\n gl.depthFunc(gl.LEQUAL); // Near things obscure far things\n\n // Clear the canvas before we start drawing on it.\n\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Create a perspective matrix, a special matrix that is\n // used to simulate the distortion of perspective in a camera.\n // Our field of view is 45 degrees, with a width/height\n // ratio that matches the display size of the canvas\n // and we only want to see objects between 0.1 units\n // and 100 units away from the camera.\n\n const fieldOfView = (45 * Math.PI) / 180; // in radians\n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n // note: glmatrix.js always has the first argument\n // as the destination to receive the result.\n mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);\n\n // Set the drawing position to the \"identity\" point, which is\n // the center of the scene.\n const modelViewMatrix = mat4.create();\n\n // Now move the drawing position a bit to where we want to\n // start drawing the square.\n mat4.translate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to translate\n [-0.0, 0.0, -6.0]\n ); // amount to translate\n\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation, // amount to rotate in radians\n [0, 0, 1]\n ); // axis to rotate around (Z)\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation * 0.7, // amount to rotate in radians\n [0, 1, 0]\n ); // axis to rotate around (Y)\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n cubeRotation * 0.3, // amount to rotate in radians\n [1, 0, 0]\n ); // axis to rotate around (X)\n\n const normalMatrix = mat4.create();\n mat4.invert(normalMatrix, modelViewMatrix);\n mat4.transpose(normalMatrix, normalMatrix);\n\n // Tell WebGL how to pull out the positions from the position\n // buffer into the vertexPosition attribute.\n setPositionAttribute(gl, buffers, programInfo);\n\n setTextureAttribute(gl, buffers, programInfo);\n\n // Tell WebGL which indices to use to index the vertices\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);\n\n setNormalAttribute(gl, buffers, programInfo);\n\n // Tell WebGL to use our program when drawing\n gl.useProgram(programInfo.program);\n\n // Set the shader uniforms\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.normalMatrix,\n false,\n normalMatrix\n );\n\n // Tell WebGL we want to affect texture unit 0\n gl.activeTexture(gl.TEXTURE0);\n\n // Bind the texture to texture unit 0\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n // Tell the shader we bound the texture to texture unit 0\n gl.uniform1i(programInfo.uniformLocations.uSampler, 0);\n\n {\n const vertexCount = 36;\n const type = gl.UNSIGNED_SHORT;\n const offset = 0;\n gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);\n }\n}\n\n// Tell WebGL how to pull out the positions from the position\n// buffer into the vertexPosition attribute.\nfunction setPositionAttribute(gl, buffers, programInfo) {\n const numComponents = 3;\n const type = gl.FLOAT; // the data in the buffer is 32bit floats\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set of values to the next\n // 0 = use type and numComponents above\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);\n}\n\n// Tell WebGL how to pull out the colors from the color buffer\n// into the vertexColor attribute.\nfunction setColorAttribute(gl, buffers, programInfo) {\n const numComponents = 4;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexColor,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);\n}\n\n// tell webgl how to pull out the texture coordinates from buffer\nfunction setTextureAttribute(gl, buffers, programInfo) {\n const num = 2; // every coordinate composed of 2 values\n const type = gl.FLOAT; // the data in the buffer is 32-bit float\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set to the next\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);\n gl.vertexAttribPointer(\n programInfo.attribLocations.textureCoord,\n num,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);\n}\n\n// Tell WebGL how to pull out the normals from\n// the normal buffer into the vertexNormal attribute.\nfunction setNormalAttribute(gl, buffers, programInfo) {\n const numComponents = 3;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexNormal,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexNormal);\n}\n\nexport { drawScene };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076349,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGL Demo\n \n \n \n\n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076350,"cells":{"text":{"kind":"string","value":"import { initBuffers } from \"./init-buffers.js\";\nimport { drawScene } from \"./draw-scene.js\";\n\nlet cubeRotation = 0.0;\nlet deltaTime = 0;\n// will set to true when video can be copied to texture\nlet copyVideo = false;\n\nmain();\n\n//\n// start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n // Initialize the GL context\n const gl = canvas.getContext(\"webgl\");\n\n // Only continue if WebGL is available and working\n if (gl === null) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Set clear color to black, fully opaque\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n // Clear the color buffer with specified clear color\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Vertex shader program\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec3 aVertexNormal;\n attribute vec2 aTextureCoord;\n\n uniform mat4 uNormalMatrix;\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying highp vec2 vTextureCoord;\n varying highp vec3 vLighting;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vTextureCoord = aTextureCoord;\n\n // Apply lighting effect\n\n highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);\n highp vec3 directionalLightColor = vec3(1, 1, 1);\n highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));\n\n highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);\n\n highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);\n vLighting = ambientLight + (directionalLightColor * directional);\n }\n`;\n\n // Fragment shader program\n\n const fsSource = `\n varying highp vec2 vTextureCoord;\n varying highp vec3 vLighting;\n\n uniform sampler2D uSampler;\n\n void main(void) {\n highp vec4 texelColor = texture2D(uSampler, vTextureCoord);\n\n gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);\n }\n`;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attributes our shader program is using\n // for aVertexPosition, aVertexColor and also\n // look up uniform locations.\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, \"aVertexPosition\"),\n vertexNormal: gl.getAttribLocation(shaderProgram, \"aVertexNormal\"),\n textureCoord: gl.getAttribLocation(shaderProgram, \"aTextureCoord\"),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(\n shaderProgram,\n \"uProjectionMatrix\"\n ),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, \"uModelViewMatrix\"),\n normalMatrix: gl.getUniformLocation(shaderProgram, \"uNormalMatrix\"),\n uSampler: gl.getUniformLocation(shaderProgram, \"uSampler\"),\n },\n };\n\n // Here's where we call the routine that builds all the\n // objects we'll be drawing.\n const buffers = initBuffers(gl);\n\n const texture = initTexture(gl);\n const video = setupVideo(\"Firefox.mp4\");\n\n // Flip image pixels into the bottom-to-top order that WebGL expects.\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);\n\n let then = 0;\n\n // Draw the scene repeatedly\n function render(now) {\n now *= 0.001; // convert to seconds\n deltaTime = now - then;\n then = now;\n\n if (copyVideo) {\n updateTexture(gl, texture, video);\n }\n\n drawScene(gl, programInfo, buffers, texture, cubeRotation);\n cubeRotation += deltaTime;\n\n requestAnimationFrame(render);\n }\n\n requestAnimationFrame(render);\n}\n\n//\n// Initialize a shader program, so WebGL knows how to draw our data\n//\nfunction initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\n `Unable to initialize the shader program: ${gl.getProgramInfoLog(\n shaderProgram\n )}`\n );\n return null;\n }\n\n return shaderProgram;\n}\n\n//\n// creates a shader of the given type, uploads the source and\n// compiles it.\n//\nfunction loadShader(gl, type, source) {\n const shader = gl.createShader(type);\n\n // Send the source to the shader object\n\n gl.shaderSource(shader, source);\n\n // Compile the shader program\n\n gl.compileShader(shader);\n\n // See if it compiled successfully\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(\n `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`\n );\n gl.deleteShader(shader);\n return null;\n }\n\n return shader;\n}\n\nfunction initTexture(gl) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n // Because video has to be download over the internet\n // they might take a moment until it's ready so\n // put a single pixel in the texture so we can\n // use it immediately.\n const level = 0;\n const internalFormat = gl.RGBA;\n const width = 1;\n const height = 1;\n const border = 0;\n const srcFormat = gl.RGBA;\n const srcType = gl.UNSIGNED_BYTE;\n const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue\n gl.texImage2D(\n gl.TEXTURE_2D,\n level,\n internalFormat,\n width,\n height,\n border,\n srcFormat,\n srcType,\n pixel\n );\n\n // Turn off mips and set wrapping to clamp to edge so it\n // will work regardless of the dimensions of the video.\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n\n return texture;\n}\n\nfunction updateTexture(gl, texture, video) {\n const level = 0;\n const internalFormat = gl.RGBA;\n const srcFormat = gl.RGBA;\n const srcType = gl.UNSIGNED_BYTE;\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texImage2D(\n gl.TEXTURE_2D,\n level,\n internalFormat,\n srcFormat,\n srcType,\n video\n );\n}\n\nfunction setupVideo(url) {\n const video = document.createElement(\"video\");\n\n let playing = false;\n let timeupdate = false;\n\n video.playsInline = true;\n video.muted = true;\n video.loop = true;\n\n // Waiting for these 2 events ensures\n // there is data in the video\n\n video.addEventListener(\n \"playing\",\n () => {\n playing = true;\n checkReady();\n },\n true\n );\n\n video.addEventListener(\n \"timeupdate\",\n () => {\n timeupdate = true;\n checkReady();\n },\n true\n );\n\n video.src = url;\n video.play();\n\n function checkReady() {\n if (playing && timeupdate) {\n copyVideo = true;\n }\n }\n\n return video;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076351,"cells":{"text":{"kind":"string","value":"function initBuffers(gl) {\n const positionBuffer = initPositionBuffer(gl);\n\n const colorBuffer = initColorBuffer(gl);\n\n return {\n position: positionBuffer,\n color: colorBuffer,\n };\n}\n\nfunction initPositionBuffer(gl) {\n // Create a buffer for the square's positions.\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n // Now create an array of positions for the square.\n const positions = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0];\n\n // Now pass the list of positions into WebGL to build the\n // shape. We do this by creating a Float32Array from the\n // JavaScript array, then use it to fill the current buffer.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n return positionBuffer;\n}\n\nfunction initColorBuffer(gl) {\n const colors = [\n 1.0,\n 1.0,\n 1.0,\n 1.0, // white\n 1.0,\n 0.0,\n 0.0,\n 1.0, // red\n 0.0,\n 1.0,\n 0.0,\n 1.0, // green\n 0.0,\n 0.0,\n 1.0,\n 1.0, // blue\n ];\n\n const colorBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n return colorBuffer;\n}\n\nexport { initBuffers };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076352,"cells":{"text":{"kind":"string","value":"function drawScene(gl, programInfo, buffers) {\n gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque\n gl.clearDepth(1.0); // Clear everything\n gl.enable(gl.DEPTH_TEST); // Enable depth testing\n gl.depthFunc(gl.LEQUAL); // Near things obscure far things\n\n // Clear the canvas before we start drawing on it.\n\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Create a perspective matrix, a special matrix that is\n // used to simulate the distortion of perspective in a camera.\n // Our field of view is 45 degrees, with a width/height\n // ratio that matches the display size of the canvas\n // and we only want to see objects between 0.1 units\n // and 100 units away from the camera.\n\n const fieldOfView = (45 * Math.PI) / 180; // in radians\n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n // note: glmatrix.js always has the first argument\n // as the destination to receive the result.\n mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);\n\n // Set the drawing position to the \"identity\" point, which is\n // the center of the scene.\n const modelViewMatrix = mat4.create();\n\n // Now move the drawing position a bit to where we want to\n // start drawing the square.\n mat4.translate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to translate\n [-0.0, 0.0, -6.0]\n ); // amount to translate\n\n // Tell WebGL how to pull out the positions from the position\n // buffer into the vertexPosition attribute.\n setPositionAttribute(gl, buffers, programInfo);\n\n setColorAttribute(gl, buffers, programInfo);\n\n // Tell WebGL to use our program when drawing\n gl.useProgram(programInfo.program);\n\n // Set the shader uniforms\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix\n );\n\n {\n const offset = 0;\n const vertexCount = 4;\n gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);\n }\n}\n\n// Tell WebGL how to pull out the positions from the position\n// buffer into the vertexPosition attribute.\nfunction setPositionAttribute(gl, buffers, programInfo) {\n const numComponents = 2; // pull out 2 values per iteration\n const type = gl.FLOAT; // the data in the buffer is 32bit floats\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set of values to the next\n // 0 = use type and numComponents above\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);\n}\n\n// Tell WebGL how to pull out the colors from the color buffer\n// into the vertexColor attribute.\nfunction setColorAttribute(gl, buffers, programInfo) {\n const numComponents = 4;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexColor,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);\n}\n\nexport { drawScene };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076353,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGL Demo\n \n \n \n\n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076354,"cells":{"text":{"kind":"string","value":"import { initBuffers } from \"./init-buffers.js\";\nimport { drawScene } from \"./draw-scene.js\";\n\nmain();\n\n//\n// start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n // Initialize the GL context\n const gl = canvas.getContext(\"webgl\");\n\n // Only continue if WebGL is available and working\n if (gl === null) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Set clear color to black, fully opaque\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n // Clear the color buffer with specified clear color\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Vertex shader program\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec4 aVertexColor;\n\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying lowp vec4 vColor;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vColor = aVertexColor;\n }\n `;\n\n // Fragment shader program\n\n const fsSource = `\n varying lowp vec4 vColor;\n\n void main(void) {\n gl_FragColor = vColor;\n }\n `;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attributes our shader program is using\n // for aVertexPosition, aVertexColor and also\n // look up uniform locations.\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, \"aVertexPosition\"),\n vertexColor: gl.getAttribLocation(shaderProgram, \"aVertexColor\"),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(\n shaderProgram,\n \"uProjectionMatrix\"\n ),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, \"uModelViewMatrix\"),\n },\n };\n\n // Here's where we call the routine that builds all the\n // objects we'll be drawing.\n const buffers = initBuffers(gl);\n\n // Draw the scene\n drawScene(gl, programInfo, buffers);\n}\n\n//\n// Initialize a shader program, so WebGL knows how to draw our data\n//\nfunction initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\n `Unable to initialize the shader program: ${gl.getProgramInfoLog(\n shaderProgram\n )}`\n );\n return null;\n }\n\n return shaderProgram;\n}\n\n//\n// creates a shader of the given type, uploads the source and\n// compiles it.\n//\nfunction loadShader(gl, type, source) {\n const shader = gl.createShader(type);\n\n // Send the source to the shader object\n\n gl.shaderSource(shader, source);\n\n // Compile the shader program\n\n gl.compileShader(shader);\n\n // See if it compiled successfully\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(\n `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`\n );\n gl.deleteShader(shader);\n return null;\n }\n\n return shader;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076355,"cells":{"text":{"kind":"string","value":"function initBuffers(gl) {\n const positionBuffer = initPositionBuffer(gl);\n\n const colorBuffer = initColorBuffer(gl);\n\n return {\n position: positionBuffer,\n color: colorBuffer,\n };\n}\n\nfunction initPositionBuffer(gl) {\n // Create a buffer for the square's positions.\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n // Now create an array of positions for the square.\n const positions = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0];\n\n // Now pass the list of positions into WebGL to build the\n // shape. We do this by creating a Float32Array from the\n // JavaScript array, then use it to fill the current buffer.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n return positionBuffer;\n}\n\nfunction initColorBuffer(gl) {\n const colors = [\n 1.0,\n 1.0,\n 1.0,\n 1.0, // white\n 1.0,\n 0.0,\n 0.0,\n 1.0, // red\n 0.0,\n 1.0,\n 0.0,\n 1.0, // green\n 0.0,\n 0.0,\n 1.0,\n 1.0, // blue\n ];\n\n const colorBuffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n return colorBuffer;\n}\n\nexport { initBuffers };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076356,"cells":{"text":{"kind":"string","value":"function drawScene(gl, programInfo, buffers, squareRotation) {\n gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque\n gl.clearDepth(1.0); // Clear everything\n gl.enable(gl.DEPTH_TEST); // Enable depth testing\n gl.depthFunc(gl.LEQUAL); // Near things obscure far things\n\n // Clear the canvas before we start drawing on it.\n\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Create a perspective matrix, a special matrix that is\n // used to simulate the distortion of perspective in a camera.\n // Our field of view is 45 degrees, with a width/height\n // ratio that matches the display size of the canvas\n // and we only want to see objects between 0.1 units\n // and 100 units away from the camera.\n\n const fieldOfView = (45 * Math.PI) / 180; // in radians\n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n // note: glmatrix.js always has the first argument\n // as the destination to receive the result.\n mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);\n\n // Set the drawing position to the \"identity\" point, which is\n // the center of the scene.\n const modelViewMatrix = mat4.create();\n\n // Now move the drawing position a bit to where we want to\n // start drawing the square.\n mat4.translate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to translate\n [-0.0, 0.0, -6.0]\n ); // amount to translate\n\n mat4.rotate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to rotate\n squareRotation, // amount to rotate in radians\n [0, 0, 1]\n ); // axis to rotate around\n\n // Tell WebGL how to pull out the positions from the position\n // buffer into the vertexPosition attribute.\n setPositionAttribute(gl, buffers, programInfo);\n\n setColorAttribute(gl, buffers, programInfo);\n\n // Tell WebGL to use our program when drawing\n gl.useProgram(programInfo.program);\n\n // Set the shader uniforms\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix\n );\n\n {\n const offset = 0;\n const vertexCount = 4;\n gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);\n }\n}\n\n// Tell WebGL how to pull out the positions from the position\n// buffer into the vertexPosition attribute.\nfunction setPositionAttribute(gl, buffers, programInfo) {\n const numComponents = 2; // pull out 2 values per iteration\n const type = gl.FLOAT; // the data in the buffer is 32bit floats\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set of values to the next\n // 0 = use type and numComponents above\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);\n}\n\n// Tell WebGL how to pull out the colors from the color buffer\n// into the vertexColor attribute.\nfunction setColorAttribute(gl, buffers, programInfo) {\n const numComponents = 4;\n const type = gl.FLOAT;\n const normalize = false;\n const stride = 0;\n const offset = 0;\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexColor,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);\n}\n\nexport { drawScene };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076357,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGL Demo\n \n \n \n\n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076358,"cells":{"text":{"kind":"string","value":"import { initBuffers } from \"./init-buffers.js\";\nimport { drawScene } from \"./draw-scene.js\";\n\nlet squareRotation = 0.0;\nlet deltaTime = 0;\n\nmain();\n\n//\n// start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n // Initialize the GL context\n const gl = canvas.getContext(\"webgl\");\n\n // Only continue if WebGL is available and working\n if (gl === null) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Set clear color to black, fully opaque\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n // Clear the color buffer with specified clear color\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Vertex shader program\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec4 aVertexColor;\n\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying lowp vec4 vColor;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vColor = aVertexColor;\n }\n `;\n\n // Fragment shader program\n\n const fsSource = `\n varying lowp vec4 vColor;\n\n void main(void) {\n gl_FragColor = vColor;\n }\n `;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attributes our shader program is using\n // for aVertexPosition, aVertexColor and also\n // look up uniform locations.\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, \"aVertexPosition\"),\n vertexColor: gl.getAttribLocation(shaderProgram, \"aVertexColor\"),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(\n shaderProgram,\n \"uProjectionMatrix\"\n ),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, \"uModelViewMatrix\"),\n },\n };\n\n // Here's where we call the routine that builds all the\n // objects we'll be drawing.\n const buffers = initBuffers(gl);\n\n let then = 0;\n\n // Draw the scene repeatedly\n function render(now) {\n now *= 0.001; // convert to seconds\n deltaTime = now - then;\n then = now;\n\n drawScene(gl, programInfo, buffers, squareRotation);\n squareRotation += deltaTime;\n\n requestAnimationFrame(render);\n }\n requestAnimationFrame(render);\n}\n\n//\n// Initialize a shader program, so WebGL knows how to draw our data\n//\nfunction initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\n `Unable to initialize the shader program: ${gl.getProgramInfoLog(\n shaderProgram\n )}`\n );\n return null;\n }\n\n return shaderProgram;\n}\n\n//\n// creates a shader of the given type, uploads the source and\n// compiles it.\n//\nfunction loadShader(gl, type, source) {\n const shader = gl.createShader(type);\n\n // Send the source to the shader object\n\n gl.shaderSource(shader, source);\n\n // Compile the shader program\n\n gl.compileShader(shader);\n\n // See if it compiled successfully\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(\n `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`\n );\n gl.deleteShader(shader);\n return null;\n }\n\n return shader;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076359,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGL Demo\n \n \n\n \n \n \n\n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076360,"cells":{"text":{"kind":"string","value":"var tetrahedronRotation = 0.0;\n\nmain();\n\n//\n// Start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n const gl =\n canvas.getContext(\"webgl\") || canvas.getContext(\"experimental-webgl\");\n\n // If we don't have a GL context, give up now\n\n if (!gl) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Vertex shader program\n\n const vsSource = `\n attribute vec4 aVertexPosition;\n attribute vec4 aVertexColor;\n\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n\n varying lowp vec4 vColor;\n\n void main(void) {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n vColor = aVertexColor;\n }\n `;\n\n // Fragment shader program\n\n const fsSource = `\n varying lowp vec4 vColor;\n\n void main(void) {\n gl_FragColor = vColor;\n }\n `;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attributes our shader program is using\n // for aVertexPosition, aVevrtexColor and also\n // look up uniform locations.\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, \"aVertexPosition\"),\n vertexColor: gl.getAttribLocation(shaderProgram, \"aVertexColor\"),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(\n shaderProgram,\n \"uProjectionMatrix\"\n ),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, \"uModelViewMatrix\"),\n },\n };\n\n // Here's where we call the routine that builds all the\n // objects we'll be drawing.\n const buffers = initBuffers(gl);\n\n var then = 0;\n\n // Draw the scene repeatedly\n function render(now) {\n now *= 0.001; // convert to seconds\n const deltaTime = now - then;\n then = now;\n\n drawScene(gl, programInfo, buffers, deltaTime);\n\n requestAnimationFrame(render);\n }\n\n requestAnimationFrame(render);\n}\n\n//\n// initBuffers\n//\n// Initialize the buffers we'll need. For this demo, we just\n// have one object -- a simple three-dimensional tetrahedron.\n//\nfunction initBuffers(gl) {\n // Create a buffer for the tetrahedron's vertex positions.\n\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n // Now create an array of positions for the tetrahedron.\n // A equilateral triangle is needed ( well 4 of them )\n // Point `O` is where the height is projected\n // The tetrahedron is rotated around point `M`\n // Height from vertex `A` to the edge `BC` is `H`\n // The edge of the tetrahedron is 2 units long\n // |AH| = 1.7320508075688772935274463415059\n // The median and a height AH divides itself by\n // the other medians into 1x and 2x ( one part and two parts )\n // |AH|/3 = 0.57735026918962576450914878050197\n // Find the tetrahedron height by argument sine (\n\n \n \n WebGL Demo\n \n \n\n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076362,"cells":{"text":{"kind":"string","value":"main();\n\n//\n// start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n // Initialize the GL context\n const gl = canvas.getContext(\"webgl\");\n\n // Only continue if WebGL is available and working\n if (gl === null) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Set clear color to black, fully opaque\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n // Clear the color buffer with specified clear color\n gl.clear(gl.COLOR_BUFFER_BIT);\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076363,"cells":{"text":{"kind":"string","value":"function initBuffers(gl) {\n const positionBuffer = initPositionBuffer(gl);\n\n return {\n position: positionBuffer,\n };\n}\n\nfunction initPositionBuffer(gl) {\n // Create a buffer for the square's positions.\n const positionBuffer = gl.createBuffer();\n\n // Select the positionBuffer as the one to apply buffer\n // operations to from here out.\n gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);\n\n // Now create an array of positions for the square.\n const positions = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0];\n\n // Now pass the list of positions into WebGL to build the\n // shape. We do this by creating a Float32Array from the\n // JavaScript array, then use it to fill the current buffer.\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);\n\n return positionBuffer;\n}\n\nexport { initBuffers };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076364,"cells":{"text":{"kind":"string","value":"function drawScene(gl, programInfo, buffers) {\n gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque\n gl.clearDepth(1.0); // Clear everything\n gl.enable(gl.DEPTH_TEST); // Enable depth testing\n gl.depthFunc(gl.LEQUAL); // Near things obscure far things\n\n // Clear the canvas before we start drawing on it.\n\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Create a perspective matrix, a special matrix that is\n // used to simulate the distortion of perspective in a camera.\n // Our field of view is 45 degrees, with a width/height\n // ratio that matches the display size of the canvas\n // and we only want to see objects between 0.1 units\n // and 100 units away from the camera.\n\n const fieldOfView = (45 * Math.PI) / 180; // in radians\n const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;\n const zNear = 0.1;\n const zFar = 100.0;\n const projectionMatrix = mat4.create();\n\n // note: glmatrix.js always has the first argument\n // as the destination to receive the result.\n mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);\n\n // Set the drawing position to the \"identity\" point, which is\n // the center of the scene.\n const modelViewMatrix = mat4.create();\n\n // Now move the drawing position a bit to where we want to\n // start drawing the square.\n mat4.translate(\n modelViewMatrix, // destination matrix\n modelViewMatrix, // matrix to translate\n [-0.0, 0.0, -6.0]\n ); // amount to translate\n\n // Tell WebGL how to pull out the positions from the position\n // buffer into the vertexPosition attribute.\n setPositionAttribute(gl, buffers, programInfo);\n\n // Tell WebGL to use our program when drawing\n gl.useProgram(programInfo.program);\n\n // Set the shader uniforms\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.projectionMatrix,\n false,\n projectionMatrix\n );\n gl.uniformMatrix4fv(\n programInfo.uniformLocations.modelViewMatrix,\n false,\n modelViewMatrix\n );\n\n {\n const offset = 0;\n const vertexCount = 4;\n gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);\n }\n}\n\n// Tell WebGL how to pull out the positions from the position\n// buffer into the vertexPosition attribute.\nfunction setPositionAttribute(gl, buffers, programInfo) {\n const numComponents = 2; // pull out 2 values per iteration\n const type = gl.FLOAT; // the data in the buffer is 32bit floats\n const normalize = false; // don't normalize\n const stride = 0; // how many bytes to get from one set of values to the next\n // 0 = use type and numComponents above\n const offset = 0; // how many bytes inside the buffer to start from\n gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);\n gl.vertexAttribPointer(\n programInfo.attribLocations.vertexPosition,\n numComponents,\n type,\n normalize,\n stride,\n offset\n );\n gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);\n}\n\nexport { drawScene };\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076365,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGL Demo\n \n \n \n\n \n \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076366,"cells":{"text":{"kind":"string","value":"import { initBuffers } from \"./init-buffers.js\";\nimport { drawScene } from \"./draw-scene.js\";\n\nmain();\n\n//\n// start here\n//\nfunction main() {\n const canvas = document.querySelector(\"#glcanvas\");\n // Initialize the GL context\n const gl = canvas.getContext(\"webgl\");\n\n // Only continue if WebGL is available and working\n if (gl === null) {\n alert(\n \"Unable to initialize WebGL. Your browser or machine may not support it.\"\n );\n return;\n }\n\n // Set clear color to black, fully opaque\n gl.clearColor(0.0, 0.0, 0.0, 1.0);\n // Clear the color buffer with specified clear color\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Vertex shader program\n const vsSource = `\n attribute vec4 aVertexPosition;\n uniform mat4 uModelViewMatrix;\n uniform mat4 uProjectionMatrix;\n void main() {\n gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;\n }\n`;\n\n const fsSource = `\n void main() {\n gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\n }\n `;\n\n // Initialize a shader program; this is where all the lighting\n // for the vertices and so forth is established.\n const shaderProgram = initShaderProgram(gl, vsSource, fsSource);\n\n // Collect all the info needed to use the shader program.\n // Look up which attribute our shader program is using\n // for aVertexPosition and look up uniform locations.\n const programInfo = {\n program: shaderProgram,\n attribLocations: {\n vertexPosition: gl.getAttribLocation(shaderProgram, \"aVertexPosition\"),\n },\n uniformLocations: {\n projectionMatrix: gl.getUniformLocation(\n shaderProgram,\n \"uProjectionMatrix\"\n ),\n modelViewMatrix: gl.getUniformLocation(shaderProgram, \"uModelViewMatrix\"),\n },\n };\n\n // Here's where we call the routine that builds all the\n // objects we'll be drawing.\n const buffers = initBuffers(gl);\n\n // Draw the scene\n drawScene(gl, programInfo, buffers);\n}\n\n//\n// Initialize a shader program, so WebGL knows how to draw our data\n//\nfunction initShaderProgram(gl, vsSource, fsSource) {\n const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);\n const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);\n\n // Create the shader program\n\n const shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertexShader);\n gl.attachShader(shaderProgram, fragmentShader);\n gl.linkProgram(shaderProgram);\n\n // If creating the shader program failed, alert\n\n if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {\n alert(\n `Unable to initialize the shader program: ${gl.getProgramInfoLog(\n shaderProgram\n )}`\n );\n return null;\n }\n\n return shaderProgram;\n}\n\n//\n// creates a shader of the given type, uploads the source and\n// compiles it.\n//\nfunction loadShader(gl, type, source) {\n const shader = gl.createShader(type);\n\n // Send the source to the shader object\n\n gl.shaderSource(shader, source);\n\n // Compile the shader program\n\n gl.compileShader(shader);\n\n // See if it compiled successfully\n\n if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {\n alert(\n `An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`\n );\n gl.deleteShader(shader);\n return null;\n }\n\n return shader;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076367,"cells":{"text":{"kind":"string","value":"\n\n\n\nPointer Events pinch/zoom example\n\n\n\n\n\n\n

Pointer Event pinch/zoom gesture

\n \n
Touch and Hold with 2 pointers, then pinch in or out.
\n The background color will change to pink if the pinch is opening (Zoom In) \n or changes to lightblue if the pinch is closing (Zoom out).
\n \n \n \n

\n \n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076368,"cells":{"text":{"kind":"string","value":"\n\n\n\n\n\n\n\n Your browser does not support canvas element.\n\n
\n\n
\nLog: \n
\n\n\n\n\n"},"meta":{"kind":"string","value":"{\n  \"repo_name\": \"mdn/dom-examples\",\n  \"stars\": \"2648\",\n  \"repo_language\": \"JavaScript\",\n  \"file_name\": \"style.css\",\n  \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076369,"cells":{"text":{"kind":"string","value":"\n\n\n\nPointer Events multi-touch interaction\n\n\n\n\n\n\n

Multi-touch interaction

\n \n
Tap, Hold or Swipe me 1
\n
Tap, Hold or Swipe me 2
\n
Tap, Hold or Swipe me 3
\n\n \n \n \n

\n \n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076370,"cells":{"text":{"kind":"string","value":"Examples:\n\n* [Drawing program](https://mdn.github.com/dom-examples/pointerevents/Using_Pointer_Events.html). This application is a Pointer Events version of the [Touch Events drawing program](https://developer.mozilla.org/en-US/docs/Web/API/Touch_events/Using_Touch_Events). The application is described in [Using Pointer Events](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events/Using_Pointer_Events).\n* [Multi-touch interaction demo](http://mdn.github.io/dom-examples/pointerevents/Multi-touch_interaction.html). This interactive demo shows how to use Pointer Events for mulit-touch interaction. The application is described in [Multi-touch interaction](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events/Multi-touch_interaction).\n* [Two-pointer Pinch/Zoom Demo](http://mdn.github.io/dom-examples/pointerevents/Pinch_zoom_gestures.html). This interactive demo shows how to recognize a simple two-pointer pinch/zoom gesture. The application is described in [Pinch zoom gestures](https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events/Pinch_zoom_gestures).\n\nExternal Pointer Events Demos:\n\n* [Patrick H Lauke's site](http://patrickhlauke.github.io/touch/)\n* [Pointer Events demo](http://limpet.net/pointer.html) described in Mozilla Hacks article [Pointer Events now in Firefox Nightly](https://hacks.mozilla.org/2015/08/pointer-events-now-in-firefox-nightly/) by Matt Brubeck and Jason Weathersby\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076371,"cells":{"text":{"kind":"string","value":"\n\n\n\n \n auxclick demo\n \n\n\n\n\n \n\n\n \n\n\n\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076372,"cells":{"text":{"kind":"string","value":"# auxclick demo\n\nThe onauxclick property is an event handler called when an auxclick event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button).\n\nThis property is implemented as part of a plan to improve compatibility between browsers with regards to button behaviours — event behaviour is being updated so that click only fires for primary button clicks (e.g. left mouse button). Developers can then use auxclick to provide explicit behaviour for non-primary button clicks.\n\nPrevious to this, click generally fired for clicks on all input device buttons, and browser behaviour was somewhat inconsistent.\n\n[See the demo live](https://mdn.github.io/dom-examples/auxclick/).\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076373,"cells":{"text":{"kind":"string","value":"\n\n\n \n Server-sent events demo\n\n\n \n\n
    \n
\n\n\n\n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076374,"cells":{"text":{"kind":"string","value":" 0) {\n ob_end_flush();\n }\n flush();\n\n // break the loop if the client aborted the connection (closed the page)\n \n if ( connection_aborted() ) break;\n\n // sleep for 1 second before running the loop again\n \n sleep(1);\n\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076375,"cells":{"text":{"kind":"string","value":"## Note about running this example through **NGINX**:\n\nBy default `fastcgi_buffering` is ON, thus you have to add `fastcgi_buffering off;` to the appropriate `location` block for this example to work.\n\nSimilarly, if you use a reverse proxy, `proxy_buffering` is ON by default, thus you have to add `proxy_buffering off;`.\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076376,"cells":{"text":{"kind":"string","value":"\n\n \n Picture-in-Picture Example\n \n \n \n \n
\n

A quick example for the use of the Picture-in-Picture API

\n\n\t\t\t\n\n
\n\n
\n\t\t\t\t

\n\t\t\t\t\tPicture-in-Picture mode not available\n\t\t\t\t

\n

\n\n\t\t\t

\n\t\t\t\tEvents\n\t\t\t

\n
    \n
    \n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076377,"cells":{"text":{"kind":"string","value":"#contents {\n\twidth: 600px;\n\tfont: 14px \"Open Sans\", sans-serif;\n}\n\n#credits {\n\tpadding: 0 0 10px 0;\n\tfont: italic 10px \"Open Sans\", sans-serif;\n}\n\n:picture-in-picture {\n\tbox-shadow: 0 0 0 5px red;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076378,"cells":{"text":{"kind":"string","value":"\nwindow.addEventListener(\"load\", startup, false);\nlet video;\nlet logs;\n\nfunction startup() {\n\tvideo = document.getElementById(\"video\");\n\tlogs = document.getElementById(\"logs\");\n\n\tif (document.pictureInPictureEnabled) {\n\n\t\tdocument\n\t\t\t.querySelector(\".no-picture-in-picture\")\n\t\t\t.remove();\n\n\t\tconst togglePipButton = document.createElement(\"button\");\n\t\ttogglePipButton.textContent = \"Toggle Picture-in-Picture\";\n\t\ttogglePipButton.addEventListener(\"click\", togglePictureInPicture, false);\n\n\t\tdocument\n\t\t\t.getElementById(\"controlbar\")\n\t\t\t.appendChild(togglePipButton);\n\t}\n}\n\nfunction togglePictureInPicture() {\n\tif (document.pictureInPictureElement) {\n\t\tdocument.exitPictureInPicture();\n\t} else {\n\t\tif (document.pictureInPictureEnabled) {\n\t\t\tvideo.requestPictureInPicture()\n\t\t\t\t.then(pictureInPictureWindow => {\n\t\t\t\t\tpictureInPictureWindow.addEventListener(\"resize\", onPictureInPictureResize, false);\n\t\t\t\t});\n\t\t}\n\t}\n}\n\nfunction onPictureInPictureResize() {\n\tconst listItem = document.createElement(\"li\");\n\tlistItem.textContent = `resize - ${Date.now()}`;\n\n\tlogs.appendChild(listItem);\n\tsetTimeout(() => logs.removeChild(listItem), 2000);\n};\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076379,"cells":{"text":{"kind":"string","value":"# Picture-in-Picture example\n\nThis example will progressively enhance a video by adding a toggle picture-in-picture mode button if that feature is enabled.\n\nIt also highlights how to set up a resize event on the &lt;PictureInPictureWindow&gt;\n\n[See the example live](https://mdn.github.io/dom-examples/picture-in-picture/).\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076380,"cells":{"text":{"kind":"string","value":"\n\n \n \n WebGPU data\n \n \n \n

    WebGPU data

    \n \n \n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076381,"cells":{"text":{"kind":"string","value":"// Define global buffer size\nconst BUFFER_SIZE = 1000; \n\n// Compute shader\nconst shader = `\n@group(0) @binding(0)\nvar output: array;\n\n@compute @workgroup_size(64)\nfn main(\n @builtin(global_invocation_id)\n global_id : vec3u,\n\n @builtin(local_invocation_id)\n local_id : vec3u,\n) {\n // Avoid accessing the buffer out of bounds\n if (global_id.x >= ${BUFFER_SIZE}u) {\n return;\n }\n\n output[global_id.x] =\n f32(global_id.x) * 1000. + f32(local_id.x);\n}\n`;\n\n// Main function\n\nasync function init() {\n // 1: request adapter and device\n if (!navigator.gpu) {\n throw Error('WebGPU not supported.');\n }\n\n const adapter = await navigator.gpu.requestAdapter();\n if (!adapter) {\n throw Error('Couldn\\'t request WebGPU adapter.');\n }\n\n const device = await adapter.requestDevice();\n\n // 2: Create a shader module from the shader template literal\n const shaderModule = device.createShaderModule({\n code: shader\n });\n\n // 3: Create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access\n\n const output = device.createBuffer({\n size: BUFFER_SIZE,\n usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC\n });\n\n const stagingBuffer = device.createBuffer({\n size: BUFFER_SIZE,\n usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST\n });\n\n // 4: Create a GPUBindGroupLayout to define the bind group structure, create a GPUBindGroup from it,\n // then use it to create a GPUComputePipeline\n\n const bindGroupLayout =\n device.createBindGroupLayout({\n entries: [{\n binding: 0,\n visibility: GPUShaderStage.COMPUTE,\n buffer: {\n type: \"storage\"\n }\n }]\n });\n\n const bindGroup = device.createBindGroup({\n layout: bindGroupLayout,\n entries: [{\n binding: 0,\n resource: {\n buffer: output,\n }\n }]\n });\n\n const computePipeline = device.createComputePipeline({\n layout: device.createPipelineLayout({\n bindGroupLayouts: [bindGroupLayout]\n }),\n compute: {\n module: shaderModule,\n entryPoint: 'main'\n }\n });\n\n // 5: Create GPUCommandEncoder to issue commands to the GPU\n const commandEncoder = device.createCommandEncoder();\n\n // 6: Initiate render pass\n const passEncoder = commandEncoder.beginComputePass();\n \n // 7: Issue commands\n passEncoder.setPipeline(computePipeline);\n passEncoder.setBindGroup(0, bindGroup);\n passEncoder.dispatchWorkgroups(Math.ceil(BUFFER_SIZE / 64));\n\n // End the render pass\n passEncoder.end();\n\n // Copy output buffer to staging buffer\n commandEncoder.copyBufferToBuffer(\n output,\n 0, // Source offset\n stagingBuffer,\n 0, // Destination offset\n BUFFER_SIZE\n );\n\n // 8: End frame by passing array of command buffers to command queue for execution\n device.queue.submit([commandEncoder.finish()]);\n\n // map staging buffer to read results back to JS\n await stagingBuffer.mapAsync(\n GPUMapMode.READ,\n 0, // Offset\n BUFFER_SIZE // Length\n );\n\n const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER_SIZE);\n const data = copyArrayBuffer.slice();\n stagingBuffer.unmap();\n console.log(new Float32Array(data));\n}\n\ninit();\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076382,"cells":{"text":{"kind":"string","value":"\n\n\n \n Pre-authorize Transaction\n \n \n \n\n\n\n

    Pre-authorize Transaction

    \n\n
    \n

    \n Some use cases (e.g., paying for fuel at a service station) involve \n pre-authorization of payment. One way to do this is through a Payment Handler \n (see the Payment Handler API). \n Currently that specification includes a CanMakePayment that a \n Payment Handler could make use of, to return authorization status.\n

    \n \n \n
    \n \n
    \n

    \n Payment Request success. Demo complete. No payment has been taken.\n

    \n
    \n\n
    \n

    \n The Payment Request API is unsupported or was cancelled or failed, \n so here we can proceed with our legacy web form (not implemented for this demo).\n

    \n
    \n\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076383,"cells":{"text":{"kind":"string","value":"\n\n\n \n Customize the Payment Request Button Depending on Whether User Can Make Payments\n \n \n \n\n\n\n

    Customize the Payment Request Button Depending on Whether User Can Make Payments

    \n\n
    \n

    \n In this example, depending on whether the user can make a fast payment or needs to add \n payment credentials first, the title of the checkout button changes between \n \"W3C Checkout\" and \"Fast W3C Checkout\". This is determined using \n PaymentRequest.canMakePayment(). In both cases, the checkout button calls \n PaymentRequest.show().\n

    \n

    \n For the purposes of the demo, imagine you have chosen an item and\n now you need to check out. Please note that no payments will be taken, this is just a \n front-end demo. If you would like to try entering card details, you can use dummy data,\n for example the card number 4111 1111 1111 1111.\n

    \n\n \n
    \n \n
    \n

    \n Payment Request success. Demo complete. No payment has been taken.\n

    \n
    \n\n
    \n

    \n The Payment Request API is unsupported or was cancelled or failed.\n Here we can proceed with a fallback (not implemented for this demo).\n

    \n
    \n\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076384,"cells":{"text":{"kind":"string","value":"\n\n\n \n Check Whether User Can Make Payment Before All Prices Are Known\n \n \n \n\n\n\n

    Check Whether User Can Make Payment Before All Prices Are Known

    \n\n
    \n

    \n If the checkout flow needs to know whether PaymentRequest.canMakePayment() \n will return true even before all line items and their prices are known, then you can \n instantiate PaymentRequest with dummy data and pre-query .canMakePayment(). \n

    \n

    \n If you call .canMakePayment() multiple times, keep in mind that the first \n parameter to the PaymentRequest constructor should contain the same method names and data.\n

    \n

    \n Please note that no payments will be taken, this is just a front-end demo. \n If you would like to try entering card details, you can use dummy data,\n for example the card number 4111 1111 1111 1111.\n

    \n\n \n
    \n \n
    \n

    \n Payment Request success. Demo complete. No payment has been taken.\n

    \n
    \n\n
    \n

    \n The Payment Request API is unsupported or was cancelled or failed, \n so here we can proceed with our legacy web form (not implemented for this demo).\n

    \n
    \n\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076385,"cells":{"text":{"kind":"string","value":"\n\n\n \n Feature Detect Support for Payment Request API\n \n \n \n\n\n\n

    Feature Detect Support for Payment Request API

    \n\n
    \n

    \n This example shows how a legacy checkout form can be replaced by a Payment Request\n - only for browsers that support it - using:\n if (window.PaymentRequest) { ... }.\n

    \n

    \n For the purposes of the demo, imagine you have chosen an item and now you need to\n check out. Please note that no payments will be taken, this is just a front-end\n demo. If you would like to try entering card details, you can use dummy data,\n for example the card number 4111 1111 1111 1111.\n

    \n\n \n
    \n \n
    \n

    \n Payment Request success. Demo complete. No payment has been taken.\n

    \n
    \n\n
    \n

    \n The Payment Request API is unsupported or was cancelled or failed, \n so here we can proceed with our legacy web form (not implemented for this demo).\n

    \n
    \n\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076386,"cells":{"text":{"kind":"string","value":"\n\n\n \n Show Additional User Interface After Successful Payment\n \n \n \n\n\n\n

    Show Additional User Interface After Successful Payment

    \n\n
    \n

    \n If the merchant desires to collect additional information not part of the API \n (e.g., additional delivery instructions), the merchant can show a page with \n additional &lt;input&gt; fields after the checkout..\n

    \n

    \n For the purposes of the demo, imagine you have chosen an item and now you need to \n check out. Please note that no payments will be taken, this is just a front-end \n demo. If you would like to try entering card details, you can use dummy data,\n for example the card number 4111 1111 1111 1111.\n

    \n\n \n\n
    \n \n
    \n \n \n \n
    \n\n
    \n

    \n Payment Request success. Demo complete. No payment has been taken.\n

    \n
    \n\n
    \n

    \n The Payment Request API is unsupported or was cancelled or failed, \n so here we can proceed with our legacy web form (not implemented for this demo).\n

    \n
    \n\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076387,"cells":{"text":{"kind":"string","value":"\n\n\n \n Recommend a Payment App when User Has No Apps\n \n \n \n\n\n\n

    Recommend a Payment App when User Has No Apps

    \n\n
    \n

    \n In this example, if you select to pay with BobPay on this merchant page, it tries to \n call PaymentRequest.show(), while intercepting the \n NOT_SUPPORTED_ERR exception. If this payment method is not supported, \n it redirects to the download page for BobPay.\n

    \n

    \n For the purposes of the demo, imagine you have chosen an item and\n now you need to check out.\n

    \n \n \n
    \n \n
    \n

    \n Payment Request success. Demo complete. No payment has been taken.\n

    \n
    \n\n
    \n

    \n The Payment Request API is unsupported or was cancelled or failed.\n Here we can proceed with a fallback (not implemented for this demo).\n

    \n
    \n\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076388,"cells":{"text":{"kind":"string","value":"# Examples\n\n* [Feature Detect Support](feature-detect-support.html): Demonstrates using PaymentRequest if it is supported, otherwise falling back to a legacy web form. [See Feature Detect Support demo live](https://mdn.github.io/dom-examples/payment-request/feature-detect-support.html).\n* [Customizing Button Depending on Whether User Can Make Payments](customize-button-can-make-payment.html): Demonstrates changing the title of the checkout button depending on whether the user can make a fast payment or they need to add payment credentials first. [See Customizing Button Depending on Whether User Can Make Payments demo live](https://mdn.github.io/dom-examples/payment-request/customize-button-can-make-payment.html).\n* [Recommend Payment App when User Has No Apps](recommend-payment-app.html): Demonstrates redirecting to a signup page for a payment app when the payment method is not supported. [See Recommend Payment App when User Has No Apps demo live](https://mdn.github.io/dom-examples/payment-request/recommend-payment-app.html).\n* [Check User Can Make Payment Before All Prices Known](check-user-can-make-payment.html): Demonstrates checking the user can make a payment before the line items and their prices are known, using `.canMakePayment()` with dummy data. [See Check User Can Make Payment Before All Prices Known demo live](https://mdn.github.io/dom-examples/payment-request/check-user-can-make-payment.html).\n* [Show Additional User Interface After Successful Payment](show-additional-ui-after-payment.html): Demonstrates showing another page for additional information collection, after the checkout. [See Show Additional User Interface After Successful Payment demo live](https://mdn.github.io/dom-examples/payment-request/show-additional-ui-after-payment.html).\n* [Pre-authorize Transaction](pre-authorize-transaction.html): Indicates how a Payment Handler could be used to return an authorization status, subject to the specification at the time of writing. [See Pre-authorize Transaction demo live](https://mdn.github.io/dom-examples/payment-request/pre-authorize-transaction.html).\n\n# External Examples\n\n* [Payment Request Samples](https://googlechrome.github.io/samples/paymentrequest/) from Google\n* [Payment Request Codelab](https://codelabs.developers.google.com/codelabs/payment-request-api/#0) from Google\n* [VeggieShop](https://github.com/pjbazin/wpwg-demo) e-commerce website demo and source code\n* [WhiteCollar](https://github.com/pjbazin/wpwg-demo/tree/master/WhiteCollar) web payment app demo and source code\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076389,"cells":{"text":{"kind":"string","value":"\n\n \n IndexedDB Example\n \n \n \n \n \n\n \n

    IndexedDB Demo: storing blobs, e-publication example

    \n
    \n

    Works and tested with:

    \n
    \n
    \n\n
    \n\n
    \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
    \n \n \n \n
    \n \n \n \n
    \n \n \n \n
    \n \n \n \n
    \n \n \n \n
    \n\n
    \n \n \n
    \n
    \n\n
    \n \n \n \n \n \n \n \n \n \n \n \n
    \n \n \n \n
    \n \n \n \n
    \n
    \n \n \n
    \n
    \n\n
    \n
    \n \n
    \n
    \n\n
    \n
    \n
    \n
      \n
      \n\n \n\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076390,"cells":{"text":{"kind":"string","value":"body {\n font-family: sans-serif;\n}\n\ntable {\n border-collapse: collapse;\n}\n\nform {\n background-color: #cccccc;\n border-radius: 0.3em;\n display: inline-block;\n margin-bottom: 0.5em;\n padding: 1em;\n}\n\ntable {\n border-collapse: collapse;\n}\n\ninput {\n padding: 0.3em;\n border-color: #cccccc;\n border-radius: 0.3em;\n}\n\n.required:after {\n content: \"*\";\n color: red;\n}\n\n.button-pane {\n margin-top: 1em;\n}\n\n#pub-viewer {\n float: right;\n width: 48%;\n height: 20em;\n border: solid #d092ff 0.1em;\n}\n\n#pub-viewer iframe {\n width: 100%;\n height: 100%;\n}\n\n#pub-list {\n width: 46%;\n background-color: #eeeeee;\n border-radius: 0.3em;\n}\n\n#pub-list li {\n padding-top: 0.5em;\n padding-bottom: 0.5em;\n padding-right: 0.5em;\n}\n\n#msg {\n margin-bottom: 1em;\n}\n\n.action-success {\n padding: 0.5em;\n color: #00d21e;\n background-color: #eeeeee;\n border-radius: 0.2em;\n}\n\n.action-failure {\n padding: 0.5em;\n color: #ff1408;\n background-color: #eeeeee;\n border-radius: 0.2em;\n}\n\n.note {\n font-size: smaller;\n}\n\n.destructive {\n background-color: orange;\n}\n\n.destructive:hover {\n background-color: #ff8000;\n}\n\n.destructive:active {\n background-color: red;\n}\n"},"meta":{"kind":"string","value":"{\n \"repo_name\": \"mdn/dom-examples\",\n \"stars\": \"2648\",\n \"repo_language\": \"JavaScript\",\n \"file_name\": \"style.css\",\n \"mime_type\": \"text/plain\"\n}"}}},{"rowIdx":1076391,"cells":{"text":{"kind":"string","value":"(function () {\n var COMPAT_ENVS = [\n ['Firefox', \">= 16.0\"],\n ['Google Chrome',\n \">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support\"]\n ];\n var compat = $('#compat');\n compat.empty();\n compat.append('
        ');\n COMPAT_ENVS.forEach(function(val, idx, array) {\n $('#compat-list').append('
      • ' + val[0] + ': ' + val[1] + '
      • ');\n });\n\n const DB_NAME = 'mdn-demo-indexeddb-epublications';\n const DB_VERSION = 1; // Use a long long for this value (don't use a float)\n const DB_STORE_NAME = 'publications';\n\n var db;\n\n // Used to keep track of which view is displayed to avoid uselessly reloading it\n var current_view_pub_key;\n\n function openDb() {\n console.log(\"openDb ...\");\n var req = indexedDB.open(DB_NAME, DB_VERSION);\n req.onsuccess = function (evt) {\n // Equal to: db = req.result;\n db = this.result;\n console.log(\"openDb DONE\");\n };\n req.onerror = function (evt) {\n console.error(\"openDb:\", evt.target.errorCode);\n };\n\n req.onupgradeneeded = function (evt) {\n console.log(\"openDb.onupgradeneeded\");\n var store = evt.currentTarget.result.createObjectStore(\n DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });\n\n store.createIndex('biblioid', 'biblioid', { unique: true });\n store.createIndex('title', 'title', { unique: false });\n store.createIndex('year', 'year', { unique: false });\n };\n }\n\n /**\n * @param {string} store_name\n * @param {string} mode either \"readonly\" or \"readwrite\"\n */\n function getObjectStore(store_name, mode) {\n var tx = db.transaction(store_name, mode);\n return tx.objectStore(store_name);\n }\n\n function clearObjectStore() {\n var store = getObjectStore(DB_STORE_NAME, 'readwrite');\n var req = store.clear();\n req.onsuccess = function(evt) {\n displayActionSuccess(\"Store cleared\");\n displayPubList(store);\n };\n req.onerror = function (evt) {\n console.error(\"clearObjectStore:\", evt.target.errorCode);\n displayActionFailure(this.error);\n };\n }\n\n function getBlob(key, store, success_callback) {\n var req = store.get(key);\n req.onsuccess = function(evt) {\n var value = evt.target.result;\n if (value)\n success_callback(value.blob);\n };\n }\n\n /**\n * @param {IDBObjectStore=} store\n */\n function displayPubList(store) {\n console.log(\"displayPubList\");\n\n if (typeof store == 'undefined')\n store = getObjectStore(DB_STORE_NAME, 'readonly');\n\n var pub_msg = $('#pub-msg');\n pub_msg.empty();\n var pub_list = $('#pub-list');\n pub_list.empty();\n // Resetting the iframe so that it doesn't display previous content\n newViewerFrame();\n\n var req;\n req = store.count();\n // Requests are executed in the order in which they were made against the\n // transaction, and their results are returned in the same order.\n // Thus the count text below will be displayed before the actual pub list\n // (not that it is algorithmically important in this case).\n req.onsuccess = function(evt) {\n pub_msg.append('

        There are ' + evt.target.result +\n ' record(s) in the object store.

        ');\n };\n req.onerror = function(evt) {\n console.error(\"add error\", this.error);\n displayActionFailure(this.error);\n };\n\n var i = 0;\n req = store.openCursor();\n req.onsuccess = function(evt) {\n var cursor = evt.target.result;\n\n // If the cursor is pointing at something, ask for the data\n if (cursor) {\n console.log(\"displayPubList cursor:\", cursor);\n req = store.get(cursor.key);\n req.onsuccess = function (evt) {\n var value = evt.target.result;\n var list_item = $('
      • ' +\n '[' + cursor.key + '] ' +\n '(biblioid: ' + value.biblioid + ') ' +\n value.title +\n '
      • ');\n if (value.year != null)\n list_item.append(' - ' + value.year);\n\n if (value.hasOwnProperty('blob') &&\n typeof value.blob != 'undefined') {\n var link = $('File');\n link.on('click', function() { return false; });\n link.on('mouseenter', function(evt) {\n setInViewer(evt.target.getAttribute('href')); });\n list_item.append(' / ');\n list_item.append(link);\n } else {\n list_item.append(\" / No attached file\");\n }\n pub_list.append(list_item);\n };\n\n // Move on to the next object in store\n cursor.continue();\n\n // This counter serves only to create distinct ids\n i++;\n } else {\n console.log(\"No more entries\");\n }\n };\n }\n\n function newViewerFrame() {\n var viewer = $('#pub-viewer');\n viewer.empty();\n var iframe = $('