text
stringlengths 2
104M
| meta
dict |
---|---|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width" />
<title>Service worker demo</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<h1>Lego Star Wars gallery</h1>
<section></section>
<script type="module" src="app.js"></script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
export const Path = 'gallery/';
export const Gallery = {
images: [
{
name: 'Darth Vader',
alt: 'A Black Clad warrior lego toy',
url: 'gallery/myLittleVader.jpg',
credit:
'<a href="https://www.flickr.com/photos/legofenris/">legOfenris</a>, published under a <a href="https://creativecommons.org/licenses/by-nc-nd/2.0/">Attribution-NonCommercial-NoDerivs 2.0 Generic</a> license.',
},
{
name: 'Snow Troopers',
alt: 'Two lego solders in white outfits walking across an icy plain',
url: 'gallery/snowTroopers.jpg',
credit:
'<a href="https://www.flickr.com/photos/legofenris/">legOfenris</a>, published under a <a href="https://creativecommons.org/licenses/by-nc-nd/2.0/">Attribution-NonCommercial-NoDerivs 2.0 Generic</a> license.',
},
{
name: 'Bounty Hunters',
alt: 'A group of bounty hunters meeting, aliens and humans in costumes.',
url: 'gallery/bountyHunters.jpg',
credit:
'<a href="https://www.flickr.com/photos/legofenris/">legOfenris</a>, published under a <a href="https://creativecommons.org/licenses/by-nc-nd/2.0/">Attribution-NonCommercial-NoDerivs 2.0 Generic</a> license.',
},
],
};
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
html,
body {
margin: 0;
padding: 0;
font-size: 10px;
font-family: sans-serif;
}
h1 {
text-indent: 100%;
white-space: nowrap;
overflow: hidden;
height: 197px;
background: url(star-wars-logo.jpg) no-repeat center;
}
section {
max-width: 640px;
margin: 0 auto;
}
figure {
width: 100%;
margin: 0;
}
img {
width: 100%;
box-shadow: 2px 2px 1px black;
}
caption {
display: block;
margin: 0 auto 1rem;
width: 70%;
font-size: 1.2rem;
line-height: 1.5;
padding: 5px;
background: #ccc;
box-shadow: 1px 1px 1px black;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
const addResourcesToCache = async (resources) => {
const cache = await caches.open('v1');
await cache.addAll(resources);
};
const putInCache = async (request, response) => {
const cache = await caches.open('v1');
await cache.put(request, response);
};
const cacheFirst = async ({ request, preloadResponsePromise, fallbackUrl }) => {
// First try to get the resource from the cache
const responseFromCache = await caches.match(request);
if (responseFromCache) {
return responseFromCache;
}
// Next try to use the preloaded response, if it's there
const preloadResponse = await preloadResponsePromise;
if (preloadResponse) {
console.info('using preload response', preloadResponse);
putInCache(request, preloadResponse.clone());
return preloadResponse;
}
// Next try to get the resource from the network
try {
const responseFromNetwork = await fetch(request.clone());
// response may be used only once
// we need to save clone to put one copy in cache
// and serve second one
putInCache(request, responseFromNetwork.clone());
return responseFromNetwork;
} catch (error) {
const fallbackResponse = await caches.match(fallbackUrl);
if (fallbackResponse) {
return fallbackResponse;
}
// when even the fallback response is not available,
// there is nothing we can do, but we must always
// return a Response object
return new Response('Network error happened', {
status: 408,
headers: { 'Content-Type': 'text/plain' },
});
}
};
const enableNavigationPreload = async () => {
if (self.registration.navigationPreload) {
// Enable navigation preloads!
await self.registration.navigationPreload.enable();
}
};
self.addEventListener('activate', (event) => {
event.waitUntil(enableNavigationPreload());
});
self.addEventListener('install', (event) => {
event.waitUntil(
addResourcesToCache([
'./',
'./index.html',
'./style.css',
'./app.js',
'./image-list.js',
'./star-wars-logo.jpg',
'./gallery/bountyHunters.jpg',
'./gallery/myLittleVader.jpg',
'./gallery/snowTroopers.jpg',
])
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
cacheFirst({
request: event.request,
preloadResponsePromise: event.preloadResponse,
fallbackUrl: './gallery/myLittleVader.jpg',
})
);
});
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
# simple service worker
Service 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/).
You 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).
In 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)
if you are having problems getting your code to do anything. You need to change the paths relative to where you are serving your files!
## Running locally
To get this code running locally on your computer as-is, you need to do the following:
1. 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).
2. Clone the repo in a location on your machine.
3. Start a local server in the root of this directory using [`lite-server`](https://www.npmjs.com/package/lite-server). `npx lite-server .`
4. When the server starts, the `index.html`` page will open in your default browser.
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Popover API examples</title>
</head>
<body>
<h1>MDN Popover API examples</h1>
<p>
This set of examples demonstrates usage of the
<a href="https://developer.mozilla.org/en-US/docs/Web/API/Popover_API"
>Popover API</a
>
(also see the
<a href="https://html.spec.whatwg.org/multipage/popover.html"
>specification</a
>).
</p>
<ul>
<li>
<a href="basic-declarative/">Basic declarative popover example</a>:
Demonstrates a basic auto state popover.
</li>
<li>
<a href="blur-background/">Blur background popover example</a>: Shows how
you can add styling to the content behind the popover using the
<code>::backdrop</code> pseudo-element.
</li>
<li>
<a href="multiple-auto/">Multiple auto popovers example</a>: Demonstrates
that, generally, only one auto popover can be displayed at once.
</li>
<li>
<a href="multiple-manual/">Multiple manual popovers example</a>:
Demonstrates that multiple manual popovers can be displayed at once, bt
they can't be light-dismissed.
</li>
<li>
<a href="nested-popovers/">Nested popover menu example</a>: Demonstrates
the behavior of nested auto state popovers.
</li>
<li>
<a href="popover-positioning/">Popover positioning example</a>: An
isolated example showing CSS overriding of the default popover positioning
specified by the UA sylesheet.
</li>
<li>
<a href="toggle-help-ui/">Toggle help UI example</a>: Shows the basics of
using JavaScript to control popover showing and hiding.
</li>
<li>
<a href="toast-popovers/">Toast popovers example</a>: Illustrates how to
make a simple system of "toast" notifications with popovers, which
automatically hide again after a certain time.
</li>
</ul>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Nested popovers example</title>
<style>
body,
html {
font-family: sans-serif;
}
body [popover] {
border: 1px solid black;
width: 120px;
inset: unset;
}
#mainpopover {
left: 7px;
top: 38px;
}
#subpopover {
left: 120px;
top: 86px;
}
.listcontainer,
.subcontainer {
display: flex;
flex-direction: column;
}
a {
flex: 1;
text-decoration: none;
outline: none;
text-align: center;
line-height: 3;
color: black;
}
a:link,
a:visited {
background: palegoldenrod;
color: black;
}
a:hover,
a:focus {
background: orange;
}
a:active {
background: darkred;
color: white;
}
</style>
<script src="index.js" defer></script>
</head>
<body>
<button popovertarget="mainpopover" popovertargetaction="toggle">
Menu
</button>
<div id="mainpopover" popover>
<nav class="listcontainer">
<a href="#">Home</a>
<div class="subcontainer" tabindex="0">
<a href="#">Pizza <strong>></strong></a>
<div id="subpopover" popover>
<div class="listcontainer">
<a href="#">Margherita</a>
<a href="#">Pepperoni</a>
<a href="#">Ham & Shroom</a>
<a href="#">Vegan</a>
</div>
</div>
</div>
<a href="#">Music</a>
<a href="#">Wombats</a>
<a href="#">Finland</a>
</nav>
</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
const subcontainer = document.querySelector(".subcontainer");
const mainpopover = document.getElementById("mainpopover");
const subpopover = document.getElementById("subpopover");
// Events to show/hide the subpopover when the mouse moves over and out
subcontainer.addEventListener("mouseover", () => {
subpopover.showPopover();
});
subcontainer.addEventListener("mouseout", () => {
if (subpopover.matches(":popover-open")) {
subpopover.hidePopover();
}
});
// Event to make the subpopover keyboard-accessible
subcontainer.addEventListener("focusin", () => {
subpopover.showPopover();
});
// Events to hide the popover menus when an option is selected in either of them
mainpopover.addEventListener("click", () => {
if (subpopover.matches(":popover-open")) {
subpopover.hidePopover();
}
if (mainpopover.matches(":popover-open")) {
mainpopover.hidePopover();
}
});
subpopover.addEventListener("click", () => {
subpopover.hidePopover();
mainpopover.hidePopover();
});
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Multiple manual popovers example</title>
<style>
:popover-open {
position: absolute;
inset: unset;
top: 80px;
}
#mypopup-1 {
left: 8px;
}
#mypopup-2 {
left: 150px;
}
</style>
</head>
<body>
<button popovertarget="mypopup-1" popovertargetaction="show">
Show popover #1
</button>
<button popovertarget="mypopup-1" popovertargetaction="hide">
Hide popover #1
</button>
<hr>
<button popovertarget="mypopup-2" popovertargetaction="show">
Show popover #2
</button>
<button popovertarget="mypopup-2" popovertargetaction="hide">
Hide popover #2
</button>
<div id="mypopup-1" popover="manual">Popover content #1</div>
<div id="mypopup-2" popover="manual">Popover content #2</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Toast popovers example</title>
<style>
.failure {
background: rgb(255, 100, 100);
}
.success {
background: rgb(50, 255, 50);
}
:popover-open {
position: absolute;
inset: unset;
right: 5px;
bottom: 5px;
}
</style>
<script src="index.js" defer></script>
</head>
<body>
<button id="success-toast-btn">Generate success toast</button>
<button id="failure-toast-btn">Generate fail toast</button>
<p>Successes: 0. Failures: 0.</p>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
const successToastBtn = document.getElementById("success-toast-btn");
const failureToastBtn = document.getElementById("failure-toast-btn");
const counter = document.querySelector("p");
let successCount = 0;
let failCount = 0;
function makeToast(result) {
// Create an element and make it into a popover
const popover = document.createElement("article");
popover.popover = "manual";
popover.classList.add("toast");
popover.classList.add("newest");
let msg;
// Give the toast an appropriate text content, class for styling, and update
// the relevant count, depending on whether it was a success or a failure
if (result === "success") {
msg = "Action was successful!";
popover.classList.add("success");
successCount++;
} else if (result === "failure") {
msg = "Action failed!";
popover.classList.add("failure");
failCount++;
} else {
return;
}
// Give the toast its text content, and add it to the DOM
popover.textContent = msg;
document.body.appendChild(popover);
// Show the popover
popover.showPopover();
// Update the counter paragraph
updateCounter();
// Remove the toast again after 4 seconds
setTimeout(() => {
popover.hidePopover();
popover.remove();
}, 4000);
// When a new toast appears, run the movetoastsUp() function
popover.addEventListener("toggle", (event) => {
if (event.newState === "open") {
moveToastsUp();
}
});
}
function moveToastsUp() {
const toasts = document.querySelectorAll(".toast");
toasts.forEach((toast) => {
// If the toast is the one that has just appeared, we don't want it to move up.
if (toast.classList.contains("newest")) {
toast.style.bottom = `5px`;
toast.classList.remove("newest");
} else {
// Move up all the other toasts by 50px to make way for the new one
const prevValue = toast.style.bottom.replace("px", "");
const newValue = parseInt(prevValue) + 50;
toast.style.bottom = `${newValue}px`;
}
});
}
function updateCounter() {
// Update the counter paragraph with the new count each time a new toast is generated
counter.textContent = `Successes: ${successCount}. Failures: ${failCount}.`;
}
// Handlers to wire up the buttons to the makeToast() function
successToastBtn.addEventListener("click", () => {
makeToast("success");
});
failureToastBtn.addEventListener("click", () => {
makeToast("failure");
});
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blur background example</title>
<style>
body {
margin: 0;
background: url("tile.png");
font-family: Arial, Helvetica, sans-serif;
}
button {
margin: 5px 0 0 5px;
}
:popover-open {
width: 300px;
height: 200px;
padding: 0 10px;
border-radius: 10px;
}
p {
line-height: 1.5;
}
::backdrop {
backdrop-filter: blur(3px);
}
</style>
</head>
<body>
<button popovertarget="mypopover" popovertargetaction="show">
Show popover
</button>
<div id="mypopover" popover>
<h2>Popover heading</h2>
<p>
This here is some very important content that we want to draw your
attention to before you light dismiss it. Read it all, do not delay!
</p>
</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Basic declarative popover example</title>
</head>
<body>
<button popovertarget="mypopover" popovertargetaction="show">
Show popover
</button>
<button popovertarget="mypopover" popovertargetaction="hide">
Hide popover
</button>
<div id="mypopover" popover>Popover content</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Toggle help UI example</title>
<style>
:popover-open {
position: absolute;
inset: unset;
bottom: 5px;
right: 5px;
}
@media all and (max-width: 600px) {
:popover-open {
left: 5px;
}
}
</style>
<script src="index.js" defer></script>
</head>
<body>
<button id="toggleBtn">Toggle popover help UI</button>
<p id="keyboard-help-para">Click the above button or press "h" to get help with using our awesome app.</p>
<div id="mypopover">
<h2>Help!</h2>
<p>You can use the following commands to control the app</p>
<ul>
<li>Press <ins>C</ins> to order cheese</li>
<li>Press <ins>T</ins> to order tofu</li>
<li>Press <ins>B</ins> to order bacon</li>
<hr />
<li>Say "Service" to summon the robot waiter to take your order</li>
<li>Say "Escape" to engage the ejector seat</li>
</ul>
</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function supportsPopover() {
return HTMLElement.prototype.hasOwnProperty("popover");
}
const popover = document.getElementById("mypopover");
const toggleBtn = document.getElementById("toggleBtn");
const keyboardHelpPara = document.getElementById("keyboard-help-para");
const popoverSupported = supportsPopover();
if (popoverSupported) {
popover.popover = "auto";
toggleBtn.popoverTargetElement = popover;
toggleBtn.popoverTargetAction = "toggle";
document.addEventListener("keydown", (event) => {
if (event.key === "h") {
popover.togglePopover();
}
});
} else {
toggleBtn.style.display = "none";
keyboardHelpPara.style.display = "none";
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Popover positioning example</title>
<style>
:popover-open {
width: 300px;
height: 200px;
position: absolute;
inset: unset;
bottom: 5px;
right: 5px;
margin: 0;
}
</style>
</head>
<body>
<button popovertarget="mypopover" popovertargetaction="show">
Show popover
</button>
<button popovertarget="mypopover" popovertargetaction="hide">
Hide popover
</button>
<div id="mypopover" popover>
<h2>Popover heading</h2>
<p>Popover content</p>
</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Multiple auto popovers example</title>
<style>
:popover-open {
position: absolute;
inset: unset;
top: 40px;
}
#mypopover-1 {
left: 8px;
}
#mypopover-2 {
left: 150px;
}
</style>
</head>
<body>
<button popovertarget="mypopover-1" popovertargetaction="show">
Show popover #1
</button>
<button popovertarget="mypopover-2" popovertargetaction="show">
Show popover #2
</button>
<div id="mypopover-1" popover>Popover content #1</div>
<div id="mypopover-2" popover>Popover content #2</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Abort APi example</title>
<style>
.wrapper {
width: 70%;
max-width: 800px;
margin: 0 auto;
}
video {
max-width: 100%;
}
.wrapper > div {
margin-bottom: 10px;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<div class="wrapper">
<h1>Simple offline video player</h1>
<div class="controls">
<button class="download">Download video</button>
<button class="abort hidden">Cancel download</button>
<p class="reports"></p>
</div>
<div class="videoWrapper hidden">
<p>Sintel © copyright Blender Foundation | <a href="http://www.sintel.org/">www.sintel.org</a>.</p>
</div>
</div>
</body>
<script>
const url = 'sintel.mp4';
const videoWrapper = document.querySelector('.videoWrapper');
const downloadBtn = document.querySelector('.download');
const abortBtn = document.querySelector('.abort');
const reports = document.querySelector('.reports');
let controller;
let progressAnim;
let animCount = 0;
downloadBtn.addEventListener('click', fetchVideo);
abortBtn.addEventListener('click', () => {
controller.abort();
console.log('Download aborted');
downloadBtn.classList.remove('hidden');
});
function fetchVideo() {
controller = new AbortController();
const signal = controller.signal;
downloadBtn.classList.add('hidden');
abortBtn.classList.remove('hidden');
reports.textContent = 'Video awaiting download...';
fetch(url, { signal }).then((response) => {
if (response.status === 200) {
runAnimation();
setTimeout(() => console.log('Body used: ', response.bodyUsed), 1);
return response.blob();
} else {
throw new Error('Failed to fetch');
}
}).then((myBlob) => {
const video = document.createElement('video');
video.setAttribute('controls', '');
video.src = URL.createObjectURL(myBlob);
videoWrapper.appendChild(video);
videoWrapper.classList.remove('hidden');
abortBtn.classList.add('hidden');
downloadBtn.classList.add('hidden');
reports.textContent = 'Video ready to play';
}).catch((e) => {
abortBtn.classList.add('hidden');
downloadBtn.classList.remove('hidden');
reports.textContent = 'Download error: ' + e.message;
}).finally(() => {
clearInterval(progressAnim);
animCount = 0;
});
}
function runAnimation() {
progressAnim = setInterval(() => {
switch (animCount++ & 3) {
case 0: reports.textContent = 'Download occuring; waiting for video player to be constructed'; break;
case 1: reports.textContent = 'Download occuring; waiting for video player to be constructed.'; break;
case 2: reports.textContent = 'Download occuring; waiting for video player to be constructed..'; break;
case 3: reports.textContent = 'Download occuring; waiting for video player to be constructed...'; break;
}
}, 300);
}
</script>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>matchMedia test file</title>
<style>
html {
font-family: sans-serif;
background-color: white;
}
body {
padding: 20px;
margin: 10px;
background-color: blue;
border: 10px solid black;
}
h1, p {
text-align: center;
}
p {
font-size: 1.3rem;
}
</style>
</head>
<body>
<h1>matchMedia test</h1>
<p></p>
</body>
<script>
var para = document.querySelector('p');
function screenTest() {
if (window.matchMedia('(max-width: 600px)').matches) {
/* the viewport is 600 pixels wide or less */
para.textContent = 'This is a narrow screen; ' + window.innerWidth + "px wide.";
document.body.style.backgroundColor = 'red';
} else if(window.matchMedia('(min-width: 1400px)').matches) {
/* the viewport is more than than 1400 pixels wide */
para.textContent = 'This is a REALLY wide screen; ' + window.innerWidth + "px wide.";
document.body.style.backgroundColor = 'green';
} else {
/* the viewport is more than than 400 pixels wide */
para.textContent = 'This is a wide screen; ' + window.innerWidth + "px wide.";
document.body.style.backgroundColor = 'blue';
}
}
screenTest();
document.body.onresize = screenTest;
</script>
</html> | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<title>Using Drag and Drop API to copy and move elements</title>
<!--
This example demonstrates using various HTML Drag and Drop interfaces including:
* Global "draggable" attribute
* Event handlers for dragstart, dragover and drop
* Global event handlers for ondragstart, ondragover and ondrop
* Using the DataTransfer interface to copy and move elements (<div>)
-->
<style>
div {
margin: 0em;
padding: 2em;
}
#src_copy, #src_move {
color: blue;
border: 5px solid black;
max-width: 300px;
width: fit-content;
height: 50px;
}
#dest_copy, #dest_move {
border: 5px solid blue;
width: 300px;
min-height: 50px;
}
</style>
<script>
function dragstart_handler(ev) {
console.log("dragStart");
// Change the source element's background color to signify drag has started
ev.currentTarget.style.border = "dashed";
// Add the id of the drag source element to the drag data payload so
// it is available when the drop event is fired
ev.dataTransfer.setData("text", ev.target.id);
// Tell the browser both copy and move are possible
ev.effectAllowed = "copyMove";
}
function dragover_handler(ev) {
console.log("dragOver");
// Change the target element's border to signify a drag over event
// has occurred
ev.currentTarget.style.background = "lightblue";
ev.preventDefault();
}
function drop_handler(ev) {
console.log("Drop");
ev.preventDefault();
// Get the id of drag source element (that was added to the drag data
// payload by the dragstart event handler)
var id = ev.dataTransfer.getData("text");
// Only Move the element if the source and destination ids are both "move"
if (id == "src_move" && ev.target.id == "dest_move")
ev.target.appendChild(document.getElementById(id));
// Copy the element if the source and destination ids are both "copy"
if (id == "src_copy" && ev.target.id == "dest_copy") {
var nodeCopy = document.getElementById(id).cloneNode(true);
nodeCopy.id = "newId";
ev.target.appendChild(nodeCopy);
}
}
function dragend_handler(ev) {
console.log("dragEnd");
// Restore source's border
ev.target.style.border = "solid black";
}
</script>
</head>
<body>
<h1>Drag and Drop: Copy and Move elements with <code>DataTransfer</code></h1>
<div draggable="true" id="src_copy" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);">
Select this element and drag to the <strong>Copy Drop Zone</strong>.
</div>
<div id="dest_copy" ondrop="drop_handler(event);" ondragover="dragover_handler(event);"><strong>Copy Drop Zone</strong></div>
<div draggable="true" id="src_move" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);">
Select this element and drag to the <strong>Move Drop Zone</strong>.
</div>
<div id="dest_move" ondrop="drop_handler(event);" ondragover="dragover_handler(event);"><strong>Move Drop Zone</strong></div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<title>Using Drag and Drop API to copy and move elements</title>
<!--
This example demonstrates using the HTML Drag and Drop
DataTransferItem, and DataTransferItemList interfaces to copy
and move elements.
-->
<style>
div {
margin: 0em;
padding: 2em;
}
#src_copy, #src_move {
color: blue;
border: 5px solid black;
max-width: 300px;
width: fit-content;
height: 50px;
}
#dest_copy, #dest_move {
border: 5px solid blue;
width: 300px;
min-height: 50px;
}
</style>
<script>
function dragstart_handler(ev) {
console.log("dragStart");
var dti = ev.dataTransfer.items;
if (dti === undefined || dti == null) {
console.log("Browser does not support DataTransferItem interface");
return;
}
// Change the source element's background color to signify drag has started
ev.currentTarget.style.border = "dashed";
// Add the id of the drag source element to the drag data payload so
// it is available when the drop event is fired
dti.add(ev.target.id, "text/plain");
// Tell the browser both copy and move are possible
ev.effectAllowed = "copyMove";
}
function dragover_handler(ev) {
console.log("dragOver");
var dti = ev.dataTransfer.items;
if (dti === undefined || dti == null) {
console.log("Browser does not support DataTransferItem interface");
return;
}
// Change the target element's border to signify a drag over event
// has occurred
ev.currentTarget.style.background = "lightblue";
ev.preventDefault();
}
function drop_handler(ev) {
console.log("Drop");
ev.preventDefault();
var dti = ev.dataTransfer.items;
if (dti === undefined || dti == null) {
console.log("Browser does not support DataTransferItem interface");
return;
}
// Get the id of the drag source element (that was added to the drag data
// payload by the dragstart event handler). Even though only one drag item
// was explicitly added, the browser may include other items so need to search
// for the plain/text item.
for (var i=0; i < dti.length; i++) {
console.log("Drop: item[" + i + "].kind = " + dti[i].kind + " ; item[" + i + "].type = " + dti[i].type);
if ((dti[i].kind == 'string') && (dti[i].type.match('^text/plain'))) {
// This item is the target node
dti[i].getAsString(function (id){
// Only Move the element if the source and destination ids are both "move"
if (id == "src_move" && ev.target.id == "dest_move")
ev.target.appendChild(document.getElementById(id));
// Copy the element if the source and destination ids are both "copy"
if (id == "src_copy" && ev.target.id == "dest_copy") {
var nodeCopy = document.getElementById(id).cloneNode(true);
nodeCopy.id = "newId";
ev.target.appendChild(nodeCopy);
}
});
}
}
}
function dragend_handler(ev) {
console.log("dragEnd");
var dti = ev.dataTransfer.items;
if (dti === undefined || dti == null) {
console.log("Browser does not support DataTransferItem interface");
return;
}
// Restore source's border
ev.target.style.border = "solid black";
// Remove all of the items from the list.
dti.clear();
}
</script>
</head>
<body>
<h1>Drag and Drop: Copy and Move elements with <code>DataTransferItemList</code> interface</h1>
<div draggable="true" id="src_copy" ondragstart="dragstart_handler(event);" ondragend="dragend_handler(event);">
Select this element and drag to the <strong>Copy Drop Zone</strong>.
</div>
<div id="dest_copy" ondrop="drop_handler(event);" ondragover="dragover_handler(event);"><strong>Copy Drop Zone</strong></div>
<div draggable="true" id="src_move" ondragstart="dragstart_handler(event);">
Select this element and drag to the <strong>Move Drop Zone</strong>.
</div>
<div id="dest_move" ondrop="drop_handler(event);" ondragover="dragover_handler(event);"><strong>Move Drop Zone</strong></div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<title>Feature tests for DnD interfaces</title>
<meta name="viewport" content="width=device-width">
<style>
div {
margin: 0em;
padding: 2em;
}
#source {
color: blue;
border: 1px solid black;
}
#target {
border: 1px solid black;
}
</style>
<script>
function check_DragEvents() {
// Check for support of the Drag event types
var events = ["ondrag",
"ondragstart",
"ondragend",
"ondragover",
"ondragenter",
"ondragleave",
"ondragexit",
"ondrop"];
console.log("Drag Event Types...");
for (var i=0; i < events.length; i++) {
var supported = events[i] in window;
console.log("... " + events[i] + " = " + (supported ? "Yes" : "No"));
}
}
function check_DataTransfer(dt) {
// Check the DataTransfer object's methods and properties
var properties = ["dropEffect",
"effectAllowed",
"types",
"files",
"items"];
var methods = ["setDragImage",
"getData",
"setData",
"clearData"];
console.log("DataTransfer ... " + dt);
for (var i=0; i < properties.length; i++) {
var supported = properties[i] in dt;
console.log("... dataTransfer." + properties[i] + " = " + (supported ? "Yes" : "No"));
}
for (var i=0; i < methods.length; i++) {
var supported = typeof dt[methods[i]] == "function";
console.log("... dataTransfer." + methods[i] + "() = " + (supported ? "Yes" : "No"));
}
}
function check_DataTransferItem(dti) {
// Check the DataTransferItem object's methods and properties
var properties = ["kind",
"type"];
var methods = ["getAsFile",
"getAsString"];
console.log("DataTransferItem ... " + dti);
for (var i=0; i < properties.length; i++) {
if (dti === undefined) {
console.log("... items." + properties[i] + " = undefined");
} else {
var supported = properties[i] in dti;
console.log("... items." + properties[i] + " = " + (supported ? "Yes" : "No"));
}
}
for (var i=0; i < methods.length; i++) {
if (dti === undefined) {
console.log("... items." + methods[i] + "() = undefined");
} else {
var supported = typeof dti[methods[i]] == "function";
console.log("... items." + methods[i] + "() = " + (supported ? "Yes" : "No"));
}
}
}
function check_DataTransferItemList(dtil) {
// Check the DataTransferItemList object's methods and properties
var properties = ["length"];
var methods = ["add",
"remove",
"clear"];
console.log("DataTransferItemList ... " + dtil);
for (var i=0; i < properties.length; i++) {
if (dtil === undefined) {
console.log("... items." + properties[i] + " = undefined");
} else {
var supported = properties[i] in dtil;
console.log("... items." + properties[i] + " = " + (supported ? "Yes" : "No"));
}
}
for (var i=0; i < methods.length; i++) {
if (dtil === undefined) {
console.log("... items." + methods[i] + "() = undefined");
} else {
var supported = typeof dtil[methods[i]] == "function";
console.log("... items." + methods[i] + "() = " + (supported ? "Yes" : "No"));
}
}
}
function dragstart_handler(ev) {
ev.dataTransfer.dropEffect = "move";
check_DragEvents();
var dt = ev.dataTransfer;
if (dt === undefined) {
console.log("DataTransfer is NOT supported.");
} else {
// Make sure there is at least one item
dt.setData("text/plain", "Move this.");
check_DataTransfer(dt);
}
}
function dragover_handler(ev) {
ev.dataTransfer.dropEffect = "move";
ev.preventDefault();
}
function drop_handler(ev) {
if (ev.dataTransfer === undefined) {
console.log("DataTransferItem NOT supported.");
console.log("DataTransferItemList NOT supported.");
} else {
var dti = ev.dataTransfer.items;
if (dti === undefined) {
console.log("DataTransferItem NOT supported.");
console.log("DataTransferItemList NOT supported.");
} else {
check_DataTransferItem(dti[0]);
check_DataTransferItemList(dti);
}
}
}
</script>
<body>
<h1>Log support of DnD objects' methods and properties</h1>
<div>
<p id="source" ondragstart="dragstart_handler(event);" draggable="true">
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.</p>
</div>
<div id="target" ondrop="drop_handler(event);" ondragover="dragover_handler(event);">Drop Zone</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<title>Demo: Drag and Drop files</title>
<!--
This example demonstrates using the HTML Drag and Drop's DataTransfer
and DataTransferItemList interfaces to drag files from the platform's
file manger and drop them in an HTML document.
-->
<style>
div {
margin: 0em;
padding: 2em;
}
#drop_zone {
border: 5px solid blue;
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<h1>Drag and drop files</h1>
<div id="drop_zone" ondrop="dropHandler(event);" ondragover="dragOverHandler(event);">
<p>Drag one or more files to this Drop Zone ...</p>
</div>
<script type="text/javascript">
function dragOverHandler(ev) {
console.log('File(s) in drop zone');
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
}
function dropHandler(ev) {
console.log('File(s) dropped');
// Prevent default behavior (Prevent file from being opened)
ev.preventDefault();
if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.items.length; i++) {
// If dropped items aren't files, reject them
if (ev.dataTransfer.items[i].kind === 'file') {
var file = ev.dataTransfer.items[i].getAsFile();
console.log('... file[' + i + '].name = ' + file.name);
}
}
} else {
// Use DataTransfer interface to access the file(s)
for (var i = 0; i < ev.dataTransfer.files.length; i++) {
console.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name);
}
}
// Pass event to removeDragData for cleanup
removeDragData(ev)
}
function removeDragData(ev) {
console.log('Removing drag data')
if (ev.dataTransfer.items) {
// Use DataTransferItemList interface to remove the drag data
ev.dataTransfer.items.clear();
}
}
</script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
Examples:
* [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.
* [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.
* [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)).
* [File Drag and Drop](http://mdn.github.io/dom-examples/drag-and-drop/File-drag.html). Select one or more files in a <em>File Manager</em> and drag them to this app's <em>drop zone</em>.
External DnD Demos:
* [Drag and Drop File](https://jsbin.com/hiqasek/edit?html,js,output); jsbin
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<!--
This app demonstrates using the Touch Events touch event types (touchstart,
touchmove, touchcancel and touchend) for the following interaction:
1. Single touch
2. Two (simultaneous) touches
3. More than two simultaneous touches
4. 1-finger swipe
5. 2-finger move/pinch/swipe
-->
<head>
<title>Touch Events tutorial</title>
<meta name="viewport" content="width=device-width">
<style>
div {
margin: 0em;
padding: 2em;
}
#target1, #target2, #target3, #target4 {
background: white;
border: 1px solid black;
}
</style>
</head>
<script>
// Log events flag
var logEvents = false;
// Touch Point cache
var tpCache = new Array();
function enableLog(ev) {
logEvents = logEvents ? false : true;
}
function log(name, ev, printTargetIds) {
var o = document.getElementsByTagName('output')[0];
var s = name + ": touches = " + ev.touches.length +
" ; targetTouches = " + ev.targetTouches.length +
" ; changedTouches = " + ev.changedTouches.length;
o.innerHTML += s + " <br>";
if (printTargetIds) {
s = "";
for (var i=0; i < ev.targetTouches.length; i++) {
s += "... id = " + ev.targetTouches[i].identifier + " <br>";
}
o.innerHTML += s;
}
}
function clearLog(event) {
var o = document.getElementsByTagName('output')[0];
o.innerHTML = "";
}
function update_background(ev) {
// Change background color based on the number simultaneous touches
// in the event's targetTouches list:
// yellow - one tap (or hold)
// pink - two taps
// lightblue - more than two taps
switch (ev.targetTouches.length) {
case 1:
// Single tap`
ev.target.style.background = "yellow";
break;
case 2:
// Two simultaneous touches
ev.target.style.background = "pink";
break;
default:
// More than two simultaneous touches
ev.target.style.background = "lightblue";
}
}
// This is a very basic 2-touch move/pinch/zoom handler that does not include
// error handling, only handles horizontal moves, etc.
function handle_pinch_zoom(ev) {
if (ev.targetTouches.length == 2 && ev.changedTouches.length == 2) {
// Check if the two target touches are the same ones that started
// the 2-touch
var point1=-1, point2=-1;
for (var i=0; i < tpCache.length; i++) {
if (tpCache[i].identifier == ev.targetTouches[0].identifier) point1 = i;
if (tpCache[i].identifier == ev.targetTouches[1].identifier) point2 = i;
}
if (point1 >=0 && point2 >= 0) {
// Calculate the difference between the start and move coordinates
var diff1 = Math.abs(tpCache[point1].clientX - ev.targetTouches[0].clientX);
var diff2 = Math.abs(tpCache[point2].clientX - ev.targetTouches[1].clientX);
// This threshold is device dependent as well as application specific
var PINCH_THRESHHOLD = ev.target.clientWidth / 10;
if (diff1 >= PINCH_THRESHHOLD && diff2 >= PINCH_THRESHHOLD)
ev.target.style.background = "green";
}
else {
// empty tpCache
tpCache = new Array();
}
}
}
function start_handler(ev) {
// If the user makes simultaneious touches, the browser will fire a
// separate touchstart event for each touch point. Thus if there are
// three simultaneous touches, the first touchstart event will have
// targetTouches length of one, the second event will have a length
// of two, and so on.
ev.preventDefault();
// Cache the touch points for later processing of 2-touch pinch/zoom
if (ev.targetTouches.length == 2) {
for (var i=0; i < ev.targetTouches.length; i++) {
tpCache.push(ev.targetTouches[i]);
}
}
if (logEvents) log("touchStart", ev, true);
update_background(ev);
}
function move_handler(ev) {
// Note: if the user makes more than one "simultaneous" touches, most browsers
// fire at least one touchmove event and some will fire several touchmoves.
// Consequently, an application might want to "ignore" some touchmoves.
//
// This function sets the target element's outline to "dashed" to visualy
// indicate the target received a move event.
//
ev.preventDefault();
if (logEvents) log("touchMove", ev, false);
// To avoid too much color flashing many touchmove events are started,
// don't update the background if two touch points are active
if (!(ev.touches.length == 2 && ev.targetTouches.length == 2))
update_background(ev);
// Set the target element's outline to dashed to give a clear visual
// indication the element received a move event.
ev.target.style.outline = "dashed";
// Check this event for 2-touch Move/Pinch/Zoom gesture
handle_pinch_zoom(ev);
}
function end_handler(ev) {
ev.preventDefault();
if (logEvents) log(ev.type, ev, false);
if (ev.targetTouches.length == 0) {
// Restore background and outline to original values
ev.target.style.background = "white";
ev.target.style.outline = "1px solid black";
}
}
function set_handlers(name) {
// Install event handlers for the given element
var el=document.getElementById(name);
el.ontouchstart = start_handler;
el.ontouchmove = move_handler;
// Use same handler for touchcancel and touchend
el.ontouchcancel = end_handler;
el.ontouchend = end_handler;
}
function init() {
set_handlers("target1");
set_handlers("target2");
set_handlers("target3");
set_handlers("target4");
}
</script>
<body onload="init();">
<h1>Multi-touch interaction</h1>
<!-- Create some boxes to test various gestures. -->
<div id="target1"> Tap, Hold or Swipe me 1</div>
<div id="target2"> Tap, Hold or Swipe me 2</div>
<div id="target3"> Tap, Hold or Swipe me 3</div>
<div id="target4"> Tap, Hold or Swipe me 4</div>
<!-- UI for logging/debugging -->
<button id="log" onclick="enableLog(event);">Start/Stop event logging</button>
<button id="clearlog" onclick="clearLog(event);">Clear the log</button>
<p></p>
<output></output>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Basic View Transitions API demo</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Slab:wght@500&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<h1 class="title">Basic View Transitions API demo</h1>
<main>
<section class="thumbs">
</section>
<section class="gallery-view">
<figure>
<img>
<figcaption><div class="caption-text"></div></figcaption>
</figure>
</section>
</main>
<footer class="footer">
<a href="https://glitch.com/edit/#!/basic-view-transitions-api">
See source code
</a>
</footer>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
/* resets */
figure {
margin: 0
}
/* layout */
body {
width: 70%;
max-width: 700px;
margin: 0 auto;
}
main {
display: flex;
}
img {
border: 1px solid #999;
}
.thumbs img {
display: block;
margin: 10px;
border-radius: 7px;
opacity: 0.7;
}
a {
outline: 0;
}
.thumbs a:hover img, .thumbs a:focus img {
opacity: 1;
}
.thumbs img:first-child {
margin-top: 0px;
}
.gallery-view img {
max-width: 100%;
margin-right: 10px;
border-radius: 7px;
}
footer, figcaption {
position: absolute;
padding: 5px 10px;
background-color: rgba(255,255,255,0.5);
}
footer {
bottom: 3px;
left: 3px;
}
figure {
position: relative;
}
figcaption {
top: 0px;
right: -2px;
border: 1px solid #999;
border-radius: 0 7px 0 7px;
}
/* text */
h1, figcaption, a {
font-family: 'Roboto Slab', serif;
}
h1 {
text-align: center;
}
/* media queries */
@media (max-width: 980px) {
body {
width: 90%;
}
}
@media (max-width: 700px) {
body {
width: 98%;
}
main {
flex-direction: column;
}
.thumbs {
display: flex;
align-items: space-between;
justify-content: space-between;
}
.thumbs img {
margin: 0 0 10px 0;
}
}
/* View Transitions CSS */
::view-transition-old(root),
::view-transition-new(root) {
animation-duration: 0.5s;
}
figcaption {
view-transition-name: figure-caption;
}
/* Simple final style */
::view-transition-old(figure-caption),
::view-transition-new(figure-caption) {
height: 100%;
}
/* Alternative custom animation style */
/* @keyframes grow-x {
from { transform: scaleX(0); }
to { transform: scaleX(1); }
}
@keyframes shrink-x {
from { transform: scaleX(1); }
to { transform: scaleX(0); }
}
::view-transition-old(figure-caption),
::view-transition-new(figure-caption) {
height: auto;
right: 0;
left: auto;
transform-origin: right center;
}
::view-transition-old(figure-caption) {
animation: 0.25s linear both shrink-x;
}
::view-transition-new(figure-caption) {
animation: 0.25s 0.25s linear both grow-x;
} */ | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
const imageData = [
{
'name': 'Jungle coast',
'file': 'jungle-coast',
},
{
'name': 'Bird in the tree',
'file': 'tree-bird',
},
{
'name': 'A view from the sky',
'file': 'view-from-the-sky',
},
{
'name': 'The view across the water',
'file': 'watery-view',
}
]
const thumbs = document.querySelector('.thumbs');
const galleryImg = document.querySelector('.gallery-view img');
const galleryCaption = document.querySelector('.gallery-view figcaption');
function init() {
imageData.forEach(data => {
const img = document.createElement('img');
const a = document.createElement('a');
a.href = "#";
a.title = `Click to load ${data.name} in main gallery view`;
img.alt = data.name;
img.src = `images/${ data.file }_th.jpg`;
a.appendChild(img);
thumbs.appendChild(a);
a.addEventListener('click', updateView);
a.addEventListener('keypress', updateView);
})
galleryImg.src = `images/${ imageData[0].file }.jpg`;
galleryCaption.textContent = imageData[0].name;
}
function updateView(event) {
// Handle the difference in whether the event is fired on the <a> or the <img>
const targetIdentifier = event.target.firstChild || event.target;
const displayNewImage = () => {
const mainSrc = `${targetIdentifier.src.split("_th.jpg")[0]}.jpg`;
galleryImg.src = mainSrc;
galleryCaption.textContent = targetIdentifier.alt;
};
// Fallback for browsers that don't support View Transitions:
if (!document.startViewTransition) {
displayNewImage();
return;
}
// With View Transitions:
const transition = document.startViewTransition(() => displayNewImage());
}
init(); | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Web Animations API implicit keyframes</title>
<style>
html {
height: 100%;
}
body {
margin: 0;
height: inherit;
display: flex;
justify-content: center;
align-items: center;
}
div {
width: 150px;
height: 100px;
background-color: red;
border: 10px solid black;
border-radius: 10px;
}
</style>
</head>
<body>
<div>
</div>
<script>
const divElem = document.querySelector('div');
let rotate360 = [
{ transform: 'rotate(360deg)' }
];
let slowInfinite = {
duration: 5000,
iterations: Infinity
}
divElem.animate( rotate360, slowInfinite );
</script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!doctype html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Web Animations API replace indefinite animations</title>
<style>
html {
height: 100%;
}
body {
margin: 0;
height: inherit;
}
div {
width: 150px;
height: 100px;
background-color: red;
border: 10px solid black;
border-radius: 10px;
}
p {
position: absolute;
width: 300px;
right: 10px;
bottom: 10px;
}
</style>
</head>
<body>
<p>Click, tap, or press the space bar to start the animation (disabled by default to protect those who suffer migraines when experiencing such animations).</p>
<div>
</div>
<script>
const divElem = document.querySelector('div');
document.addEventListener('keypress', function(e) {
if(e.key === ' ') {
startAnimation();
}
});
document.addEventListener('click', startAnimation);
function startAnimation() {
document.body.addEventListener('mousemove', evt => {
let anim = divElem.animate(
{ transform: `translate(${ evt.clientX}px, ${evt.clientY}px)` },
{ duration: 500, fill: 'forwards' }
);
// commitStyles() writes the end state of the animation to the animated
//element inside a style attribute
anim.commitStyles();
// If you explicitly want the animations to be retained, then you can invoke persist()
// But don't do this unless you really need to — having a huge list of animations
// persisted can cause a memory leak
//anim.persist()
// onremove allows you to run an event handler that fires when the animation
// was removed (i.e. put into an active replace state)
anim.onremove = function() {
console.log('Animation removed');
}
// replaceState allows you to query an element to see what its replace state is
// It will be active by default, or persisted if persist() was invoked
console.log(anim.replaceState);
});
}
</script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
# Web animations API demos
Some simple demos to show Web Animations API features.
## Implicit to/from keyframes
That 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:
```
let rotate360 = [
{ transform: 'rotate(360deg)' }
];
```
[See the demo live](https://mdn.github.io/dom-examples/web-animations-api/implicit-keyframes.html).
## Automatically removing filling animations
It 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.
[See a live demo of this](https://mdn.github.io/dom-examples/web-animations-api/replace-indefinite-animations.html).
The related JavaScript features are as follows:
* `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.
* `animation.onremove` — allows you to run an event handler that fires when the animation is removed (i.e., put into an active replace state).
* `animation.persist()` — when you explicitly want animations to be retained, then invoke persist().
* `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.
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
@font-face {
font-family: 'zillaslab';
src: url('https://s3-us-west-2.amazonaws.com/s.cdpn.io/858/ZillaSlab.woff2') format('woff2');
}
:root {
--black: hsl(0, 0%, 16%);
--white: hsl(0,0%,97%);
--blue: hsl(198, 100%, 66%);
--teal: hsl(198, 43%, 42%);
--lightYellow: hsl(43, 100%, 92%);
--grey: hsl(0, 0%, 80%);
--unit: 1.2rem;
}
body {
padding: var(--unit);
background-color: var(--white);
font-family: 'Arial', sans-serif; font-size: 100%;
color: var(--black); line-height: 1.3;
}
/* page partials */
footer {
padding: var(--unit);
margin-top: calc(var(--unit)*2);
border-top: 1px solid var(--grey);
}
footer p {
margin: 0px; text-align: center;
}
/* base styles */
h1, h2 {
font-family: "zillaslab", serif;
}
h2 {
padding: calc(var(--unit)/2);
background-color: var(--black);
color: var(--white); font-weight: normal;
}
p {}
a {
border: 1px solid var(--teal);
border-width: 0px 0px 1px 0px;
color: var(--teal);
text-decoration: none;
}
a:hover {
border-width: 1px 0px 0px 0px;
}
nav ul {
display: flex; justify-content: space-between;
margin: 0px; padding: 0px;
list-style: none;
}
nav li {margin: 0px; padding: 0px;}
dl {display: flex; flex-wrap: wrap;}
dt, dd {padding: 2%; box-sizing: border-box;}
dt {width: 30%; font-weight: bold; text-align: right;}
dd {width: 66%; margin: 0px;}
code {
background-color: var(--lightYellow);
font-family:monospace; font-size:110%;
letter-spacing:0.5px;
}
pre {
padding: var(--unit);
background-color: var(--grey);
border-left: 4px solid var(--teal);
white-space: pre-wrap;
overflow-wrap: break-word;
tab-size: 4; font-size: 86%;
}
pre code {
background: none;
} | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Wake Lock Demo</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css">
<!-- my styles -->
<link rel="stylesheet" href="moz.css">
<style>
#status {
width: 50vw; min-width: 500px;
margin-top: 20px;
}
#status h2 {margin-top: 0px;}
#status p {padding-left: 20px;}
[data-status="off"] ~ #status {
border: 2px solid red;
}
[data-status="on"] ~ #status {
border: 2px solid green;
}
</style>
<script src="script.js" defer></script>
</head>
<body>
<header>
<h1>Wake Lock Demo</h1>
</header>
<p>The button below changes depending on whether wake lock is active or not.</p>
<button data-status="off">Turn Wake Lock ON</button>
<section id="status">
<h2>Wake Lock Status</h2>
<p></p>
</section>
<p>Wake lock will automatically release if if the tab becomes inactive.</p>
<p>To re-activate the wake lock automatically when the tab becomes active again, check this box: <input type="checkbox" id="reaquire" /></p>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
console.clear();
// status paragraph
const statusElem = document.querySelector('#status p');
// toggle button
const wakeButton = document.querySelector('[data-status]');
// checkbox
const reaquireCheck = document.querySelector('#reaquire');
// change button and status if wakelock becomes aquired or is released
const changeUI = (status = 'acquired') => {
const acquired = status === 'acquired' ? true : false;
wakeButton.dataset.status = acquired ? 'on' : 'off';
wakeButton.textContent = `Turn Wake Lock ${acquired ? 'OFF' : 'ON'}`;
statusElem.textContent = `Wake Lock ${acquired ? 'is active!' : 'has been released.'}`;
}
// test support
let isSupported = false;
if ('wakeLock' in navigator) {
isSupported = true;
statusElem.textContent = 'Screen Wake Lock API supported 🎉';
} else {
wakeButton.disabled = true;
statusElem.textContent = 'Wake lock is not supported by this browser.';
}
if (isSupported) {
// create a reference for the wake lock
let wakeLock = null;
// create an async function to request a wake lock
const requestWakeLock = async () => {
try {
wakeLock = await navigator.wakeLock.request('screen');
// change up our interface to reflect wake lock active
changeUI();
// listen for our release event
wakeLock.onrelease = function(ev) {
console.log(ev);
}
wakeLock.addEventListener('release', () => {
// if wake lock is released alter the button accordingly
changeUI('released');
});
} catch (err) {
// if wake lock request fails - usually system related, such as battery
wakeButton.dataset.status = 'off';
wakeButton.textContent = 'Turn Wake Lock ON';
statusElem.textContent = `${err.name}, ${err.message}`;
}
} // requestWakeLock()
// if we click our button
wakeButton.addEventListener('click', () => {
// if wakelock is off request it
if (wakeButton.dataset.status === 'off') {
requestWakeLock()
} else { // if it's on release it
wakeLock.release()
.then(() => {
wakeLock = null;
})
}
})
const handleVisibilityChange = () => {
if (wakeLock !== null && document.visibilityState === 'visible') {
requestWakeLock();
}
}
reaquireCheck.addEventListener('change', () => {
if (reaquireCheck.checked) {
document.addEventListener('visibilitychange', handleVisibilityChange);
} else {
document.removeEventListener('visibilitychange', handleVisibilityChange);
}
});
} // isSupported
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
# MDN WebGL examples
This folder is home to examples for the MDN Web Docs content about
the [WebGL API](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API),
which is used for 2D and 3D graphics on the web.
Specifically, each of these examples pairs with an article in the MDN
[WebGL tutorial](https://developer.mozilla.org/en-US/docs/Web/API/WebGL_API/Tutorial).
## The examples
- [Sample 1](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample1/)
- [Sample 2](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample2/)
- [Sample 3](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample3/)
- [Sample 4](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample4/)
- [Sample 5](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample5/)
- [Sample 6](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample6/)
- [Sample 7](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample7/)
- [Sample 8](https://mdn.github.io/dom-examples/webgl-examples/tutorial/sample8/)
### Additional example
- [Tetrahedron](https://mdn.github.io/dom-examples/webgl-examples/tutorial/tetrahedron/)
## Installing and testing
If you choose to fork or clone these examples to experiment with them,
be aware that WebGL requires that any textures or other binary data
be loaded from a secure context, which means you can't just use most
of these samples from a `file:///` URL. Instead, you need to run a
local web server, or post them to a secure server online.
See 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).
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function initBuffers(gl) {
const positionBuffer = initPositionBuffer(gl);
const colorBuffer = initColorBuffer(gl);
const indexBuffer = initIndexBuffer(gl);
return {
position: positionBuffer,
color: colorBuffer,
indices: indexBuffer,
};
}
function initPositionBuffer(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [
// Front face
-1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,
];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return positionBuffer;
}
function initColorBuffer(gl) {
const faceColors = [
[1.0, 1.0, 1.0, 1.0], // Front face: white
[1.0, 0.0, 0.0, 1.0], // Back face: red
[0.0, 1.0, 0.0, 1.0], // Top face: green
[0.0, 0.0, 1.0, 1.0], // Bottom face: blue
[1.0, 1.0, 0.0, 1.0], // Right face: yellow
[1.0, 0.0, 1.0, 1.0], // Left face: purple
];
// Convert the array of colors into a table for all the vertices.
var colors = [];
for (var j = 0; j < faceColors.length; ++j) {
const c = faceColors[j];
// Repeat each color four times for the four vertices of the face
colors = colors.concat(c, c, c, c);
}
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
return colorBuffer;
}
function initIndexBuffer(gl) {
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// This array defines each face as two triangles, using the
// indices into the vertex array to specify each triangle's
// position.
const indices = [
0,
1,
2,
0,
2,
3, // front
4,
5,
6,
4,
6,
7, // back
8,
9,
10,
8,
10,
11, // top
12,
13,
14,
12,
14,
15, // bottom
16,
17,
18,
16,
18,
19, // right
20,
21,
22,
20,
22,
23, // left
];
// Now send the element array to GL
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices),
gl.STATIC_DRAW
);
return indexBuffer;
}
export { initBuffers };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function drawScene(gl, programInfo, buffers, cubeRotation) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation, // amount to rotate in radians
[0, 0, 1]
); // axis to rotate around (Z)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.7, // amount to rotate in radians
[0, 1, 0]
); // axis to rotate around (Y)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.3, // amount to rotate in radians
[1, 0, 0]
); // axis to rotate around (X)
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
setPositionAttribute(gl, buffers, programInfo);
setColorAttribute(gl, buffers, programInfo);
// Tell WebGL which indices to use to index the vertices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
const offset = 0;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
}
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
function setPositionAttribute(gl, buffers, programInfo) {
const numComponents = 3;
const type = gl.FLOAT; // the data in the buffer is 32bit floats
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the colors from the color buffer
// into the vertexColor attribute.
function setColorAttribute(gl, buffers, programInfo) {
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);
}
export { drawScene };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"
defer
></script>
<script src="webgl-demo.js" type="module"></script>
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
import { initBuffers } from "./init-buffers.js";
import { drawScene } from "./draw-scene.js";
let cubeRotation = 0.0;
let deltaTime = 0;
main();
//
// start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (gl === null) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec4 aVertexColor;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying lowp vec4 vColor;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vColor = aVertexColor;
}
`;
// Fragment shader program
const fsSource = `
varying lowp vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attributes our shader program is using
// for aVertexPosition, aVertexColor and also
// look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
vertexColor: gl.getAttribLocation(shaderProgram, "aVertexColor"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram,
"uProjectionMatrix"
),
modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
let then = 0;
// Draw the scene repeatedly
function render(now) {
now *= 0.001; // convert to seconds
deltaTime = now - then;
then = now;
drawScene(gl, programInfo, buffers, cubeRotation);
cubeRotation += deltaTime;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert(
`Unable to initialize the shader program: ${gl.getProgramInfoLog(
shaderProgram
)}`
);
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(
`An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`
);
gl.deleteShader(shader);
return null;
}
return shader;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function initBuffers(gl) {
const positionBuffer = initPositionBuffer(gl);
const textureCoordBuffer = initTextureBuffer(gl);
const indexBuffer = initIndexBuffer(gl);
return {
position: positionBuffer,
textureCoord: textureCoordBuffer,
indices: indexBuffer,
};
}
function initPositionBuffer(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [
// Front face
-1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,
];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return positionBuffer;
}
function initColorBuffer(gl) {
const faceColors = [
[1.0, 1.0, 1.0, 1.0], // Front face: white
[1.0, 0.0, 0.0, 1.0], // Back face: red
[0.0, 1.0, 0.0, 1.0], // Top face: green
[0.0, 0.0, 1.0, 1.0], // Bottom face: blue
[1.0, 1.0, 0.0, 1.0], // Right face: yellow
[1.0, 0.0, 1.0, 1.0], // Left face: purple
];
// Convert the array of colors into a table for all the vertices.
var colors = [];
for (var j = 0; j < faceColors.length; ++j) {
const c = faceColors[j];
// Repeat each color four times for the four vertices of the face
colors = colors.concat(c, c, c, c);
}
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
return colorBuffer;
}
function initIndexBuffer(gl) {
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// This array defines each face as two triangles, using the
// indices into the vertex array to specify each triangle's
// position.
const indices = [
0,
1,
2,
0,
2,
3, // front
4,
5,
6,
4,
6,
7, // back
8,
9,
10,
8,
10,
11, // top
12,
13,
14,
12,
14,
15, // bottom
16,
17,
18,
16,
18,
19, // right
20,
21,
22,
20,
22,
23, // left
];
// Now send the element array to GL
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices),
gl.STATIC_DRAW
);
return indexBuffer;
}
function initTextureBuffer(gl) {
const textureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
const textureCoordinates = [
// Front
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Back
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Top
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Bottom
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Right
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Left
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
];
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(textureCoordinates),
gl.STATIC_DRAW
);
return textureCoordBuffer;
}
export { initBuffers };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function drawScene(gl, programInfo, buffers, texture, cubeRotation) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation, // amount to rotate in radians
[0, 0, 1]
); // axis to rotate around (Z)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.7, // amount to rotate in radians
[0, 1, 0]
); // axis to rotate around (Y)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.3, // amount to rotate in radians
[1, 0, 0]
); // axis to rotate around (X)
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
setPositionAttribute(gl, buffers, programInfo);
setTextureAttribute(gl, buffers, programInfo);
// Tell WebGL which indices to use to index the vertices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
// Tell WebGL we want to affect texture unit 0
gl.activeTexture(gl.TEXTURE0);
// Bind the texture to texture unit 0
gl.bindTexture(gl.TEXTURE_2D, texture);
// Tell the shader we bound the texture to texture unit 0
gl.uniform1i(programInfo.uniformLocations.uSampler, 0);
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
const offset = 0;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
}
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
function setPositionAttribute(gl, buffers, programInfo) {
const numComponents = 3;
const type = gl.FLOAT; // the data in the buffer is 32bit floats
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the colors from the color buffer
// into the vertexColor attribute.
function setColorAttribute(gl, buffers, programInfo) {
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);
}
// tell webgl how to pull out the texture coordinates from buffer
function setTextureAttribute(gl, buffers, programInfo) {
const num = 2; // every coordinate composed of 2 values
const type = gl.FLOAT; // the data in the buffer is 32-bit float
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set to the next
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);
gl.vertexAttribPointer(
programInfo.attribLocations.textureCoord,
num,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);
}
export { drawScene };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"
defer
></script>
<script src="webgl-demo.js" type="module"></script>
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
import { initBuffers } from "./init-buffers.js";
import { drawScene } from "./draw-scene.js";
let cubeRotation = 0.0;
let deltaTime = 0;
main();
//
// start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (gl === null) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec2 aTextureCoord;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying highp vec2 vTextureCoord;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vTextureCoord = aTextureCoord;
}
`;
// Fragment shader program
const fsSource = `
varying highp vec2 vTextureCoord;
uniform sampler2D uSampler;
void main(void) {
gl_FragColor = texture2D(uSampler, vTextureCoord);
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attributes our shader program is using
// for aVertexPosition, aVertexColor and also
// look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
textureCoord: gl.getAttribLocation(shaderProgram, "aTextureCoord"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram,
"uProjectionMatrix"
),
modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
uSampler: gl.getUniformLocation(shaderProgram, "uSampler"),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
// Load texture
const texture = loadTexture(gl, "cubetexture.png");
// Flip image pixels into the bottom-to-top order that WebGL expects.
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
let then = 0;
// Draw the scene repeatedly
function render(now) {
now *= 0.001; // convert to seconds
deltaTime = now - then;
then = now;
drawScene(gl, programInfo, buffers, texture, cubeRotation);
cubeRotation += deltaTime;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert(
`Unable to initialize the shader program: ${gl.getProgramInfoLog(
shaderProgram
)}`
);
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(
`An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`
);
gl.deleteShader(shader);
return null;
}
return shader;
}
//
// Initialize a texture and load an image.
// When the image finished loading copy it into the texture.
//
function loadTexture(gl, url) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Because images have to be downloaded over the internet
// they might take a moment until they are ready.
// Until then put a single pixel in the texture so we can
// use it immediately. When the image has finished downloading
// we'll update the texture with the contents of the image.
const level = 0;
const internalFormat = gl.RGBA;
const width = 1;
const height = 1;
const border = 0;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
width,
height,
border,
srcFormat,
srcType,
pixel
);
const image = new Image();
image.onload = () => {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
srcFormat,
srcType,
image
);
// WebGL1 has different requirements for power of 2 images
// vs non power of 2 images so check if the image is a
// power of 2 in both dimensions.
if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
// Yes, it's a power of 2. Generate mips.
gl.generateMipmap(gl.TEXTURE_2D);
} else {
// No, it's not a power of 2. Turn off mips and set
// wrapping to clamp to edge
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
};
image.src = url;
return texture;
}
function isPowerOf2(value) {
return (value & (value - 1)) === 0;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function initBuffers(gl) {
const positionBuffer = initPositionBuffer(gl);
const textureCoordBuffer = initTextureBuffer(gl);
const indexBuffer = initIndexBuffer(gl);
const normalBuffer = initNormalBuffer(gl);
return {
position: positionBuffer,
normal: normalBuffer,
textureCoord: textureCoordBuffer,
indices: indexBuffer,
};
}
function initPositionBuffer(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [
// Front face
-1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,
];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return positionBuffer;
}
function initColorBuffer(gl) {
const faceColors = [
[1.0, 1.0, 1.0, 1.0], // Front face: white
[1.0, 0.0, 0.0, 1.0], // Back face: red
[0.0, 1.0, 0.0, 1.0], // Top face: green
[0.0, 0.0, 1.0, 1.0], // Bottom face: blue
[1.0, 1.0, 0.0, 1.0], // Right face: yellow
[1.0, 0.0, 1.0, 1.0], // Left face: purple
];
// Convert the array of colors into a table for all the vertices.
var colors = [];
for (var j = 0; j < faceColors.length; ++j) {
const c = faceColors[j];
// Repeat each color four times for the four vertices of the face
colors = colors.concat(c, c, c, c);
}
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
return colorBuffer;
}
function initIndexBuffer(gl) {
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// This array defines each face as two triangles, using the
// indices into the vertex array to specify each triangle's
// position.
const indices = [
0,
1,
2,
0,
2,
3, // front
4,
5,
6,
4,
6,
7, // back
8,
9,
10,
8,
10,
11, // top
12,
13,
14,
12,
14,
15, // bottom
16,
17,
18,
16,
18,
19, // right
20,
21,
22,
20,
22,
23, // left
];
// Now send the element array to GL
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices),
gl.STATIC_DRAW
);
return indexBuffer;
}
function initTextureBuffer(gl) {
const textureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
const textureCoordinates = [
// Front
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Back
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Top
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Bottom
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Right
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Left
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
];
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(textureCoordinates),
gl.STATIC_DRAW
);
return textureCoordBuffer;
}
function initNormalBuffer(gl) {
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
const vertexNormals = [
// Front
0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,
// Back
0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0,
// Top
0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
// Bottom
0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0,
// Right
1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,
// Left
-1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0,
];
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(vertexNormals),
gl.STATIC_DRAW
);
return normalBuffer;
}
export { initBuffers };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function drawScene(gl, programInfo, buffers, texture, cubeRotation) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation, // amount to rotate in radians
[0, 0, 1]
); // axis to rotate around (Z)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.7, // amount to rotate in radians
[0, 1, 0]
); // axis to rotate around (Y)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.3, // amount to rotate in radians
[1, 0, 0]
); // axis to rotate around (X)
const normalMatrix = mat4.create();
mat4.invert(normalMatrix, modelViewMatrix);
mat4.transpose(normalMatrix, normalMatrix);
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
setPositionAttribute(gl, buffers, programInfo);
setTextureAttribute(gl, buffers, programInfo);
// Tell WebGL which indices to use to index the vertices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
setNormalAttribute(gl, buffers, programInfo);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.normalMatrix,
false,
normalMatrix
);
// Tell WebGL we want to affect texture unit 0
gl.activeTexture(gl.TEXTURE0);
// Bind the texture to texture unit 0
gl.bindTexture(gl.TEXTURE_2D, texture);
// Tell the shader we bound the texture to texture unit 0
gl.uniform1i(programInfo.uniformLocations.uSampler, 0);
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
const offset = 0;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
}
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
function setPositionAttribute(gl, buffers, programInfo) {
const numComponents = 3;
const type = gl.FLOAT; // the data in the buffer is 32bit floats
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the colors from the color buffer
// into the vertexColor attribute.
function setColorAttribute(gl, buffers, programInfo) {
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);
}
// tell webgl how to pull out the texture coordinates from buffer
function setTextureAttribute(gl, buffers, programInfo) {
const num = 2; // every coordinate composed of 2 values
const type = gl.FLOAT; // the data in the buffer is 32-bit float
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set to the next
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);
gl.vertexAttribPointer(
programInfo.attribLocations.textureCoord,
num,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);
}
// Tell WebGL how to pull out the normals from
// the normal buffer into the vertexNormal attribute.
function setNormalAttribute(gl, buffers, programInfo) {
const numComponents = 3;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexNormal,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexNormal);
}
export { drawScene };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"
defer
></script>
<script src="webgl-demo.js" type="module"></script>
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
import { initBuffers } from "./init-buffers.js";
import { drawScene } from "./draw-scene.js";
let cubeRotation = 0.0;
let deltaTime = 0;
main();
//
// start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (gl === null) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
uniform mat4 uNormalMatrix;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying highp vec2 vTextureCoord;
varying highp vec3 vLighting;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vTextureCoord = aTextureCoord;
// Apply lighting effect
highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);
highp vec3 directionalLightColor = vec3(1, 1, 1);
highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));
highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);
highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);
vLighting = ambientLight + (directionalLightColor * directional);
}
`;
// Fragment shader program
const fsSource = `
varying highp vec2 vTextureCoord;
varying highp vec3 vLighting;
uniform sampler2D uSampler;
void main(void) {
highp vec4 texelColor = texture2D(uSampler, vTextureCoord);
gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attributes our shader program is using
// for aVertexPosition, aVertexColor and also
// look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
vertexNormal: gl.getAttribLocation(shaderProgram, "aVertexNormal"),
textureCoord: gl.getAttribLocation(shaderProgram, "aTextureCoord"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram,
"uProjectionMatrix"
),
modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
normalMatrix: gl.getUniformLocation(shaderProgram, "uNormalMatrix"),
uSampler: gl.getUniformLocation(shaderProgram, "uSampler"),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
// Load texture
const texture = loadTexture(gl, "cubetexture.png");
// Flip image pixels into the bottom-to-top order that WebGL expects.
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
let then = 0;
// Draw the scene repeatedly
function render(now) {
now *= 0.001; // convert to seconds
deltaTime = now - then;
then = now;
drawScene(gl, programInfo, buffers, texture, cubeRotation);
cubeRotation += deltaTime;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert(
`Unable to initialize the shader program: ${gl.getProgramInfoLog(
shaderProgram
)}`
);
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(
`An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`
);
gl.deleteShader(shader);
return null;
}
return shader;
}
//
// Initialize a texture and load an image.
// When the image finished loading copy it into the texture.
//
function loadTexture(gl, url) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Because images have to be downloaded over the internet
// they might take a moment until they are ready.
// Until then put a single pixel in the texture so we can
// use it immediately. When the image has finished downloading
// we'll update the texture with the contents of the image.
const level = 0;
const internalFormat = gl.RGBA;
const width = 1;
const height = 1;
const border = 0;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
width,
height,
border,
srcFormat,
srcType,
pixel
);
const image = new Image();
image.onload = () => {
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
srcFormat,
srcType,
image
);
// WebGL1 has different requirements for power of 2 images
// vs non power of 2 images so check if the image is a
// power of 2 in both dimensions.
if (isPowerOf2(image.width) && isPowerOf2(image.height)) {
// Yes, it's a power of 2. Generate mips.
gl.generateMipmap(gl.TEXTURE_2D);
} else {
// No, it's not a power of 2. Turn off mips and set
// wrapping to clamp to edge
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
};
image.src = url;
return texture;
}
function isPowerOf2(value) {
return (value & (value - 1)) === 0;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function initBuffers(gl) {
const positionBuffer = initPositionBuffer(gl);
const textureCoordBuffer = initTextureBuffer(gl);
const indexBuffer = initIndexBuffer(gl);
const normalBuffer = initNormalBuffer(gl);
return {
position: positionBuffer,
normal: normalBuffer,
textureCoord: textureCoordBuffer,
indices: indexBuffer,
};
}
function initPositionBuffer(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positions = [
// Front face
-1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, -1.0, 1.0, -1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0, -1.0, -1.0, 1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0,
];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return positionBuffer;
}
function initColorBuffer(gl) {
const faceColors = [
[1.0, 1.0, 1.0, 1.0], // Front face: white
[1.0, 0.0, 0.0, 1.0], // Back face: red
[0.0, 1.0, 0.0, 1.0], // Top face: green
[0.0, 0.0, 1.0, 1.0], // Bottom face: blue
[1.0, 1.0, 0.0, 1.0], // Right face: yellow
[1.0, 0.0, 1.0, 1.0], // Left face: purple
];
// Convert the array of colors into a table for all the vertices.
var colors = [];
for (var j = 0; j < faceColors.length; ++j) {
const c = faceColors[j];
// Repeat each color four times for the four vertices of the face
colors = colors.concat(c, c, c, c);
}
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
return colorBuffer;
}
function initIndexBuffer(gl) {
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// This array defines each face as two triangles, using the
// indices into the vertex array to specify each triangle's
// position.
const indices = [
0,
1,
2,
0,
2,
3, // front
4,
5,
6,
4,
6,
7, // back
8,
9,
10,
8,
10,
11, // top
12,
13,
14,
12,
14,
15, // bottom
16,
17,
18,
16,
18,
19, // right
20,
21,
22,
20,
22,
23, // left
];
// Now send the element array to GL
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices),
gl.STATIC_DRAW
);
return indexBuffer;
}
function initTextureBuffer(gl) {
const textureCoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, textureCoordBuffer);
const textureCoordinates = [
// Front
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Back
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Top
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Bottom
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Right
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
// Left
0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0,
];
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(textureCoordinates),
gl.STATIC_DRAW
);
return textureCoordBuffer;
}
function initNormalBuffer(gl) {
const normalBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer);
const vertexNormals = [
// Front
0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0,
// Back
0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0,
// Top
0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0,
// Bottom
0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0,
// Right
1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0,
// Left
-1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0, -1.0, 0.0, 0.0,
];
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array(vertexNormals),
gl.STATIC_DRAW
);
return normalBuffer;
}
export { initBuffers };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function drawScene(gl, programInfo, buffers, texture, cubeRotation) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation, // amount to rotate in radians
[0, 0, 1]
); // axis to rotate around (Z)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.7, // amount to rotate in radians
[0, 1, 0]
); // axis to rotate around (Y)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
cubeRotation * 0.3, // amount to rotate in radians
[1, 0, 0]
); // axis to rotate around (X)
const normalMatrix = mat4.create();
mat4.invert(normalMatrix, modelViewMatrix);
mat4.transpose(normalMatrix, normalMatrix);
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
setPositionAttribute(gl, buffers, programInfo);
setTextureAttribute(gl, buffers, programInfo);
// Tell WebGL which indices to use to index the vertices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
setNormalAttribute(gl, buffers, programInfo);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.normalMatrix,
false,
normalMatrix
);
// Tell WebGL we want to affect texture unit 0
gl.activeTexture(gl.TEXTURE0);
// Bind the texture to texture unit 0
gl.bindTexture(gl.TEXTURE_2D, texture);
// Tell the shader we bound the texture to texture unit 0
gl.uniform1i(programInfo.uniformLocations.uSampler, 0);
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
const offset = 0;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
}
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
function setPositionAttribute(gl, buffers, programInfo) {
const numComponents = 3;
const type = gl.FLOAT; // the data in the buffer is 32bit floats
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the colors from the color buffer
// into the vertexColor attribute.
function setColorAttribute(gl, buffers, programInfo) {
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);
}
// tell webgl how to pull out the texture coordinates from buffer
function setTextureAttribute(gl, buffers, programInfo) {
const num = 2; // every coordinate composed of 2 values
const type = gl.FLOAT; // the data in the buffer is 32-bit float
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set to the next
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.textureCoord);
gl.vertexAttribPointer(
programInfo.attribLocations.textureCoord,
num,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.textureCoord);
}
// Tell WebGL how to pull out the normals from
// the normal buffer into the vertexNormal attribute.
function setNormalAttribute(gl, buffers, programInfo) {
const numComponents = 3;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.normal);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexNormal,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexNormal);
}
export { drawScene };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"
defer
></script>
<script src="webgl-demo.js" type="module"></script>
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
import { initBuffers } from "./init-buffers.js";
import { drawScene } from "./draw-scene.js";
let cubeRotation = 0.0;
let deltaTime = 0;
// will set to true when video can be copied to texture
let copyVideo = false;
main();
//
// start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (gl === null) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
uniform mat4 uNormalMatrix;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying highp vec2 vTextureCoord;
varying highp vec3 vLighting;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vTextureCoord = aTextureCoord;
// Apply lighting effect
highp vec3 ambientLight = vec3(0.3, 0.3, 0.3);
highp vec3 directionalLightColor = vec3(1, 1, 1);
highp vec3 directionalVector = normalize(vec3(0.85, 0.8, 0.75));
highp vec4 transformedNormal = uNormalMatrix * vec4(aVertexNormal, 1.0);
highp float directional = max(dot(transformedNormal.xyz, directionalVector), 0.0);
vLighting = ambientLight + (directionalLightColor * directional);
}
`;
// Fragment shader program
const fsSource = `
varying highp vec2 vTextureCoord;
varying highp vec3 vLighting;
uniform sampler2D uSampler;
void main(void) {
highp vec4 texelColor = texture2D(uSampler, vTextureCoord);
gl_FragColor = vec4(texelColor.rgb * vLighting, texelColor.a);
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attributes our shader program is using
// for aVertexPosition, aVertexColor and also
// look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
vertexNormal: gl.getAttribLocation(shaderProgram, "aVertexNormal"),
textureCoord: gl.getAttribLocation(shaderProgram, "aTextureCoord"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram,
"uProjectionMatrix"
),
modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
normalMatrix: gl.getUniformLocation(shaderProgram, "uNormalMatrix"),
uSampler: gl.getUniformLocation(shaderProgram, "uSampler"),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
const texture = initTexture(gl);
const video = setupVideo("Firefox.mp4");
// Flip image pixels into the bottom-to-top order that WebGL expects.
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
let then = 0;
// Draw the scene repeatedly
function render(now) {
now *= 0.001; // convert to seconds
deltaTime = now - then;
then = now;
if (copyVideo) {
updateTexture(gl, texture, video);
}
drawScene(gl, programInfo, buffers, texture, cubeRotation);
cubeRotation += deltaTime;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert(
`Unable to initialize the shader program: ${gl.getProgramInfoLog(
shaderProgram
)}`
);
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(
`An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`
);
gl.deleteShader(shader);
return null;
}
return shader;
}
function initTexture(gl) {
const texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
// Because video has to be download over the internet
// they might take a moment until it's ready so
// put a single pixel in the texture so we can
// use it immediately.
const level = 0;
const internalFormat = gl.RGBA;
const width = 1;
const height = 1;
const border = 0;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
const pixel = new Uint8Array([0, 0, 255, 255]); // opaque blue
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
width,
height,
border,
srcFormat,
srcType,
pixel
);
// Turn off mips and set wrapping to clamp to edge so it
// will work regardless of the dimensions of the video.
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
return texture;
}
function updateTexture(gl, texture, video) {
const level = 0;
const internalFormat = gl.RGBA;
const srcFormat = gl.RGBA;
const srcType = gl.UNSIGNED_BYTE;
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2D(
gl.TEXTURE_2D,
level,
internalFormat,
srcFormat,
srcType,
video
);
}
function setupVideo(url) {
const video = document.createElement("video");
let playing = false;
let timeupdate = false;
video.playsInline = true;
video.muted = true;
video.loop = true;
// Waiting for these 2 events ensures
// there is data in the video
video.addEventListener(
"playing",
() => {
playing = true;
checkReady();
},
true
);
video.addEventListener(
"timeupdate",
() => {
timeupdate = true;
checkReady();
},
true
);
video.src = url;
video.play();
function checkReady() {
if (playing && timeupdate) {
copyVideo = true;
}
}
return video;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function initBuffers(gl) {
const positionBuffer = initPositionBuffer(gl);
const colorBuffer = initColorBuffer(gl);
return {
position: positionBuffer,
color: colorBuffer,
};
}
function initPositionBuffer(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Now create an array of positions for the square.
const positions = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return positionBuffer;
}
function initColorBuffer(gl) {
const colors = [
1.0,
1.0,
1.0,
1.0, // white
1.0,
0.0,
0.0,
1.0, // red
0.0,
1.0,
0.0,
1.0, // green
0.0,
0.0,
1.0,
1.0, // blue
];
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
return colorBuffer;
}
export { initBuffers };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function drawScene(gl, programInfo, buffers) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
setPositionAttribute(gl, buffers, programInfo);
setColorAttribute(gl, buffers, programInfo);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
{
const offset = 0;
const vertexCount = 4;
gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
}
}
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
function setPositionAttribute(gl, buffers, programInfo) {
const numComponents = 2; // pull out 2 values per iteration
const type = gl.FLOAT; // the data in the buffer is 32bit floats
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the colors from the color buffer
// into the vertexColor attribute.
function setColorAttribute(gl, buffers, programInfo) {
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);
}
export { drawScene };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"
defer
></script>
<script src="webgl-demo.js" type="module"></script>
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
import { initBuffers } from "./init-buffers.js";
import { drawScene } from "./draw-scene.js";
main();
//
// start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (gl === null) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec4 aVertexColor;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying lowp vec4 vColor;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vColor = aVertexColor;
}
`;
// Fragment shader program
const fsSource = `
varying lowp vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attributes our shader program is using
// for aVertexPosition, aVertexColor and also
// look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
vertexColor: gl.getAttribLocation(shaderProgram, "aVertexColor"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram,
"uProjectionMatrix"
),
modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
// Draw the scene
drawScene(gl, programInfo, buffers);
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert(
`Unable to initialize the shader program: ${gl.getProgramInfoLog(
shaderProgram
)}`
);
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(
`An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`
);
gl.deleteShader(shader);
return null;
}
return shader;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function initBuffers(gl) {
const positionBuffer = initPositionBuffer(gl);
const colorBuffer = initColorBuffer(gl);
return {
position: positionBuffer,
color: colorBuffer,
};
}
function initPositionBuffer(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Now create an array of positions for the square.
const positions = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return positionBuffer;
}
function initColorBuffer(gl) {
const colors = [
1.0,
1.0,
1.0,
1.0, // white
1.0,
0.0,
0.0,
1.0, // red
0.0,
1.0,
0.0,
1.0, // green
0.0,
0.0,
1.0,
1.0, // blue
];
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
return colorBuffer;
}
export { initBuffers };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function drawScene(gl, programInfo, buffers, squareRotation) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
squareRotation, // amount to rotate in radians
[0, 0, 1]
); // axis to rotate around
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
setPositionAttribute(gl, buffers, programInfo);
setColorAttribute(gl, buffers, programInfo);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
{
const offset = 0;
const vertexCount = 4;
gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
}
}
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
function setPositionAttribute(gl, buffers, programInfo) {
const numComponents = 2; // pull out 2 values per iteration
const type = gl.FLOAT; // the data in the buffer is 32bit floats
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the colors from the color buffer
// into the vertexColor attribute.
function setColorAttribute(gl, buffers, programInfo) {
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);
}
export { drawScene };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"
defer
></script>
<script src="webgl-demo.js" type="module"></script>
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
import { initBuffers } from "./init-buffers.js";
import { drawScene } from "./draw-scene.js";
let squareRotation = 0.0;
let deltaTime = 0;
main();
//
// start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (gl === null) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec4 aVertexColor;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying lowp vec4 vColor;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vColor = aVertexColor;
}
`;
// Fragment shader program
const fsSource = `
varying lowp vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attributes our shader program is using
// for aVertexPosition, aVertexColor and also
// look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
vertexColor: gl.getAttribLocation(shaderProgram, "aVertexColor"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram,
"uProjectionMatrix"
),
modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
let then = 0;
// Draw the scene repeatedly
function render(now) {
now *= 0.001; // convert to seconds
deltaTime = now - then;
then = now;
drawScene(gl, programInfo, buffers, squareRotation);
squareRotation += deltaTime;
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert(
`Unable to initialize the shader program: ${gl.getProgramInfoLog(
shaderProgram
)}`
);
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(
`An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`
);
gl.deleteShader(shader);
return null;
}
return shader;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<link rel="stylesheet" href="../webgl.css" type="text/css" />
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
<script src="../gl-matrix.js"></script>
<script src="webgl-demo.js"></script>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
var tetrahedronRotation = 0.0;
main();
//
// Start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
const gl =
canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
// If we don't have a GL context, give up now
if (!gl) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
attribute vec4 aVertexColor;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
varying lowp vec4 vColor;
void main(void) {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
vColor = aVertexColor;
}
`;
// Fragment shader program
const fsSource = `
varying lowp vec4 vColor;
void main(void) {
gl_FragColor = vColor;
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attributes our shader program is using
// for aVertexPosition, aVevrtexColor and also
// look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
vertexColor: gl.getAttribLocation(shaderProgram, "aVertexColor"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram,
"uProjectionMatrix"
),
modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
var then = 0;
// Draw the scene repeatedly
function render(now) {
now *= 0.001; // convert to seconds
const deltaTime = now - then;
then = now;
drawScene(gl, programInfo, buffers, deltaTime);
requestAnimationFrame(render);
}
requestAnimationFrame(render);
}
//
// initBuffers
//
// Initialize the buffers we'll need. For this demo, we just
// have one object -- a simple three-dimensional tetrahedron.
//
function initBuffers(gl) {
// Create a buffer for the tetrahedron's vertex positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Now create an array of positions for the tetrahedron.
// A equilateral triangle is needed ( well 4 of them )
// Point `O` is where the height is projected
// The tetrahedron is rotated around point `M`
// Height from vertex `A` to the edge `BC` is `H`
// The edge of the tetrahedron is 2 units long
// |AH| = 1.7320508075688772935274463415059
// The median and a height AH divides itself by
// the other medians into 1x and 2x ( one part and two parts )
// |AH|/3 = 0.57735026918962576450914878050197
// Find the tetrahedron height by argument sine (<OAD)
// <OAD = 54.735610317245345684622999669982
// |DO| = 1.6329931618554520654648560498039
// |DO|/3 = 0.5443310539518173551549520166013
// 2 * (|DO|/3) = 1.0886621079036347103099040332026
const positions = [
-1.0,
-0.5773,
-0.54433, // A
1.0,
-0.5773,
-0.54433, // B
0.0,
1.1547,
-0.54433, // C
-1.0,
-0.5773,
-0.54433, // A
1.0,
-0.5773,
-0.54433, // B
0.0,
0.0,
1.08866, // D
1.0,
-0.5773,
-0.54433, // B
0.0,
1.1547,
-0.54433, // C
0.0,
0.0,
1.08866, // D
-1.0,
-0.5773,
-0.54433, // A
0.0,
1.1547,
-0.54433, // C
0.0,
0.0,
1.08866, // D
];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
// Now set up the colors for the faces. We'll use solid colors
// for each face.
const faceColors = [
[1.0, 1.0, 1.0, 1.0], // Front face: white
[1.0, 0.0, 0.0, 1.0], // Back face: red
[0.0, 1.0, 0.0, 1.0], // Top face: green
[0.0, 0.0, 1.0, 1.0], // Bottom face: blue
];
// Convert the array of colors into a table for all the vertices.
var colors = [];
for (var j = 0; j < faceColors.length; ++j) {
const c = faceColors[j];
// Repeat each color four times for the four vertices of the face
colors = colors.concat(c, c, c);
}
const colorBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, colorBuffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
// Build the element array buffer; this specifies the indices
// into the vertex arrays for each face's vertices.
const indexBuffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
// This array defines each face as two triangles, using the
// indices into the vertex array to specify each triangle's
// position.
const indices = [
0,
1,
2,
0,
1,
2, // ABC
3,
4,
5,
3,
4,
5, // ABD
6,
7,
8,
6,
7,
8, // BCD
9,
10,
11,
9,
10,
11, // ACD
0,
0,
0,
0,
0,
0, // Dummy1
0,
0,
0,
0,
0,
0, // Dummy2
];
// Now send the element array to GL
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array(indices),
gl.STATIC_DRAW
);
return {
position: positionBuffer,
color: colorBuffer,
indices: indexBuffer,
};
}
//
// Draw the scene.
//
function drawScene(gl, programInfo, buffers, deltaTime) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
tetrahedronRotation, // amount to rotate in radians
[0, 0, 1]
); // axis to rotate around (Z)
mat4.rotate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to rotate
tetrahedronRotation * 0.7, // amount to rotate in radians
[0, 1, 0]
); // axis to rotate around (X)
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute
{
const numComponents = 3;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
// Tell WebGL how to pull out the colors from the color buffer
// into the vertexColor attribute.
{
const numComponents = 4;
const type = gl.FLOAT;
const normalize = false;
const stride = 0;
const offset = 0;
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.color);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexColor,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexColor);
}
// Tell WebGL which indices to use to index the vertices
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffers.indices);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
{
const vertexCount = 36;
const type = gl.UNSIGNED_SHORT;
const offset = 0;
gl.drawElements(gl.TRIANGLES, vertexCount, type, offset);
}
// Update the rotation for the next draw
tetrahedronRotation += deltaTime;
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert(
"Unable to initialize the shader program: " +
gl.getProgramInfoLog(shaderProgram)
);
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(
"An error occurred compiling the shaders: " + gl.getShaderInfoLog(shader)
);
gl.deleteShader(shader);
return null;
}
return shader;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<script src="webgl-demo.js" type="module"></script>
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
main();
//
// start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (gl === null) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function initBuffers(gl) {
const positionBuffer = initPositionBuffer(gl);
return {
position: positionBuffer,
};
}
function initPositionBuffer(gl) {
// Create a buffer for the square's positions.
const positionBuffer = gl.createBuffer();
// Select the positionBuffer as the one to apply buffer
// operations to from here out.
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
// Now create an array of positions for the square.
const positions = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0];
// Now pass the list of positions into WebGL to build the
// shape. We do this by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer.
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);
return positionBuffer;
}
export { initBuffers };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
function drawScene(gl, programInfo, buffers) {
gl.clearColor(0.0, 0.0, 0.0, 1.0); // Clear to black, fully opaque
gl.clearDepth(1.0); // Clear everything
gl.enable(gl.DEPTH_TEST); // Enable depth testing
gl.depthFunc(gl.LEQUAL); // Near things obscure far things
// Clear the canvas before we start drawing on it.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Create a perspective matrix, a special matrix that is
// used to simulate the distortion of perspective in a camera.
// Our field of view is 45 degrees, with a width/height
// ratio that matches the display size of the canvas
// and we only want to see objects between 0.1 units
// and 100 units away from the camera.
const fieldOfView = (45 * Math.PI) / 180; // in radians
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 100.0;
const projectionMatrix = mat4.create();
// note: glmatrix.js always has the first argument
// as the destination to receive the result.
mat4.perspective(projectionMatrix, fieldOfView, aspect, zNear, zFar);
// Set the drawing position to the "identity" point, which is
// the center of the scene.
const modelViewMatrix = mat4.create();
// Now move the drawing position a bit to where we want to
// start drawing the square.
mat4.translate(
modelViewMatrix, // destination matrix
modelViewMatrix, // matrix to translate
[-0.0, 0.0, -6.0]
); // amount to translate
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
setPositionAttribute(gl, buffers, programInfo);
// Tell WebGL to use our program when drawing
gl.useProgram(programInfo.program);
// Set the shader uniforms
gl.uniformMatrix4fv(
programInfo.uniformLocations.projectionMatrix,
false,
projectionMatrix
);
gl.uniformMatrix4fv(
programInfo.uniformLocations.modelViewMatrix,
false,
modelViewMatrix
);
{
const offset = 0;
const vertexCount = 4;
gl.drawArrays(gl.TRIANGLE_STRIP, offset, vertexCount);
}
}
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute.
function setPositionAttribute(gl, buffers, programInfo) {
const numComponents = 2; // pull out 2 values per iteration
const type = gl.FLOAT; // the data in the buffer is 32bit floats
const normalize = false; // don't normalize
const stride = 0; // how many bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0; // how many bytes inside the buffer to start from
gl.bindBuffer(gl.ARRAY_BUFFER, buffers.position);
gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset
);
gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition);
}
export { drawScene };
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>WebGL Demo</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/gl-matrix/2.8.1/gl-matrix-min.js"
integrity="sha512-zhHQR0/H5SEBL3Wn6yYSaTTZej12z0hVZKOv3TwCUXT1z5qeqGcXJLLrbERYRScEDDpYIJhPC1fk31gqR783iQ=="
crossorigin="anonymous"
defer
></script>
<script src="webgl-demo.js" type="module"></script>
</head>
<body>
<canvas id="glcanvas" width="640" height="480"></canvas>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
import { initBuffers } from "./init-buffers.js";
import { drawScene } from "./draw-scene.js";
main();
//
// start here
//
function main() {
const canvas = document.querySelector("#glcanvas");
// Initialize the GL context
const gl = canvas.getContext("webgl");
// Only continue if WebGL is available and working
if (gl === null) {
alert(
"Unable to initialize WebGL. Your browser or machine may not support it."
);
return;
}
// Set clear color to black, fully opaque
gl.clearColor(0.0, 0.0, 0.0, 1.0);
// Clear the color buffer with specified clear color
gl.clear(gl.COLOR_BUFFER_BIT);
// Vertex shader program
const vsSource = `
attribute vec4 aVertexPosition;
uniform mat4 uModelViewMatrix;
uniform mat4 uProjectionMatrix;
void main() {
gl_Position = uProjectionMatrix * uModelViewMatrix * aVertexPosition;
}
`;
const fsSource = `
void main() {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
`;
// Initialize a shader program; this is where all the lighting
// for the vertices and so forth is established.
const shaderProgram = initShaderProgram(gl, vsSource, fsSource);
// Collect all the info needed to use the shader program.
// Look up which attribute our shader program is using
// for aVertexPosition and look up uniform locations.
const programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: gl.getAttribLocation(shaderProgram, "aVertexPosition"),
},
uniformLocations: {
projectionMatrix: gl.getUniformLocation(
shaderProgram,
"uProjectionMatrix"
),
modelViewMatrix: gl.getUniformLocation(shaderProgram, "uModelViewMatrix"),
},
};
// Here's where we call the routine that builds all the
// objects we'll be drawing.
const buffers = initBuffers(gl);
// Draw the scene
drawScene(gl, programInfo, buffers);
}
//
// Initialize a shader program, so WebGL knows how to draw our data
//
function initShaderProgram(gl, vsSource, fsSource) {
const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource);
const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource);
// Create the shader program
const shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
// If creating the shader program failed, alert
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
alert(
`Unable to initialize the shader program: ${gl.getProgramInfoLog(
shaderProgram
)}`
);
return null;
}
return shaderProgram;
}
//
// creates a shader of the given type, uploads the source and
// compiles it.
//
function loadShader(gl, type, source) {
const shader = gl.createShader(type);
// Send the source to the shader object
gl.shaderSource(shader, source);
// Compile the shader program
gl.compileShader(shader);
// See if it compiled successfully
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
alert(
`An error occurred compiling the shaders: ${gl.getShaderInfoLog(shader)}`
);
gl.deleteShader(shader);
return null;
}
return shader;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<!--
This application demonstrates using Pointer Events for simple 2-pointer
pinch/zoom gesture recognition.
-->
<head>
<title>Pointer Events pinch/zoom example</title>
<meta name="viewport" content="width=device-width">
<style>
div {
margin: 0em;
padding: 2em;
}
#target {
background: white;
border: 1px solid black;
}
</style>
</head>
<script>
// Log events flag
var logEvents = false;
// Global vars to cache event state
var evCache = new Array();
var prevDiff = -1;
// Logging/debugging functions
function enableLog(ev) {
logEvents = logEvents ? false : true;
}
function log(prefix, ev) {
if (!logEvents) return;
var o = document.getElementsByTagName('output')[0];
var s = prefix + ": pointerID = " + ev.pointerId +
" ; pointerType = " + ev.pointerType +
" ; isPrimary = " + ev.isPrimary;
o.innerHTML += s + " <br>";
}
function clearLog(event) {
var o = document.getElementsByTagName('output')[0];
o.innerHTML = "";
}
function pointerdown_handler(ev) {
// The pointerdown event signals the start of a touch interaction.
// This event is cached to support 2-finger gestures
evCache.push(ev);
log("pointerDown", ev);
}
function pointermove_handler(ev) {
// This function implements a 2-pointer horizontal pinch/zoom gesture.
//
// If the distance between the two pointers has increased (zoom in),
// the taget element's background is changed to "pink" and if the
// distance is decreasing (zoom out), the color is changed to "lightblue".
//
// This function sets the target element's border to "dashed" to visually
// indicate the pointer's target received a move event.
log("pointerMove", ev);
ev.target.style.border = "dashed";
// Find this event in the cache and update its record with this event
for (var i = 0; i < evCache.length; i++) {
if (ev.pointerId == evCache[i].pointerId) {
evCache[i] = ev;
break;
}
}
// If two pointers are down, check for pinch gestures
if (evCache.length == 2) {
// Calculate the distance between the two pointers
var curDiff = Math.sqrt(Math.pow(evCache[1].clientX - evCache[0].clientX, 2) + Math.pow(evCache[1].clientY - evCache[0].clientY, 2));
if (prevDiff > 0) {
if (curDiff > prevDiff) {
// The distance between the two pointers has increased
log("Pinch moving OUT -> Zoom in", ev);
ev.target.style.background = "pink";
}
if (curDiff < prevDiff) {
// The distance between the two pointers has decreased
log("Pinch moving IN -> Zoom out",ev);
ev.target.style.background = "lightblue";
}
}
// Cache the distance for the next move event
prevDiff = curDiff;
}
}
function pointerup_handler(ev) {
log(ev.type, ev);
// Remove this pointer from the cache and reset the target's
// background and border
remove_event(ev);
ev.target.style.background = "white";
ev.target.style.border = "1px solid black";
// If the number of pointers down is less than two then reset diff tracker
if (evCache.length < 2) prevDiff = -1;
}
function remove_event(ev) {
// Remove this event from the target's cache
for (var i = 0; i < evCache.length; i++) {
if (evCache[i].pointerId == ev.pointerId) {
evCache.splice(i, 1);
break;
}
}
}
function init() {
// Install event handlers for the pointer target
var el=document.getElementById("target");
el.onpointerdown = pointerdown_handler;
el.onpointermove = pointermove_handler;
// Use same handler for pointer{up,cancel,out,leave} events since
// the semantics for these events - in this app - are the same.
el.onpointerup = pointerup_handler;
el.onpointercancel = pointerup_handler;
el.onpointerout = pointerup_handler;
el.onpointerleave = pointerup_handler;
}
</script>
<body onload="init();" style="touch-action:none">
<h1>Pointer Event pinch/zoom gesture</h1>
<!-- Create element for pointer gestures. -->
<div id="target">Touch and Hold with 2 pointers, then pinch in or out.<br/>
The background color will change to pink if the pinch is opening (Zoom In)
or changes to lightblue if the pinch is closing (Zoom out).</div>
<!-- UI for logging/debugging -->
<button id="log" onclick="enableLog(event);">Start/Stop event logging</button>
<button id="clearlog" onclick="clearLog(event);">Clear the log</button>
<p></p>
<output></output>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!doctype html>
<html lang="en">
<!--
This application is documented in "Using Pointer Events":
<https://developer.mozilla.org/en-US/docs/Web/API/Pointer_events/Using_Pointer_Events>
The application is a port of the example in "Using Touch events":
<https://developer.mozilla.org/en-US/docs/Web/API/Touch_events>
This port uses Pointer Events instead of Touch Events.
-->
<head>
<link rel="stylesheet" type="text/css" href="https://developer.mozilla.org/en-US/docs/Template:CustomSampleCSS?raw=1" />
</head>
<body>
<canvas id="canvas" width="600" height="300" style="border:solid black 1px; touch-action:none">
Your browser does not support canvas element.
</canvas>
<br>
<button onclick="startup();">Initialize</button>
<br>
Log:
<pre id="log" style="border: 1px solid #ccc;"></pre>
<script type="text/javascript">
function startup() {
var el = document.getElementsByTagName("canvas")[0];
el.addEventListener("pointerdown", handleStart, false);
el.addEventListener("pointerup", handleEnd, false);
el.addEventListener("pointercancel", handleCancel, false);
el.addEventListener("pointermove", handleMove, false);
log("initialized.");
}
var ongoingTouches = new Array();
function handleStart(evt) {
log("pointerdown.");
var el = document.getElementsByTagName("canvas")[0];
var ctx = el.getContext("2d");
log("pointerdown: id = " + evt.pointerId);
ongoingTouches.push(copyTouch(evt));
var color = colorForTouch(evt);
ctx.beginPath();
ctx.arc(touches[i].pageX, touches[i].pageY, 4, 0, 2 * Math.PI, false); // a circle at the start
ctx.arc(evt.clientX, evt.clientY, 4, 0, 2 * Math.PI, false); // a circle at the start
ctx.fillStyle = color;
ctx.fill();
}
function handleMove(evt) {
var el = document.getElementsByTagName("canvas")[0];
var ctx = el.getContext("2d");
var color = colorForTouch(evt);
var idx = ongoingTouchIndexById(evt.pointerId);
log("continuing touch: idx = " + idx);
if (idx >= 0) {
ctx.beginPath();
log("ctx.moveTo(" + ongoingTouches[idx].pageX + ", " + ongoingTouches[idx].pageY + ");");
ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
log("ctx.lineTo(" + evt.clientX + ", " + evt.clientY + ");");
ctx.lineTo(evt.clientX, evt.clientY);
ctx.lineWidth = 4;
ctx.strokeStyle = color;
ctx.stroke();
ongoingTouches.splice(idx, 1, copyTouch(evt)); // swap in the new touch record
log(".");
} else {
log("can't figure out which touch to continue: idx = " + idx);
}
}
function handleEnd(evt) {
log("pointerup");
var el = document.getElementsByTagName("canvas")[0];
var ctx = el.getContext("2d");
var color = colorForTouch(evt);
var idx = ongoingTouchIndexById(evt.pointerId);
if (idx >= 0) {
ctx.lineWidth = 4;
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(ongoingTouches[idx].pageX, ongoingTouches[idx].pageY);
ctx.lineTo(evt.clientX, evt.clientY);
ctx.fillRect(evt.clientX - 4, evt.clientY - 4, 8, 8); // and a square at the end
ongoingTouches.splice(idx, 1); // remove it; we're done
} else {
log("can't figure out which touch to end");
}
}
function handleCancel(evt) {
log("pointercancel: id = " + evt.pointerId);
var idx = ongoingTouchIndexById(evt.pointerId);
ongoingTouches.splice(idx, 1); // remove it; we're done
}
function colorForTouch(touch) {
var r = touch.pointerId % 16;
var g = Math.floor(touch.pointerId / 3) % 16;
var b = Math.floor(touch.pointerId / 7) % 16;
r = r.toString(16); // make it a hex digit
g = g.toString(16); // make it a hex digit
b = b.toString(16); // make it a hex digit
var color = "#" + r + g + b;
log("color for touch with identifier " + touch.pointerId + " = " + color);
return color;
}
function copyTouch(touch) {
return { identifier: touch.pointerId, pageX: touch.clientX, pageY: touch.clientY };
}
function ongoingTouchIndexById(idToFind) {
for (var i = 0; i < ongoingTouches.length; i++) {
var id = ongoingTouches[i].identifier;
if (id == idToFind) {
return i;
}
}
return -1; // not found
}
function log(msg) {
var p = document.getElementById('log');
p.innerHTML = msg + "\n" + p.innerHTML;
}
</script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<!--
This app demonstrates using Pointer Events (pointerdown, pointerup,
pointermove, pointercancel, etc.) for the following interactions:
1. Single touch
2. Two (simultaneous) touches
3. More than two simultaneous touches
-->
<head>
<title>Pointer Events multi-touch interaction</title>
<meta name="viewport" content="width=device-width">
<style>
div {
margin: 0em;
padding: 2em;
}
#target1 {
background: white;
border: 1px solid black;
}
#target2 {
background: white;
border: 1px solid black;
}
#target3 {
background: white;
border: 1px solid black;
}
</style>
</head>
<script>
// Log events flag
var logEvents = false;
// Event caches, one per touch target
var evCache1 = new Array();
var evCache2 = new Array();
var evCache3 = new Array();
function enableLog(ev) {
logEvents = logEvents ? false : true;
}
function log(name, ev) {
var o = document.getElementsByTagName('output')[0];
var s = name + ": pointerID = " + ev.pointerId +
" ; pointerType = " + ev.pointerType +
" ; isPrimary = " + ev.isPrimary;
o.innerHTML += s + " <br>";
}
function clearLog(event) {
var o = document.getElementsByTagName('output')[0];
o.innerHTML = "";
}
function update_background(ev) {
// Change background color based on the number simultaneous touches/pointers
// currently down:
// white - target element has no touch points i.e. no pointers down
// yellow - one pointer down
// pink - two pointers down
// lightblue - three or more pointers down
var evCache = get_cache(ev);
switch (evCache.length) {
case 0:
// Target element has no touch points
ev.target.style.background = "white";
break;
case 1:
// Single touch point
ev.target.style.background = "yellow";
break;
case 2:
// Two simultaneous touch points
ev.target.style.background = "pink";
break;
default:
// Three or more simultaneous touches
ev.target.style.background = "lightblue";
}
}
function pointerdown_handler(ev) {
// The pointerdown event signals the start of a touch interaction.
// Save this event for later processing (this could be part of a
// multi-touch interaction) and update the background color
push_event(ev);
if (logEvents) log("pointerDown: name = " + ev.target.id, ev);
update_background(ev);
}
function pointermove_handler(ev) {
// Note: if the user makes more than one "simultaneous" touch, most browsers
// fire at least one pointermove event and some will fire several pointermoves.
//
// This function sets the target element's border to "dashed" to visually
// indicate the target received a move event.
if (logEvents) log("pointerMove", ev);
update_background(ev);
ev.target.style.border = "dashed";
}
function pointerup_handler(ev) {
if (logEvents) log(ev.type, ev);
// Remove this touch point from the cache and reset the target's
// background and border
remove_event(ev);
update_background(ev);
ev.target.style.border = "1px solid black";
}
function get_cache(ev) {
// Return the cache for this event's target element
switch(ev.target.id) {
case "target1": return evCache1;
case "target2": return evCache2;
case "target3": return evCache3;
default: log("Error with cache handling",ev);
}
}
function push_event(ev) {
// Save this event in the target's cache
var cache = get_cache(ev);
cache.push(ev);
}
function remove_event(ev) {
// Remove this event from the target's cache
var cache = get_cache(ev);
for (var i = 0; i < cache.length; i++) {
if (cache[i].pointerId == ev.pointerId) {
cache.splice(i, 1);
break;
}
}
}
function set_handlers(name) {
// Install event handlers for the given element
var el=document.getElementById(name);
el.onpointerdown = pointerdown_handler;
el.onpointermove = pointermove_handler;
// Use same handler for pointer{up,cancel,out,leave} events since
// the semantics for these events - in this app - are the same.
el.onpointerup = pointerup_handler;
el.onpointercancel = pointerup_handler;
el.onpointerout = pointerup_handler;
el.onpointerleave = pointerup_handler;
}
function init() {
set_handlers("target1");
set_handlers("target2");
set_handlers("target3");
}
</script>
<body onload="init();" style="touch-action:none">
<h1>Multi-touch interaction</h1>
<!-- Create some boxes to test various gestures. -->
<div id="target1">Tap, Hold or Swipe me 1</div>
<div id="target2">Tap, Hold or Swipe me 2</div>
<div id="target3">Tap, Hold or Swipe me 3</div>
<!-- UI for logging/bebugging -->
<button id="log" onclick="enableLog(event);">Start/Stop event logging</button>
<button id="clearlog" onclick="clearLog(event);">Clear the log</button>
<p></p>
<output></output>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
Examples:
* [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).
* [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).
* [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).
External Pointer Events Demos:
* [Patrick H Lauke's site](http://patrickhlauke.github.io/touch/)
* [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
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>auxclick demo</title>
<style>
html {
height: 100%;
overflow: hidden;
}
body {
height: inherit;
display: flex;
justify-content: center;
align-items: center;
margin: 0;
}
button {
border: 0;
background-color: white;
font-size: 10vw;
display: block;
width: 100%;
height: 100%;
}
button {
letter-spacing: 1rem;
}
</style>
</head>
<body>
<button>Click me!</button>
<script>
const button = document.querySelector('button');
const html = document.querySelector('html');
function random(number) {
return Math.floor(Math.random() * number);
}
button.onclick = () => {
const rndCol = `rgb(${random(255)}, ${random(255)}, ${random(255)})`;
button.style.backgroundColor = rndCol;
};
button.onauxclick = (e) => {
e.preventDefault();
const rndCol = `rgb(${random(255)}, ${random(255)}, ${random(255)})`;
button.style.color = rndCol;
}
</script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
# auxclick demo
The <code>onauxclick</code> property is an event handler called when an <code>auxclick</code> event is sent, indicating that a non-primary button has been pressed on an input device (e.g. a middle mouse button).
This 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 <code>click</code> only fires for primary button clicks (e.g. left mouse button). Developers can then use <code>auxclick</code> to provide explicit behaviour for non-primary button clicks.
Previous to this, <code>click</code> generally fired for clicks on all input device buttons, and browser behaviour was somewhat inconsistent.
[See the demo live](https://mdn.github.io/dom-examples/auxclick/).
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
</head>
<body>
<button>Close the connection</button>
<ul>
</ul>
<script>
const button = document.querySelector('button');
const evtSource = new EventSource('sse.php');
console.log(evtSource.withCredentials);
console.log(evtSource.readyState);
console.log(evtSource.url);
const eventList = document.querySelector('ul');
evtSource.onopen = function() {
console.log("Connection to server opened.");
};
evtSource.onmessage = function(e) {
const newElement = document.createElement("li");
newElement.textContent = "message: " + e.data;
eventList.appendChild(newElement);
};
evtSource.onerror = function() {
console.log("EventSource failed.");
};
button.onclick = function() {
console.log('Connection closed');
evtSource.close();
};
// evtSource.addEventListener("ping", function(e) {
// var newElement = document.createElement("li");
//
// var obj = JSON.parse(e.data);
// newElement.innerHTML = "ping at " + obj.time;
// eventList.appendChild(newElement);
// }, false);
</script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<?php
date_default_timezone_set("America/New_York");
header("X-Accel-Buffering: no");
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$counter = rand(1, 10); // a random counter
while (1) {
// 1 is always true, so repeat the while loop forever (aka event-loop)
$curDate = date(DATE_ISO8601);
echo "event: ping\n",
'data: {"time": "' . $curDate . '"}', "\n\n";
// Send a simple message at random intervals.
$counter--;
if (!$counter) {
echo 'data: This is a message at time ' . $curDate, "\n\n";
$counter = rand(1, 10); // reset random counter
}
// flush the output buffer and send echoed messages to the browser
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
// break the loop if the client aborted the connection (closed the page)
if ( connection_aborted() ) break;
// sleep for 1 second before running the loop again
sleep(1);
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
## Note about running this example through **NGINX**:
By default `fastcgi_buffering` is ON, thus you have to add `fastcgi_buffering off;` to the appropriate `location` block for this example to work.
Similarly, if you use a reverse proxy, `proxy_buffering` is ON by default, thus you have to add `proxy_buffering off;`.
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!doctype html>
<html lang="en">
<head>
<title>Picture-in-Picture Example</title>
<script src="main.js"></script>
<link href="main.css" rel="stylesheet">
</head>
<body>
<div id="contents">
<p>A quick example for the use of the <code>Picture-in-Picture</code> API</p>
<video src="assets/bigbuckbunny.mp4" id="video" muted autoplay width="300"></video>
<div id="credits"><a href="https://peach.blender.org/download/" target="_blank">Video by Blender</a>;
<a href="https://peach.blender.org/about/" target="_blank">licensed CC-BY 3.0</a></div>
<div id="controlbar">
<p class="no-picture-in-picture">
Picture-in-Picture mode not available
<p>
</div>
<p>
Events
</p>
<ul id="logs"></ul>
</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
#contents {
width: 600px;
font: 14px "Open Sans", sans-serif;
}
#credits {
padding: 0 0 10px 0;
font: italic 10px "Open Sans", sans-serif;
}
:picture-in-picture {
box-shadow: 0 0 0 5px red;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
window.addEventListener("load", startup, false);
let video;
let logs;
function startup() {
video = document.getElementById("video");
logs = document.getElementById("logs");
if (document.pictureInPictureEnabled) {
document
.querySelector(".no-picture-in-picture")
.remove();
const togglePipButton = document.createElement("button");
togglePipButton.textContent = "Toggle Picture-in-Picture";
togglePipButton.addEventListener("click", togglePictureInPicture, false);
document
.getElementById("controlbar")
.appendChild(togglePipButton);
}
}
function togglePictureInPicture() {
if (document.pictureInPictureElement) {
document.exitPictureInPicture();
} else {
if (document.pictureInPictureEnabled) {
video.requestPictureInPicture()
.then(pictureInPictureWindow => {
pictureInPictureWindow.addEventListener("resize", onPictureInPictureResize, false);
});
}
}
}
function onPictureInPictureResize() {
const listItem = document.createElement("li");
listItem.textContent = `resize - ${Date.now()}`;
logs.appendChild(listItem);
setTimeout(() => logs.removeChild(listItem), 2000);
};
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
# Picture-in-Picture example
This example will progressively enhance a video by adding a toggle picture-in-picture mode button if that feature is enabled.
It also highlights how to set up a resize event on the <code><PictureInPictureWindow></code>
[See the example live](https://mdn.github.io/dom-examples/picture-in-picture/).
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebGPU data</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>WebGPU data</h1>
</body>
</html> | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
// Define global buffer size
const BUFFER_SIZE = 1000;
// Compute shader
const shader = `
@group(0) @binding(0)
var<storage, read_write> output: array<f32>;
@compute @workgroup_size(64)
fn main(
@builtin(global_invocation_id)
global_id : vec3u,
@builtin(local_invocation_id)
local_id : vec3u,
) {
// Avoid accessing the buffer out of bounds
if (global_id.x >= ${BUFFER_SIZE}u) {
return;
}
output[global_id.x] =
f32(global_id.x) * 1000. + f32(local_id.x);
}
`;
// Main function
async function init() {
// 1: request adapter and device
if (!navigator.gpu) {
throw Error('WebGPU not supported.');
}
const adapter = await navigator.gpu.requestAdapter();
if (!adapter) {
throw Error('Couldn\'t request WebGPU adapter.');
}
const device = await adapter.requestDevice();
// 2: Create a shader module from the shader template literal
const shaderModule = device.createShaderModule({
code: shader
});
// 3: Create an output buffer to read GPU calculations to, and a staging buffer to be mapped for JavaScript access
const output = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC
});
const stagingBuffer = device.createBuffer({
size: BUFFER_SIZE,
usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST
});
// 4: Create a GPUBindGroupLayout to define the bind group structure, create a GPUBindGroup from it,
// then use it to create a GPUComputePipeline
const bindGroupLayout =
device.createBindGroupLayout({
entries: [{
binding: 0,
visibility: GPUShaderStage.COMPUTE,
buffer: {
type: "storage"
}
}]
});
const bindGroup = device.createBindGroup({
layout: bindGroupLayout,
entries: [{
binding: 0,
resource: {
buffer: output,
}
}]
});
const computePipeline = device.createComputePipeline({
layout: device.createPipelineLayout({
bindGroupLayouts: [bindGroupLayout]
}),
compute: {
module: shaderModule,
entryPoint: 'main'
}
});
// 5: Create GPUCommandEncoder to issue commands to the GPU
const commandEncoder = device.createCommandEncoder();
// 6: Initiate render pass
const passEncoder = commandEncoder.beginComputePass();
// 7: Issue commands
passEncoder.setPipeline(computePipeline);
passEncoder.setBindGroup(0, bindGroup);
passEncoder.dispatchWorkgroups(Math.ceil(BUFFER_SIZE / 64));
// End the render pass
passEncoder.end();
// Copy output buffer to staging buffer
commandEncoder.copyBufferToBuffer(
output,
0, // Source offset
stagingBuffer,
0, // Destination offset
BUFFER_SIZE
);
// 8: End frame by passing array of command buffers to command queue for execution
device.queue.submit([commandEncoder.finish()]);
// map staging buffer to read results back to JS
await stagingBuffer.mapAsync(
GPUMapMode.READ,
0, // Offset
BUFFER_SIZE // Length
);
const copyArrayBuffer = stagingBuffer.getMappedRange(0, BUFFER_SIZE);
const data = copyArrayBuffer.slice();
stagingBuffer.unmap();
console.log(new Float32Array(data));
}
init();
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8">
<title>Pre-authorize Transaction</title>
<!--
Some use cases (e.g. paying for fuel at a service station) involve pre-authorization
of payment. One way to do this is through a Payment Handler (see the Payment Handler
API). At time of writing, that specification includes a CanMakePayment that a Payment
Handler could make use of to return authorization status.
-->
<meta name="viewport" content="width=device-width">
<style>
#success,
#legacy {
display: none;
}
</style>
</head>
<body>
<h1>Pre-authorize Transaction</h1>
<div id="intro">
<p>
Some use cases (e.g., paying for fuel at a service station) involve
pre-authorization of payment. One way to do this is through a Payment Handler
(see the <a href="https://www.w3.org/TR/payment-handler/">Payment Handler API</a>).
Currently that specification includes a <code>CanMakePayment</code> that a
Payment Handler could make use of, to return authorization status.
</p>
<button id="preauthorize-button">Pre-authorize</button>
</div>
<div id="success">
<p>
Payment Request success. Demo complete. No payment has been taken.
</p>
</div>
<div id="legacy">
<p>
The Payment Request API is unsupported or was cancelled or failed,
so here we can proceed with our legacy web form (not implemented for this demo).
</p>
</div>
<script type="text/javascript">
var preauthorizeButton = document.getElementById('preauthorize-button');
var introPanel = document.getElementById('intro');
var successPanel = document.getElementById('success');
var legacyPanel = document.getElementById('legacy');
// Feature detection
if (window.PaymentRequest) {
// Payment Request is supported in this browser, so we can proceed to use it
preauthorizeButton.addEventListener('click', function() {
var request = new PaymentRequest(buildSupportedPaymentMethodData(),
buildShoppingCartDetails());
/*
* The canMakePayment() event will be handled by the Payment Handler.
* The payment handler would include the following code:
*
* self.addEventListener('canmakepayment', function(evt) {
* // Pre-authorize here.
* let preAuthSuccess = ...;
* evt.respondWith(preAuthSuccess);
* });
*/
request.canMakePayment().then(function(response) {
if (res) {
// The payment handler has pre-authorized a transaction with some
// static amount (e.g. USD $1.00). For demo purposes:
introPanel.style.display = 'none';
successPanel.style.display = 'block';
} else {
// Pre-authorization failed or payment handler not installed.
// For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
}
}).catch(function(error) {
// Cancellation or error. For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
});
} else {
// Payment Request is unsupported
preauthorizeButton.addEventListener('click', function() {
// For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
}
function buildSupportedPaymentMethodData() {
// Example supported payment methods:
return [
{
supportedMethods: 'https://example.com/preauth'
}
];
}
function buildShoppingCartDetails() {
// Hardcoded for demo purposes:
return {
id: 'order-123',
displayItems: [
{
label: 'Example item',
amount: {currency: 'USD', value: '1.00'}
}
],
total: {
label: 'Total',
amount: {currency: 'USD', value: '1.00'}
}
};
}
</script>
</body>
</html> | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8">
<title>Customize the Payment Request Button Depending on Whether User Can Make Payments</title>
<!--
Depending on whether the user can make a fast payment or needs to add payment credentials
first, the title of the checkout button changes between "Fast Checkout with W3C" and
"Setup W3C Checkout". In both cases, the checkout button calls PaymentRequest.show().
-->
<meta name="viewport" content="width=device-width">
<style>
#success,
#legacy {
display: none;
}
</style>
</head>
<body>
<h1>Customize the Payment Request Button Depending on Whether User Can Make Payments</h1>
<div id="intro">
<p>
In this example, depending on whether the user can make a fast payment or needs to add
payment credentials first, the title of the checkout button changes between
"W3C Checkout" and "Fast W3C Checkout". This is determined using
<code>PaymentRequest.canMakePayment()</code>. In both cases, the checkout button calls
<code>PaymentRequest.show()</code>.
</p>
<p>
For the purposes of the demo, imagine you have chosen an item and
now you need to check out. Please note that no payments will be taken, this is just a
front-end demo. If you would like to try entering card details, you can use dummy data,
for example the card number <code>4111 1111 1111 1111</code>.
</p>
<button id="checkout-button">Checkout</button>
</div>
<div id="success">
<p>
Payment Request success. Demo complete. No payment has been taken.
</p>
</div>
<div id="legacy">
<p>
The Payment Request API is unsupported or was cancelled or failed.
Here we can proceed with a fallback (not implemented for this demo).
</p>
</div>
<script type="text/javascript">
var checkoutButton = document.getElementById('checkout-button');
var introPanel = document.getElementById('intro');
var successPanel = document.getElementById('success');
var legacyPanel = document.getElementById('legacy');
// Feature detection
if (window.PaymentRequest) {
// Payment Request is supported in this browser, so we can proceed to use it
var request = new PaymentRequest(buildSupportedPaymentMethodData(),
buildShoppingCartDetails());
request.canMakePayment().then(function(canMakeAFastPayment) {
if (canMakeAFastPayment) {
checkoutButton.innerText = 'Fast W3C Checkout';
} else {
checkoutButton.innerText = 'W3C Checkout';
}
}).catch(function(error) {
// The user may have turned off the querying functionality in their privacy settings.
// We do not know whether they can make a fast payment, so pick a generic title.
checkoutButton.innerText = 'W3C Checkout';
});
checkoutButton.addEventListener('click', function() {
request.show().then(function(paymentResponse) {
// Here we would process the payment. For this demo, simulate immediate success:
paymentResponse.complete('success')
.then(function() {
// For demo purposes:
introPanel.style.display = 'none';
successPanel.style.display = 'block';
});
}).catch(function(error) {
// Handle cancelled or failed payment. For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
});
} else {
// Payment Request is unsupported
checkoutButton.addEventListener('click', function() {
// For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
}
function buildSupportedPaymentMethodData() {
// Example supported payment methods:
return [{
supportedMethods: 'basic-card',
data: {
supportedNetworks: ['visa', 'mastercard'],
supportedTypes: ['debit', 'credit']
}
}];
}
function buildShoppingCartDetails() {
// Hardcoded for demo purposes:
return {
id: 'order-123',
displayItems: [
{
label: 'Example item',
amount: {currency: 'USD', value: '1.00'}
}
],
total: {
label: 'Total',
amount: {currency: 'USD', value: '1.00'}
}
};
}
</script>
</body>
</html> | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8">
<title>Check Whether User Can Make Payment Before All Prices Are Known</title>
<!--
If the checkout flow needs to know whether `PaymentRequest.canMakePayment()` will
return true even before all line items and their prices are known, then you can
instantiate PaymentRequest with dummy data and pre-query `.canMakePayment()`.
If you call `.canMakePayment()` multiple times, keep in mind that the first parameter
to the PaymentRequest constructor should contain the same method names and data.
-->
<meta name="viewport" content="width=device-width">
<style>
#success,
#legacy {
display: none;
}
</style>
</head>
<body>
<h1>Check Whether User Can Make Payment Before All Prices Are Known</h1>
<div id="intro">
<p>
If the checkout flow needs to know whether <code>PaymentRequest.canMakePayment()</code>
will return true even before all line items and their prices are known, then you can
instantiate PaymentRequest with dummy data and pre-query <code>.canMakePayment()</code>.
</p>
<p>
If you call <code>.canMakePayment()</code> multiple times, keep in mind that the first
parameter to the PaymentRequest constructor should contain the same method names and data.
</p>
<p>
Please note that no payments will be taken, this is just a front-end demo.
If you would like to try entering card details, you can use dummy data,
for example the card number <code>4111 1111 1111 1111</code>.
</p>
<button id="checkout-button">Checkout</button>
</div>
<div id="success">
<p>
Payment Request success. Demo complete. No payment has been taken.
</p>
</div>
<div id="legacy">
<p>
The Payment Request API is unsupported or was cancelled or failed,
so here we can proceed with our legacy web form (not implemented for this demo).
</p>
</div>
<script type="text/javascript">
var checkoutButton = document.getElementById('checkout-button');
var introPanel = document.getElementById('intro');
var successPanel = document.getElementById('success');
var legacyPanel = document.getElementById('legacy');
// Feature detection
if (window.PaymentRequest) {
// Payment Request is supported in this browser, so we can proceed to use it
var shouldCallPaymentRequest = true;
// Make a dummy payment request to check if user can make payment
new PaymentRequest(buildSupportedPaymentMethodData(),
{total: {label: 'Stub', amount: {currency: 'USD', value: '0.01'}}})
.canMakePayment()
.then(function(result) {
shouldCallPaymentRequest = result;
}).catch(function(error) {
console.log(error);
// The user may have turned off query ability in their privacy settings.
// Let's use PaymentRequest by default & fallback to legacy web form checkout.
shouldCallPaymentRequest = true;
});
checkoutButton.addEventListener('click', function() {
callServerToRetrieveCheckoutDetails();
});
} else {
checkoutButton.addEventListener('click', function() {
// For demo purposes
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
}
function callServerToRetrieveCheckoutDetails() {
// Here we would call to the server with the chosen line items, to retrieve
// a `Checkout` object with all of the prices and shipping options.
// But for the purposes of this demo, we will skip that and proceed immediately.
onServerCheckoutDetailsRetrieved(buildShoppingCartDetails());
}
function onServerCheckoutDetailsRetrieved(checkoutObject) {
// The server has constructed the `Checkout` object. Now we know all of the prices
// and shipping options.
if (shouldCallPaymentRequest) {
var request = new PaymentRequest(buildSupportedPaymentMethodData(),
checkoutObject);
request.show().then(function(paymentResponse) {
// Here we would process the payment. For this demo, simulate immediate success:
paymentResponse.complete('success')
.then(function() {
// For demo purposes:
introPanel.style.display = 'none';
successPanel.style.display = 'block';
});
}).catch(function(error) {
// Handle cancelled/failed payment. Fall back to legacy form. For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
} else {
// Fall back to legacy form. (We could redirect, but) for demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
}
}
function buildSupportedPaymentMethodData() {
// Example supported payment methods:
return [{
supportedMethods: 'basic-card',
data: {
supportedNetworks: ['visa', 'mastercard'],
supportedTypes: ['debit', 'credit']
}
}];
}
function buildShoppingCartDetails() {
// Hardcoded for demo purposes:
return {
id: 'order-123',
displayItems: [
{
label: 'Example item',
amount: {currency: 'USD', value: '1.00'}
}
],
total: {
label: 'Total',
amount: {currency: 'USD', value: '1.00'}
},
shippingOptions: [
{
id: 'example-shipping',
label: 'Example Shipping (2-3 Days)',
amount: {currency: 'USD', value: '0.50'}
}
]
};
}
</script>
</body>
</html> | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8">
<title>Feature Detect Support for Payment Request API</title>
<!--
If the user's browser supports PaymentRequest, the merchant page updates
the checkout button to use PaymentRequest instead of using legacy web forms.
-->
<meta name="viewport" content="width=device-width">
<style>
#success,
#legacy {
display: none;
}
</style>
</head>
<body>
<h1>Feature Detect Support for Payment Request API</h1>
<div id="intro">
<p>
This example shows how a legacy checkout form can be replaced by a Payment Request
- only for browsers that support it - using:
<code>if (window.PaymentRequest) { ... }</code>.
</p>
<p>
For the purposes of the demo, imagine you have chosen an item and now you need to
check out. Please note that no payments will be taken, this is just a front-end
demo. If you would like to try entering card details, you can use dummy data,
for example the card number <code>4111 1111 1111 1111</code>.
</p>
<button id="checkout-button">Checkout</button>
</div>
<div id="success">
<p>
Payment Request success. Demo complete. No payment has been taken.
</p>
</div>
<div id="legacy">
<p>
The Payment Request API is unsupported or was cancelled or failed,
so here we can proceed with our legacy web form (not implemented for this demo).
</p>
</div>
<script type="text/javascript">
var checkoutButton = document.getElementById('checkout-button');
var introPanel = document.getElementById('intro');
var successPanel = document.getElementById('success');
var legacyPanel = document.getElementById('legacy');
// Feature detection
if (window.PaymentRequest) {
// Payment Request is supported in this browser, so we can proceed to use it
checkoutButton.addEventListener('click', function() {
// Every click on the checkout button should use a new instance of PaymentRequest
// object, because PaymentRequest.show() can be called only once per instance.
var request = new PaymentRequest(buildSupportedPaymentMethodData(),
buildShoppingCartDetails());
request.show().then(function(paymentResponse) {
// Here we would process the payment. For this demo, simulate immediate success:
paymentResponse.complete('success')
.then(function() {
// For demo purposes:
introPanel.style.display = 'none';
successPanel.style.display = 'block';
});
}).catch(function(error) {
// Handle cancelled or failed payment. For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
});
} else {
// Payment Request is unsupported
checkoutButton.addEventListener('click', function() {
// For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
}
function buildSupportedPaymentMethodData() {
// Example supported payment methods:
return [{
supportedMethods: 'basic-card',
data: {
supportedNetworks: ['visa', 'mastercard'],
supportedTypes: ['debit', 'credit']
}
}];
}
function buildShoppingCartDetails() {
// Hardcoded for demo purposes:
return {
id: 'order-123',
displayItems: [
{
label: 'Example item',
amount: {currency: 'USD', value: '1.00'}
}
],
total: {
label: 'Total',
amount: {currency: 'USD', value: '1.00'}
}
};
}
</script>
</body>
</html> | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8">
<title>Show Additional User Interface After Successful Payment</title>
<!--
If the merchant desires to collect additional information not part of the API
(e.g., additional delivery instructions), the merchant can show a page with
additional <input type="text"> fields after the checkout.
-->
<meta name="viewport" content="width=device-width">
<style>
#additional-details,
#success,
#legacy {
display: none;
}
textarea {
display: block;
margin: 1em 0;
}
</style>
</head>
<body>
<h1>Show Additional User Interface After Successful Payment</h1>
<div id="intro">
<p>
If the merchant desires to collect additional information not part of the API
(e.g., additional delivery instructions), the merchant can show a page with
additional <code><input></code> fields after the checkout..
</p>
<p>
For the purposes of the demo, imagine you have chosen an item and now you need to
check out. Please note that no payments will be taken, this is just a front-end
demo. If you would like to try entering card details, you can use dummy data,
for example the card number <code>4111 1111 1111 1111</code>.
</p>
<button id="checkout-button">Checkout</button>
</div>
<div id="additional-details">
<label for="additional-delivery-instructions">Additional delivery instructions</label>
<textarea id="additional-delivery-instructions" value=""></textarea>
<button id="confirm-button">Confirm order</button>
</div>
<div id="success">
<p>
Payment Request success. Demo complete. No payment has been taken.
</p>
</div>
<div id="legacy">
<p>
The Payment Request API is unsupported or was cancelled or failed,
so here we can proceed with our legacy web form (not implemented for this demo).
</p>
</div>
<script type="text/javascript">
var checkoutButton = document.getElementById('checkout-button');
var confirmButton = document.getElementById('confirm-button');
var introPanel = document.getElementById('intro');
var additionalDetailsPanel = document.getElementById('additional-details');
var successPanel = document.getElementById('success');
var legacyPanel = document.getElementById('legacy');
// Feature detection
if (window.PaymentRequest) {
// Payment Request is supported in this browser, so we can proceed to use it
checkoutButton.addEventListener('click', function() {
// Every click on the checkout button should use a new instance of PaymentRequest
// object, because PaymentRequest.show() can be called only once per instance.
var request = new PaymentRequest(buildSupportedPaymentMethodData(),
buildShoppingCartDetails());
request.show().then(function(paymentResponse) {
// Here we would process the payment. For this demo, simulate immediate success:
paymentResponse.complete('success')
.then(function() {
// Request additional shipping address details
introPanel.style.display = 'none';
additionalDetailsPanel.style.display = 'block';
});
}).catch(function(error) {
// Handle cancelled or failed payment. For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
});
} else {
// Payment Request is unsupported
checkoutButton.addEventListener('click', function() {
// Here we would process the additional details. For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
}
confirmButton.addEventListener('click', function() {
// For demo purposes:
additionalDetailsPanel.style.display = 'none';
successPanel.style.display = 'block';
});
function buildSupportedPaymentMethodData() {
// Example supported payment methods:
return [{
supportedMethods: 'basic-card',
data: {
supportedNetworks: ['visa', 'mastercard'],
supportedTypes: ['debit', 'credit']
}
}];
}
function buildShoppingCartDetails() {
// Hardcoded for demo purposes:
return {
id: 'order-123',
displayItems: [
{
label: 'Example item',
amount: {currency: 'USD', value: '1.00'}
}
],
total: {
label: 'Total',
amount: {currency: 'USD', value: '1.00'}
}
};
}
</script>
</body>
</html> | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang=en>
<head>
<meta charset="UTF-8">
<title>Recommend a Payment App when User Has No Apps</title>
<!--
If you select to pay with BobPay on this merchant page, it tries to call
`PaymentRequest.show()`, while intercepting the NOT_SUPPORTED_ERR exception. If this
payment method is not supported, it redirects to the download page for BobPay.
-->
<meta name="viewport" content="width=device-width">
<style>
#success,
#legacy {
display: none;
}
</style>
</head>
<body>
<h1>Recommend a Payment App when User Has No Apps</h1>
<div id="intro">
<p>
In this example, if you select to pay with BobPay on this merchant page, it tries to
call <code>PaymentRequest.show()</code>, while intercepting the
<code>NOT_SUPPORTED_ERR exception</code>. If this payment method is not supported,
it redirects to the download page for BobPay.
</p>
<p>
For the purposes of the demo, imagine you have chosen an item and
now you need to check out.
</p>
<button id="checkout-button">Checkout</button>
</div>
<div id="success">
<p>
Payment Request success. Demo complete. No payment has been taken.
</p>
</div>
<div id="legacy">
<p>
The Payment Request API is unsupported or was cancelled or failed.
Here we can proceed with a fallback (not implemented for this demo).
</p>
</div>
<script type="text/javascript">
var checkoutButton = document.getElementById('checkout-button');
var introPanel = document.getElementById('intro');
var successPanel = document.getElementById('success');
var legacyPanel = document.getElementById('legacy');
// Feature detection
if (window.PaymentRequest) {
// Payment Request is supported in this browser, so we can proceed to use it
checkoutButton.addEventListener('click', function() {
var request = new PaymentRequest(buildSupportedPaymentMethodData(),
buildShoppingCartDetails());
request.show().then(function(paymentResponse) {
// Here we would process the payment. For this demo, simulate immediate success:
paymentResponse.complete('success')
.then(function() {
// For demo purposes:
introPanel.style.display = 'none';
successPanel.style.display = 'block';
});
}).catch(function(error) {
if (error.code == DOMException.NOT_SUPPORTED_ERR) {
// BobPay not currently supported. Usually we might now wish to redirect
// to a signup page and we could pass our current URL so it could redirect
// (or link) back to this page afterwards. For this demo, we are just
// redirecting to the BobPay download page.
window.location.href =
'https://bobpay.xyz/#download';
} else {
// Other kinds of errors; cancelled or failed payment. For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
}
});
});
} else {
// Payment Request is unsupported
checkoutButton.addEventListener('click', function() {
// For demo purposes:
introPanel.style.display = 'none';
legacyPanel.style.display = 'block';
});
}
function buildSupportedPaymentMethodData() {
return [{
supportedMethods: 'https://emerald-eon.appspot.com/bobpay'
}];
}
function buildShoppingCartDetails() {
// Hardcoded for demo purposes:
return {
id: 'order-123',
displayItems: [
{
label: 'Example item',
amount: {currency: 'USD', value: '1.00'}
}
],
total: {
label: 'Total',
amount: {currency: 'USD', value: '1.00'}
}
};
}
</script>
</body>
</html> | {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
# Examples
* [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).
* [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).
* [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).
* [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).
* [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).
* [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).
# External Examples
* [Payment Request Samples](https://googlechrome.github.io/samples/paymentrequest/) from Google
* [Payment Request Codelab](https://codelabs.developers.google.com/codelabs/payment-request-api/#0) from Google
* [VeggieShop](https://github.com/pjbazin/wpwg-demo) e-commerce website demo and source code
* [WhiteCollar](https://github.com/pjbazin/wpwg-demo/tree/master/WhiteCollar) web payment app demo and source code
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<title>IndexedDB Example</title>
<link href="main.css" rel="stylesheet" type="text/css" />
<script
type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" defer>
</script>
<script src="main.js" defer></script>
</head>
<body>
<h1>IndexedDB Demo: storing blobs, e-publication example</h1>
<div class="note">
<p>Works and tested with:</p>
<div id="compat"></div>
</div>
<div id="msg"></div>
<form id="register-form">
<table>
<tbody>
<tr>
<td>
<label for="pub-title" class="required">Title:</label>
</td>
<td>
<input type="text" id="pub-title" name="pub-title" />
</td>
</tr>
<tr>
<td>
<label for="pub-biblioid" class="required"
>Bibliographic ID:<br />
<span class="note">(ISBN, ISSN, etc.)</span>
</label>
</td>
<td>
<input type="text" id="pub-biblioid" name="pub-biblioid" />
</td>
</tr>
<tr>
<td>
<label for="pub-year">
Year:
</label>
</td>
<td>
<input type="number" id="pub-year" name="pub-year" />
</td>
</tr>
</tbody>
<tbody>
<tr>
<td>
<label for="pub-file">
File image:
</label>
</td>
<td>
<input type="file" id="pub-file" />
</td>
</tr>
<tr>
<td>
<label for="pub-file-url">
Online-file image URL:<br />
<span class="note">(same origin URL)</span>
</label>
</td>
<td>
<input type="text" id="pub-file-url" name="pub-file-url" />
</td>
</tr>
</tbody>
</table>
<div class="button-pane">
<input type="button" id="add-button" value="Add Publication" />
<input type="reset" id="register-form-reset" />
</div>
</form>
<form id="delete-form">
<table>
<tbody>
<tr>
<td>
<label for="pub-biblioid-to-delete">
Bibliographic ID:<br />
<span class="note">(ISBN, ISSN, etc.)</span>
</label>
</td>
<td>
<input
type="text"
id="pub-biblioid-to-delete"
name="pub-biblioid-to-delete"
/>
</td>
</tr>
<tr>
<td>
<label for="key-to-delete">
Key:<br />
<span class="note">(for example 1, 2, 3, etc.)</span>
</label>
</td>
<td>
<input type="text" id="key-to-delete" name="key-to-delete" />
</td>
</tr>
</tbody>
</table>
<div class="button-pane">
<input type="button" id="delete-button" value="Delete Publication" />
<input
type="button"
id="clear-store-button"
value="Clear the whole store"
class="destructive"
/>
</div>
</form>
<form id="search-form">
<div class="button-pane">
<input
type="button"
id="search-list-button"
value="List database content"
/>
</div>
</form>
<div>
<div id="pub-msg"></div>
<div id="pub-viewer"></div>
<ul id="pub-list"></ul>
</div>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
body {
font-family: sans-serif;
}
table {
border-collapse: collapse;
}
form {
background-color: #cccccc;
border-radius: 0.3em;
display: inline-block;
margin-bottom: 0.5em;
padding: 1em;
}
table {
border-collapse: collapse;
}
input {
padding: 0.3em;
border-color: #cccccc;
border-radius: 0.3em;
}
.required:after {
content: "*";
color: red;
}
.button-pane {
margin-top: 1em;
}
#pub-viewer {
float: right;
width: 48%;
height: 20em;
border: solid #d092ff 0.1em;
}
#pub-viewer iframe {
width: 100%;
height: 100%;
}
#pub-list {
width: 46%;
background-color: #eeeeee;
border-radius: 0.3em;
}
#pub-list li {
padding-top: 0.5em;
padding-bottom: 0.5em;
padding-right: 0.5em;
}
#msg {
margin-bottom: 1em;
}
.action-success {
padding: 0.5em;
color: #00d21e;
background-color: #eeeeee;
border-radius: 0.2em;
}
.action-failure {
padding: 0.5em;
color: #ff1408;
background-color: #eeeeee;
border-radius: 0.2em;
}
.note {
font-size: smaller;
}
.destructive {
background-color: orange;
}
.destructive:hover {
background-color: #ff8000;
}
.destructive:active {
background-color: red;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
(function () {
var COMPAT_ENVS = [
['Firefox', ">= 16.0"],
['Google Chrome',
">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"]
];
var compat = $('#compat');
compat.empty();
compat.append('<ul id="compat-list"></ul>');
COMPAT_ENVS.forEach(function(val, idx, array) {
$('#compat-list').append('<li>' + val[0] + ': ' + val[1] + '</li>');
});
const DB_NAME = 'mdn-demo-indexeddb-epublications';
const DB_VERSION = 1; // Use a long long for this value (don't use a float)
const DB_STORE_NAME = 'publications';
var db;
// Used to keep track of which view is displayed to avoid uselessly reloading it
var current_view_pub_key;
function openDb() {
console.log("openDb ...");
var req = indexedDB.open(DB_NAME, DB_VERSION);
req.onsuccess = function (evt) {
// Equal to: db = req.result;
db = this.result;
console.log("openDb DONE");
};
req.onerror = function (evt) {
console.error("openDb:", evt.target.errorCode);
};
req.onupgradeneeded = function (evt) {
console.log("openDb.onupgradeneeded");
var store = evt.currentTarget.result.createObjectStore(
DB_STORE_NAME, { keyPath: 'id', autoIncrement: true });
store.createIndex('biblioid', 'biblioid', { unique: true });
store.createIndex('title', 'title', { unique: false });
store.createIndex('year', 'year', { unique: false });
};
}
/**
* @param {string} store_name
* @param {string} mode either "readonly" or "readwrite"
*/
function getObjectStore(store_name, mode) {
var tx = db.transaction(store_name, mode);
return tx.objectStore(store_name);
}
function clearObjectStore() {
var store = getObjectStore(DB_STORE_NAME, 'readwrite');
var req = store.clear();
req.onsuccess = function(evt) {
displayActionSuccess("Store cleared");
displayPubList(store);
};
req.onerror = function (evt) {
console.error("clearObjectStore:", evt.target.errorCode);
displayActionFailure(this.error);
};
}
function getBlob(key, store, success_callback) {
var req = store.get(key);
req.onsuccess = function(evt) {
var value = evt.target.result;
if (value)
success_callback(value.blob);
};
}
/**
* @param {IDBObjectStore=} store
*/
function displayPubList(store) {
console.log("displayPubList");
if (typeof store == 'undefined')
store = getObjectStore(DB_STORE_NAME, 'readonly');
var pub_msg = $('#pub-msg');
pub_msg.empty();
var pub_list = $('#pub-list');
pub_list.empty();
// Resetting the iframe so that it doesn't display previous content
newViewerFrame();
var req;
req = store.count();
// Requests are executed in the order in which they were made against the
// transaction, and their results are returned in the same order.
// Thus the count text below will be displayed before the actual pub list
// (not that it is algorithmically important in this case).
req.onsuccess = function(evt) {
pub_msg.append('<p>There are <strong>' + evt.target.result +
'</strong> record(s) in the object store.</p>');
};
req.onerror = function(evt) {
console.error("add error", this.error);
displayActionFailure(this.error);
};
var i = 0;
req = store.openCursor();
req.onsuccess = function(evt) {
var cursor = evt.target.result;
// If the cursor is pointing at something, ask for the data
if (cursor) {
console.log("displayPubList cursor:", cursor);
req = store.get(cursor.key);
req.onsuccess = function (evt) {
var value = evt.target.result;
var list_item = $('<li>' +
'[' + cursor.key + '] ' +
'(biblioid: ' + value.biblioid + ') ' +
value.title +
'</li>');
if (value.year != null)
list_item.append(' - ' + value.year);
if (value.hasOwnProperty('blob') &&
typeof value.blob != 'undefined') {
var link = $('<a href="' + cursor.key + '">File</a>');
link.on('click', function() { return false; });
link.on('mouseenter', function(evt) {
setInViewer(evt.target.getAttribute('href')); });
list_item.append(' / ');
list_item.append(link);
} else {
list_item.append(" / No attached file");
}
pub_list.append(list_item);
};
// Move on to the next object in store
cursor.continue();
// This counter serves only to create distinct ids
i++;
} else {
console.log("No more entries");
}
};
}
function newViewerFrame() {
var viewer = $('#pub-viewer');
viewer.empty();
var iframe = $('<iframe />');
viewer.append(iframe);
return iframe;
}
function setInViewer(key) {
console.log("setInViewer:", arguments);
key = Number(key);
if (key == current_view_pub_key)
return;
current_view_pub_key = key;
var store = getObjectStore(DB_STORE_NAME, 'readonly');
getBlob(key, store, function(blob) {
console.log("setInViewer blob:", blob);
var iframe = newViewerFrame();
// It is not possible to set a direct link to the
// blob to provide a mean to directly download it.
if (blob.type == 'text/html') {
var reader = new FileReader();
reader.onload = (function(evt) {
var html = evt.target.result;
iframe.load(function() {
$(this).contents().find('html').html(html);
});
});
reader.readAsText(blob);
} else if (blob.type.indexOf('image/') == 0) {
iframe.load(function() {
var img_id = 'image-' + key;
var img = $('<img id="' + img_id + '"/>');
$(this).contents().find('body').html(img);
var obj_url = window.URL.createObjectURL(blob);
$(this).contents().find('#' + img_id).attr('src', obj_url);
window.URL.revokeObjectURL(obj_url);
});
} else if (blob.type == 'application/pdf') {
$('*').css('cursor', 'wait');
var obj_url = window.URL.createObjectURL(blob);
iframe.load(function() {
$('*').css('cursor', 'auto');
});
iframe.attr('src', obj_url);
window.URL.revokeObjectURL(obj_url);
} else {
iframe.load(function() {
$(this).contents().find('body').html("No view available");
});
}
});
}
/**
* @param {string} biblioid
* @param {string} title
* @param {number} year
* @param {string} url the URL of the image to download and store in the local
* IndexedDB database. The resource behind this URL is subjected to the
* "Same origin policy", thus for this method to work, the URL must come from
* the same origin as the web site/app this code is deployed on.
*/
function addPublicationFromUrl(biblioid, title, year, url) {
console.log("addPublicationFromUrl:", arguments);
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// Setting the wanted responseType to "blob"
// http://www.w3.org/TR/XMLHttpRequest2/#the-response-attribute
xhr.responseType = 'blob';
xhr.onload = function (evt) {
if (xhr.status == 200) {
console.log("Blob retrieved");
var blob = xhr.response;
console.log("Blob:", blob);
addPublication(biblioid, title, year, blob);
} else {
console.error("addPublicationFromUrl error:",
xhr.responseText, xhr.status);
}
};
xhr.send();
// We can't use jQuery here because as of jQuery 1.8.3 the new "blob"
// responseType is not handled.
// http://bugs.jquery.com/ticket/11461
// http://bugs.jquery.com/ticket/7248
// $.ajax({
// url: url,
// type: 'GET',
// xhrFields: { responseType: 'blob' },
// success: function(data, textStatus, jqXHR) {
// console.log("Blob retrieved");
// console.log("Blob:", data);
// // addPublication(biblioid, title, year, data);
// },
// error: function(jqXHR, textStatus, errorThrown) {
// console.error(errorThrown);
// displayActionFailure("Error during blob retrieval");
// }
// });
}
/**
* @param {string} biblioid
* @param {string} title
* @param {number} year
* @param {Blob=} blob
*/
function addPublication(biblioid, title, year, blob) {
console.log("addPublication arguments:", arguments);
var obj = { biblioid: biblioid, title: title, year: year };
if (typeof blob != 'undefined')
obj.blob = blob;
var store = getObjectStore(DB_STORE_NAME, 'readwrite');
var req;
try {
req = store.add(obj);
} catch (e) {
if (e.name == 'DataCloneError')
displayActionFailure("This engine doesn't know how to clone a Blob, " +
"use Firefox");
throw e;
}
req.onsuccess = function (evt) {
console.log("Insertion in DB successful");
displayActionSuccess();
displayPubList(store);
};
req.onerror = function() {
console.error("addPublication error", this.error);
displayActionFailure(this.error);
};
}
/**
* @param {string} biblioid
*/
function deletePublicationFromBib(biblioid) {
console.log("deletePublication:", arguments);
var store = getObjectStore(DB_STORE_NAME, 'readwrite');
var req = store.index('biblioid');
req.get(biblioid).onsuccess = function(evt) {
if (typeof evt.target.result == 'undefined') {
displayActionFailure("No matching record found");
return;
}
deletePublication(evt.target.result.id, store);
};
req.onerror = function (evt) {
console.error("deletePublicationFromBib:", evt.target.errorCode);
};
}
/**
* @param {number} key
* @param {IDBObjectStore=} store
*/
function deletePublication(key, store) {
console.log("deletePublication:", arguments);
if (typeof store == 'undefined')
store = getObjectStore(DB_STORE_NAME, 'readwrite');
// As per spec http://www.w3.org/TR/IndexedDB/#object-store-deletion-operation
// the result of the Object Store Deletion Operation algorithm is
// undefined, so it's not possible to know if some records were actually
// deleted by looking at the request result.
var req = store.get(key);
req.onsuccess = function(evt) {
var record = evt.target.result;
console.log("record:", record);
if (typeof record == 'undefined') {
displayActionFailure("No matching record found");
return;
}
// Warning: The exact same key used for creation needs to be passed for
// the deletion. If the key was a Number for creation, then it needs to
// be a Number for deletion.
var deleteReq = store.delete(key);
deleteReq.onsuccess = function(evt) {
console.log("evt:", evt);
console.log("evt.target:", evt.target);
console.log("evt.target.result:", evt.target.result);
console.log("delete successful");
displayActionSuccess("Deletion successful");
displayPubList(store);
};
deleteReq.onerror = function (evt) {
console.error("deletePublication:", evt.target.errorCode);
};
};
req.onerror = function (evt) {
console.error("deletePublication:", evt.target.errorCode);
};
}
function displayActionSuccess(msg) {
msg = typeof msg != 'undefined' ? "Success: " + msg : "Success";
$('#msg').html('<span class="action-success">' + msg + '</span>');
}
function displayActionFailure(msg) {
msg = typeof msg != 'undefined' ? "Failure: " + msg : "Failure";
$('#msg').html('<span class="action-failure">' + msg + '</span>');
}
function resetActionStatus() {
console.log("resetActionStatus ...");
$('#msg').empty();
console.log("resetActionStatus DONE");
}
function addEventListeners() {
console.log("addEventListeners");
$('#register-form-reset').click(function(evt) {
resetActionStatus();
});
$('#add-button').click(function(evt) {
console.log("add ...");
var title = $('#pub-title').val();
var biblioid = $('#pub-biblioid').val();
if (!title || !biblioid) {
displayActionFailure("Required field(s) missing");
return;
}
var year = $('#pub-year').val();
if (year != '') {
// Better use Number.isInteger if the engine has EcmaScript 6
if (isNaN(year)) {
displayActionFailure("Invalid year");
return;
}
year = Number(year);
} else {
year = null;
}
var file_input = $('#pub-file');
var selected_file = file_input.get(0).files[0];
console.log("selected_file:", selected_file);
// Keeping a reference on how to reset the file input in the UI once we
// have its value, but instead of doing that we rather use a "reset" type
// input in the HTML form.
//file_input.val(null);
var file_url = $('#pub-file-url').val();
if (selected_file) {
addPublication(biblioid, title, year, selected_file);
} else if (file_url) {
addPublicationFromUrl(biblioid, title, year, file_url);
} else {
addPublication(biblioid, title, year);
}
});
$('#delete-button').click(function(evt) {
console.log("delete ...");
var biblioid = $('#pub-biblioid-to-delete').val();
var key = $('#key-to-delete').val();
if (biblioid != '') {
deletePublicationFromBib(biblioid);
} else if (key != '') {
// Better use Number.isInteger if the engine has EcmaScript 6
if (key == '' || isNaN(key)) {
displayActionFailure("Invalid key");
return;
}
key = Number(key);
deletePublication(key);
}
});
$('#clear-store-button').click(function(evt) {
clearObjectStore();
});
var search_button = $('#search-list-button');
search_button.click(function(evt) {
displayPubList();
});
}
openDb();
addEventListeners();
})(); // Immediately-Invoked Function Expression (IIFE)
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Resize observer border-radius test</title>
<style>
html {
height: 100%;
}
body {
height: inherit;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}
div {
background-color: green;
width: 50%;
height: 50%;
}
</style>
</head>
<body>
<div>
</div>
<script>
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
if (entry.contentBoxSize) {
// The standard makes contentBoxSize an array...
if (entry.contentBoxSize[0]) {
entry.target.style.borderRadius = Math.min(100, (entry.contentBoxSize[0].inlineSize/10) +
(entry.contentBoxSize[0].blockSize/10)) + 'px';
} else {
// ...but old versions of Firefox treat it as a single item
entry.target.style.borderRadius = Math.min(100, (entry.contentBoxSize.inlineSize/10) +
(entry.contentBoxSize.blockSize/10)) + 'px';
}
} else {
entry.target.style.borderRadius = Math.min(100, (entry.contentRect.width/10) +
(entry.contentRect.height/10)) + 'px';
}
}
});
resizeObserver.observe(document.querySelector('div'));
</script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Resize observer text test</title>
<style>
html {
height: 100%;
font-family: 'helvetica neue', arial, sans-serif;
}
body {
height: inherit;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
}
body > div {
background-color: #eee;
border: 1px solid #ccc;
padding: 20px;
width: 50%;
min-width: 320px;
}
h1 {
margin: 0;
}
p {
line-height: 1.5;
}
form {
width: 100%;
}
form > div {
display: flex;
}
form label {
flex: 2;
}
form input {
flex: 3;
}
input[type="checkbox"] {
height: 2rem;
}
</style>
</head>
<body>
<div>
<h1>So what happened?</h1>
<p>And remember, don't do anything that affects anything, unless it turns out you were supposed to, in which case, for the love of God, don't not do it! Ow, my spirit! I don't want to be rescued. You guys aren't Santa! You're not even robots. I've got to find a way to escape the horrible ravages of youth. Suddenly, I'm going to the bathroom like clockwork, every three hours. And those jerks at Social Security stopped sending me checks. Now 'I' have to pay 'them'!</p>
<form>
<div><label>Observer enabled:</label><input type="checkbox" checked></div>
<div><label>Adjust width:</label><input type="range" value="600" min="300" max="1300"></div>
</form>
</div>
<script>
if(window.ResizeObserver) {
const h1Elem = document.querySelector('h1');
const pElem = document.querySelector('p');
const divElem = document.querySelector('body > div');
const slider = document.querySelector('input[type="range"]');
const checkbox = document.querySelector('input[type="checkbox"]');
divElem.style.width = '600px';
slider.addEventListener('input', () => {
divElem.style.width = slider.value + 'px';
})
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
if(entry.contentBoxSize) {
// The standard makes contentBoxSize an array...
if (entry.contentBoxSize[0]) {
h1Elem.style.fontSize = Math.max(1.5, entry.contentBoxSize[0].inlineSize/200) + 'rem';
pElem.style.fontSize = Math.max(1, entry.contentBoxSize[0].inlineSize/600) + 'rem';
} else {
// ...but old versions of Firefox treat it as a single item
h1Elem.style.fontSize = Math.max(1.5, entry.contentBoxSize.inlineSize/200) + 'rem';
pElem.style.fontSize = Math.max(1, entry.contentBoxSize.inlineSize/600) + 'rem';
}
} else {
h1Elem.style.fontSize = Math.max(1.5, entry.contentRect.width/200) + 'rem';
pElem.style.fontSize = Math.max(1, entry.contentRect.width/600) + 'rem';
}
}
console.log('Size changed');
});
resizeObserver.observe(divElem);
checkbox.addEventListener('change', () => {
if(checkbox.checked) {
resizeObserver.observe(divElem);
} else {
resizeObserver.unobserve(divElem);
}
});
} else {
console.log('Resize observer not supported!');
}
</script>
</body>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
# indexeddb-examples
Code examples that accompany the MDN IndexedDB documentation – https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
The "idbcursor" directory contains a very simple IndexedDB example to demonstrate the usage of IDBCursor. See [https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor) for relevant reference pages. [View the example live](http://mdn.github.io/dom-examples/indexeddb-examples/idbcursor/).
The "idbindex" directory contains a very simple IndexedDB example to demonstrate the usage of IDBIndex. See [https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex) for relevant reference pages. [Run the example live](http://mdn.github.io/dom-examples/indexeddb-examples/idbindex/).
The "idbkeyrange" directory contains a very simple IndexedDB example to demonstrate the usage of IDBKeyRange. See [https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange) for relevant reference pages. [Run the example live](http://mdn.github.io/dom-examples/indexeddb-examples/idbkeyrange/).
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<title>Basic IDBIndex example — contacts directory</title>
<link
href="http://fonts.googleapis.com/css?family=Arvo|Bevan"
rel="stylesheet"
type="text/css"
/>
<link href="style/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h1>Basic IDBIndex example — contacts directory</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Last name</th>
<th>First name</th>
<th>Job title</th>
<th>Company</th>
<th>E-mail</th>
<th>Phone</th>
<th>Age</th>
</tr>
</thead>
<tbody></tbody>
</table>
<p>
Click/focus each table column heading to sort the data by that column.
</p>
</body>
<script src="scripts/main.js"></script>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
// create an instance of a db object for us to store the IDB data in
var db;
var activeIndex;
var contacts = [
{ id: 1, fName: 'Brian', lName: 'Damage', jTitle: 'Master of Synergies', company: 'Acme', eMail: '[email protected]', phone: '+441210000000', age: 37 },
{ id: 2, fName: 'Ted', lName: 'Maul', jTitle: 'Chief Reporter', company: 'Brass eye', eMail: '[email protected]', phone: '+442081111111', age: 46 },
{ id: 3, fName: 'Mr', lName: 'Bungle', jTitle: 'Bad Clown', company: 'Stub a Dub', eMail: '[email protected]', phone: '+1508888888', age: 50 },
{ id: 4, fName: 'Richard', lName: 'James', jTitle: 'Sound Engineer', company: 'Aphex Twin', eMail: '[email protected]', phone: '+1517777777', age: 43 },
{ id: 5, fName: 'Brian', lName: 'Umlaut', jTitle: 'Shredmeister', company: 'Minions of metal', eMail: '[email protected]', phone: '+14086666666', age: 40 },
{ id: 6, fName: 'Jonathan', lName: 'Crane', jTitle: 'Freelance Psychologist', company: 'Arkham', eMail: '[email protected]', phone: 'n/a', age: 38 },
{ id: 7, fName: 'Julian', lName: 'Day', jTitle: 'Schedule Keeper', company: 'Arkham', eMail: '[email protected]', phone: 'n/a', age: 43 },
{ id: 8, fName: 'Bolivar', lName: 'Trask', jTitle: 'Head of R&D', company: 'Trask', eMail: '[email protected]', phone: '+14095555555', age: 55 },
{ id: 9, fName: 'Cloud', lName: 'Strife', jTitle: 'Weapons Instructor', company: 'Avalanche', eMail: '[email protected]', phone: '+17083333333', age: 24 },
{ id: 10, fName: 'Bilbo', lName: 'Bagshot', jTitle: 'Comic Shop Owner', company: 'Fantasy Bazaar', eMail: '[email protected]', phone: '+12084444444', age: 43 }
];
// all the variables we need for the app
var tableEntry = document.querySelector('tbody');
window.onload = function() {
// In the following line, you should include the prefixes of implementations you want to test.
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// DON'T use "var indexedDB = ..." if you're not in a function.
// Moreover, you may need references to some window.IDB* objects:
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
var DBOpenRequest = window.indexedDB.open('contactsList', 1);
DBOpenRequest.onsuccess = function(event) {
db = DBOpenRequest.result;
populateData();
};
DBOpenRequest.onupgradeneeded = function(event) {
var db = event.target.result;
db.onerror = function(event) {
console.log('Error loading database.');
};
var objectStore = db.createObjectStore('contactsList', { keyPath: 'id' });
objectStore.createIndex('lName', 'lName', { unique: false });
objectStore.createIndex('fName', 'fName', { unique: false });
objectStore.createIndex('jTitle', 'jTitle', { unique: false });
objectStore.createIndex('company', 'company', { unique: false });
objectStore.createIndex('eMail', 'eMail', { unique: true });
objectStore.createIndex('phone', 'phone', { unique: false });
objectStore.createIndex('age', 'age', { unique: false });
};
function populateData() {
var transaction = db.transaction(['contactsList'], 'readwrite');
var objectStore = transaction.objectStore('contactsList');
for(i = 0; i < contacts.length ; i++) {
var request = objectStore.put(contacts[i]);
};
transaction.oncomplete = function() {
displayDataByKey();
};
};
var thControls = document.querySelectorAll('th');
for(i = 0; i < thControls.length; i++) {
var activeThead = thControls[i];
activeThead.onclick = function(e) {
activeIndex = e.target.innerHTML;
if(activeIndex == 'ID') {
displayDataByKey();
} else {
if(activeIndex == "Last name") {
displayDataByIndex('lName');
} else if(activeIndex == "First name") {
displayDataByIndex('fName');
} else if(activeIndex == "Job title") {
displayDataByIndex('jTitle');
} else if(activeIndex == "Company") {
displayDataByIndex('company');
} else if(activeIndex == "E-mail") {
displayDataByIndex('eMail');
} else if(activeIndex == "Phone") {
displayDataByIndex('phone');
} else if(activeIndex == "Age") {
displayDataByIndex('age');
}
}
}
}
function displayDataByKey() {
tableEntry.innerHTML = '';
var transaction = db.transaction(['contactsList'], 'readonly');
var objectStore = transaction.objectStore('contactsList');
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var tableRow = document.createElement('tr');
tableRow.innerHTML = '<td>' + cursor.value.id + '</td>'
+ '<td>' + cursor.value.lName + '</td>'
+ '<td>' + cursor.value.fName + '</td>'
+ '<td>' + cursor.value.jTitle + '</td>'
+ '<td>' + cursor.value.company + '</td>'
+ '<td>' + cursor.value.eMail + '</td>'
+ '<td>' + cursor.value.phone + '</td>'
+ '<td>' + cursor.value.age + '</td>';
tableEntry.appendChild(tableRow);
cursor.continue();
} else {
console.log('Entries all displayed.');
}
};
};
function displayDataByIndex(activeIndex) {
tableEntry.innerHTML = '';
var transaction = db.transaction(['contactsList'], 'readonly');
var objectStore = transaction.objectStore('contactsList');
var myIndex = objectStore.index(activeIndex);
console.log(myIndex.name);
console.log(myIndex.objectStore);
console.log(myIndex.keyPath);
console.log(myIndex.multiEntry);
console.log(myIndex.unique);
var countRequest = myIndex.count();
countRequest.onsuccess = function() {
console.log(countRequest.result);
}
if(activeIndex == 'fName') {
var getRequest = myIndex.get('Mr');
getRequest.onsuccess = function() {
console.log(getRequest.result);
}
}
if(activeIndex == 'lName') {
var getKeyRequest = myIndex.getKey('Bungle');
getKeyRequest.onsuccess = function() {
console.log(getKeyRequest.result);
}
}
myIndex.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var tableRow = document.createElement('tr');
tableRow.innerHTML = '<td>' + cursor.value.id + '</td>'
+ '<td>' + cursor.value.lName + '</td>'
+ '<td>' + cursor.value.fName + '</td>'
+ '<td>' + cursor.value.jTitle + '</td>'
+ '<td>' + cursor.value.company + '</td>'
+ '<td>' + cursor.value.eMail + '</td>'
+ '<td>' + cursor.value.phone + '</td>'
+ '<td>' + cursor.value.age + '</td>';
tableEntry.appendChild(tableRow);
cursor.continue();
} else {
console.log('Entries all displayed.');
}
};
};
};
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
html,
body {
margin: 0;
font-family: "Arvo", serif;
font-size: 100%/1.5 serif;
}
h1 {
text-align: center;
font-family: "Bevan", cursive;
font-size: 4rem;
letter-spacing: 0.2rem;
text-shadow: 1px 1px 1px #eee4fe, 2px 2px 1px #eee4fe, 3px 3px 1px #7b62ae,
4px 4px 1px #7b62ae, 5px 5px 1px #261758, 6px 6px 1px #261758;
}
table {
width: 75%;
font-size: 1.3rem;
letter-spacing: 0.1rem;
margin: 0 auto;
border-collapse: collapse;
box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.5);
}
table,
thead {
background: white;
}
tbody {
border: 1px solid #eee4fe;
}
thead {
border: 1px solid #261758;
}
th {
font-size: 1.7rem;
padding: 1.2rem;
text-align: left;
background: linear-gradient(to bottom, #261758, #666778);
color: white;
text-shadow: 1px 1px 1px black;
cursor: pointer;
}
th:hover,
th:focus {
color: #ddd;
border: 0;
}
th:active {
color: #bbb;
}
td {
padding: 1rem;
border-left: 1px solid #7b62ae;
border-right: 1px solid #7b62ae;
}
td:first-child {
border-left: none;
}
td:last-child {
border-right: none;
}
tr:nth-child(even) {
background: #eee4fe;
}
p {
font-size: 1.5rem;
text-align: center;
}
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=380" />
<title>Basic IDBCursor example — Rush studio albums 74-85</title>
<link href="style/style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<h1>Basic IDBCursor example — Rush studio albums 74-85</h1>
<ul></ul>
<button class="continue">Display all results</button>
<button class="advance">Show every other result</button>
<button class="delete">
Kill Grace under pressure (it's not that great)
</button>
<button class="update">Update "A farewell.." year</button>
<button class="direction">Display albums upsidedown</button>
</body>
<script src="scripts/main.js"></script>
</html>
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |
// create an instance of a db object for us to store the IDB data in
var db;
var records = [
{ albumTitle: 'Power windows', year: 1985 },
{ albumTitle: 'Grace under pressure', year: 1984 },
{ albumTitle: 'Signals', year: 1982 },
{ albumTitle: 'Moving pictures', year: 1981 },
{ albumTitle: 'Permanent waves', year: 1980 },
{ albumTitle: 'Hemispheres', year: 1978 },
{ albumTitle: 'A farewell to kings', year: 1977 },
{ albumTitle: '2112', year: 1976 },
{ albumTitle: 'Caress of steel', year: 1975 },
{ albumTitle: 'Fly by night', year: 1975 },
{ albumTitle: 'Rush', year: 1974 }
];
// all the variables we need for the app
var list = document.querySelector('ul');
var advance = document.querySelector('.advance');
var useContinue = document.querySelector('.continue');
var useDelete = document.querySelector('.delete');
var update = document.querySelector('.update');
var changeDirection = document.querySelector('.direction');
window.onload = function() {
// In the following line, you should include the prefixes of implementations you want to test.
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
// DON'T use "var indexedDB = ..." if you're not in a function.
// Moreover, you may need references to some window.IDB* objects:
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
// (Mozilla has never prefixed these objects, so we don't need window.mozIDB*)
var DBOpenRequest = window.indexedDB.open('albumLists', 1);
DBOpenRequest.onsuccess = function(event) {
db = DBOpenRequest.result;
populateData();
};
DBOpenRequest.onupgradeneeded = function(event) {
var db = event.target.result;
db.onerror = function(event) {
note.innerHTML += '<li>Error loading database.</li>';
};
var objectStore = db.createObjectStore('rushAlbumList', { keyPath: 'albumTitle' });
objectStore.createIndex('year', 'year', { unique: false });
};
function populateData() {
var transaction = db.transaction(['rushAlbumList'], 'readwrite');
var objectStore = transaction.objectStore('rushAlbumList');
for(i = 0; i < records.length ; i++) {
var request = objectStore.put(records[i]);
};
transaction.oncomplete = function() {
displayData();
};
};
useContinue.onclick = function() {
displayData();
}
function displayData() {
list.innerHTML = '';
var transaction = db.transaction(['rushAlbumList'], 'readonly');
var objectStore = transaction.objectStore('rushAlbumList');
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var listItem = document.createElement('li');
listItem.innerHTML = '<strong>' + cursor.value.albumTitle + '</strong>, ' + cursor.value.year;
list.appendChild(listItem);
//console.log(cursor.source);
//console.log(cursor.key);
//console.log(cursor.primaryKey);
//console.log(cursor.value);
cursor.continue();
} else {
console.log('Entries all displayed.');
}
};
};
advance.onclick = function() {
advanceResult();
};
function advanceResult() {
list.innerHTML = '';
var transaction = db.transaction(['rushAlbumList'], 'readonly');
var objectStore = transaction.objectStore('rushAlbumList');
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var listItem = document.createElement('li');
listItem.innerHTML = '<strong>' + cursor.value.albumTitle + '</strong>, ' + cursor.value.year;
list.appendChild(listItem);
cursor.advance(2);
} else {
console.log('Every other entry displayed.');
}
};
};
useDelete.onclick = function() {
deleteResult();
};
function deleteResult() {
list.innerHTML = '';
var transaction = db.transaction(['rushAlbumList'], 'readwrite');
var objectStore = transaction.objectStore('rushAlbumList');
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
if(cursor.value.albumTitle === 'Grace under pressure') {
var request = cursor.delete();
request.onsuccess = function() {
console.log('Deleted that mediocre album from 1984. Even Power windows is better.');
};
} else {
var listItem = document.createElement('li');
listItem.innerHTML = '<strong>' + cursor.value.albumTitle + '</strong>, ' + cursor.value.year;
list.appendChild(listItem);
}
cursor.continue();
} else {
console.log('Entries displayed.');
}
};
};
update.onclick = function() {
updateResult();
};
function updateResult() {
list.innerHTML = '';
var transaction = db.transaction(['rushAlbumList'], 'readwrite');
var objectStore = transaction.objectStore('rushAlbumList');
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
if(cursor.value.albumTitle === 'A farewell to kings') {
var updateData = cursor.value;
updateData.year = 2050;
var request = cursor.update(updateData);
request.onsuccess = function() {
console.log('A better album year?');
};
};
var listItem = document.createElement('li');
listItem.innerHTML = '<strong>' + cursor.value.albumTitle + '</strong>, ' + cursor.value.year;
list.appendChild(listItem);
cursor.continue();
} else {
console.log('Entries displayed.');
}
};
};
changeDirection.onclick = function() {
backwards();
}
function backwards() {
list.innerHTML = '';
var transaction = db.transaction(['rushAlbumList'], 'readonly');
var objectStore = transaction.objectStore('rushAlbumList');
objectStore.openCursor(null,'prev').onsuccess = function(event) {
var cursor = event.target.result;
if(cursor) {
var listItem = document.createElement('li');
listItem.innerHTML = '<strong>' + cursor.value.albumTitle + '</strong>, ' + cursor.value.year;
list.appendChild(listItem);
console.log(cursor.direction);
cursor.continue();
} else {
console.log('Entries displayed backwards.');
}
};
};
};
| {
"repo_name": "mdn/dom-examples",
"stars": "2648",
"repo_language": "JavaScript",
"file_name": "style.css",
"mime_type": "text/plain"
} |