返回

WebAPI 打开新世界的大门,Web 一统江湖指日可待

前端

原来我对许多 WebAPI 一无所知,当它们打开了我的新世界大门时,我意识到 Web 可以做到更多,并且早日一统江湖指日可待。虽然这些 API 目前有很多兼容性问题,但了解它们仍然很有必要。文章中的代码我已经都测试过了,希望你看完之后能够有所收获。你可能已经知道并使用了一些更流行的 WebAPI,但这些鲜为人知的 API 也同样值得关注。

  1. DataURL API:

DataURL API 允许你将数据编码为 URI 方案,然后在网页中使用它。这对于加载图像、视频和音频等资源非常有用,尤其是在你希望避免向服务器发出额外的请求时。

const dataURL = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

const image = new Image();
image.src = dataURL;

document.body.appendChild(image);
  1. FileReader API:

FileReader API 允许你读取文件内容,而无需将其加载到服务器。这对于处理本地文件非常有用,例如图像、视频和音频文件。

const file = document.querySelector('input[type=file]').files[0];

const reader = new FileReader();

reader.onload = function() {
  const text = reader.result;

  console.log(text);
};

reader.readAsText(file);
  1. SpeechSynthesis API:

SpeechSynthesis API 允许你使用浏览器将文本转换为语音。这对于创建可访问的网站非常有用,尤其是在你希望为视障用户提供替代访问方式时。

const text = 'Hello, world!';

const speech = new SpeechSynthesisUtterance(text);

speech.lang = 'en-US';

window.speechSynthesis.speak(speech);
  1. WebGL API:

WebGL API 允许你在浏览器中使用图形处理单元 (GPU) 来渲染 3D 图形。这对于创建交互式 3D 场景和游戏非常有用。

const canvas = document.querySelector('canvas');

const gl = canvas.getContext('webgl');

const vertexShaderSource = `
  attribute vec3 position;

  void main() {
    gl_Position = vec4(position, 1.0);
  }
`;

const fragmentShaderSource = `
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }
`;

const vertexShader = gl.createShader(gl.VERTEX_SHADER);
const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);

gl.shaderSource(vertexShader, vertexShaderSource);
gl.shaderSource(fragmentShader, fragmentShaderSource);

gl.compileShader(vertexShader);
gl.compileShader(fragmentShader);

const program = gl.createProgram();

gl.attachShader(program, vertexShader);
gl.attachShader(program, fragmentShader);

gl.linkProgram(program);

gl.useProgram(program);

const positionAttributeLocation = gl.getAttribLocation(program, 'position');

const positionBuffer = gl.createBuffer();

gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);

const positions = [
  -1.0, -1.0, 0.0,
  1.0, -1.0, 0.0,
  0.0, 1.0, 0.0
];

gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positions), gl.STATIC_DRAW);

gl.enableVertexAttribArray(positionAttributeLocation);

gl.vertexAttribPointer(positionAttributeLocation, 3, gl.FLOAT, false, 0, 0);

gl.drawArrays(gl.TRIANGLES, 0, 3);
  1. WebSockets API:

WebSockets API 允许你在浏览器和服务器之间建立双向通信通道。这对于创建实时应用程序非常有用,例如聊天和游戏。

const socket = new WebSocket('ws://localhost:8080');

socket.onopen = function() {
  console.log('WebSocket connection established');
};

socket.onmessage = function(event) {
  console.log('Message received: ', event.data);
};

socket.onclose = function() {
  console.log('WebSocket connection closed');
};

socket.send('Hello, world!');
  1. Push API:

Push API 允许你在浏览器中接收推送通知。这对于向用户发送有关更新、提醒和其他重要事件的通知非常有用。

const registration = await navigator.serviceWorker.register('service-worker.js');

registration.pushManager.subscribe({
  userVisibleOnly: true
}).then(function(subscription) {
  console.log('Push subscription successful');
}).catch(function(err) {
  console.log('Push subscription failed: ', err);
});
  1. Service Workers API:

Service Workers API 允许你在浏览器中运行脚本,即使浏览器窗口关闭或用户离线时也是如此。这对于创建离线应用程序非常有用,例如游戏和电子邮件客户端。

self.addEventListener('install', function(event) {
  event.waitUntil(
    caches.open('my-cache').then(function(cache) {
      return cache.addAll([
        '/',
        '/index.html',
        '/app.js',
        '/style.css'
      ]);
    })
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(function(response) {
      return response || fetch(event.request);
    })
  );
});
  1. IndexedDB API:

IndexedDB API 允许你在浏览器中存储大量数据,即使浏览器窗口关闭或用户离线时也是如此。这对于创建离线应用程序非常有用,例如游戏和电子邮件客户端。

const request = indexedDB.open('my-database', 1);

request.onsuccess = function(event) {
  const db = event.target.result;

  const transaction = db.transaction('my-object-store', 'readwrite');

  const objectStore = transaction.objectStore('my-object-store');

  const data = {
    name: 'John Doe',
    age: 30
  };

  objectStore.add(data);

  transaction.oncomplete = function() {
    console.log('Data successfully added to IndexedDB');
  };
};
  1. Media Capture API:

Media Capture API 允许你在浏览器中捕获音视频数据。这对于创建照片、视频和音频录制应用程序非常有用。

const video = document.querySelector('video');

const mediaConstraints = {
  video: true,
  audio: true
};

navigator.mediaDevices.getUserMedia(mediaConstraints).then(function(stream) {
  video.srcObject = stream;
}).catch(function(err) {
  console.log('Error capturing media: ', err);
});
  1. WebVR API:

WebVR API 允许你在浏览器中创建和体验虚拟现实 (VR) 场景。这对于创建 VR 游戏和应用程序非常有用。

const scene = new THREE.Scene();

const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });

const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

camera.position.z = 5;

function animate() {
  requestAnimationFrame(animate);

  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  renderer.render(scene, camera);
}