From 6add031cba56bb6d2b8fc9a7c2deb53e9961d3aa Mon Sep 17 00:00:00 2001 From: "Queen Vinyl Da.i'gyu-Kazotetsu" Date: Fri, 28 Jul 2023 02:49:24 -0700 Subject: [PATCH] zh-cn: Format /web/api using Prettier (part 1) --- files/zh-cn/web/api/abortcontroller/index.md | 14 +- .../web/api/abortcontroller/signal/index.md | 14 +- .../web/api/abortsignal/abort_event/index.md | 10 +- .../web/api/abortsignal/abort_static/index.md | 4 +- .../web/api/abortsignal/aborted/index.md | 4 +- files/zh-cn/web/api/abortsignal/index.md | 46 +- .../zh-cn/web/api/abortsignal/reason/index.md | 4 +- .../api/abortsignal/throwifaborted/index.md | 10 +- .../api/abortsignal/timeout_static/index.md | 6 +- files/zh-cn/web/api/accelerometer/index.md | 4 +- .../getfloatfrequencydata/index.md | 119 ++--- files/zh-cn/web/api/analysernode/index.md | 14 +- files/zh-cn/web/api/animation/effect/index.md | 2 +- files/zh-cn/web/api/animation/finish/index.md | 8 +- .../zh-cn/web/api/animation/finished/index.md | 16 +- files/zh-cn/web/api/animation/play/index.md | 25 +- .../web/api/animation/playstate/index.md | 26 +- files/zh-cn/web/api/atob/index.md | 2 +- files/zh-cn/web/api/attr/localname/index.md | 2 +- .../zh-cn/web/api/attr/namespaceuri/index.md | 7 +- .../api/audiobuffer/copyfromchannel/index.md | 4 +- .../web/api/audiobuffer/duration/index.md | 4 +- .../api/audiobuffer/getchanneldata/index.md | 24 +- files/zh-cn/web/api/audiobuffer/index.md | 11 +- .../zh-cn/web/api/audiobuffer/length/index.md | 4 +- .../api/audiobuffer/numberofchannels/index.md | 4 +- .../web/api/audiobuffer/samplerate/index.md | 4 +- .../web/api/audiobuffersourcenode/index.md | 24 +- .../api/audiobuffersourcenode/start/index.md | 2 +- .../web/api/audiocontext/baselatency/index.md | 6 +- .../zh-cn/web/api/audiocontext/close/index.md | 12 +- .../createmediaelementsource/index.md | 18 +- .../createmediastreamdestination/index.md | 68 +-- .../createmediastreamsource/index.md | 77 +-- .../web/api/audiocontext/resume/index.md | 16 +- .../web/api/audiocontext/suspend/index.md | 16 +- .../web/api/audiodestinationnode/index.md | 2 +- files/zh-cn/web/api/audionode/index.md | 10 +- .../web/api/audioparamdescriptor/index.md | 20 +- files/zh-cn/web/api/audiotrack/index.md | 6 +- files/zh-cn/web/api/audioworkletnode/index.md | 25 +- .../web/api/audioworkletprocessor/index.md | 29 +- .../clientdatajson/index.md | 6 +- .../web/api/authenticatorresponse/index.md | 16 +- .../web/api/background_tasks_api/index.md | 110 ++-- .../baseaudiocontext/createbuffer/index.md | 30 +- .../createbuffersource/index.md | 24 +- .../createchannelmerger/index.md | 46 +- .../createchannelsplitter/index.md | 46 +- .../createoscillator/index.md | 2 +- .../createperiodicwave/index.md | 2 +- .../createscriptprocessor/index.md | 49 +- .../baseaudiocontext/decodeaudiodata/index.md | 44 +- .../web/api/baseaudiocontext/state/index.md | 4 +- .../statechange_event/index.md | 4 +- .../web/api/batterymanager/charging/index.md | 7 +- .../zh-cn/web/api/beforeunloadevent/index.md | 12 +- files/zh-cn/web/api/blob/blob/index.md | 2 +- files/zh-cn/web/api/blob/index.md | 34 +- files/zh-cn/web/api/blob/size/index.md | 10 +- files/zh-cn/web/api/blob/type/index.md | 6 +- .../web/api/broadcast_channel_api/index.md | 10 +- .../broadcastchannel/index.md | 2 +- .../web/api/broadcastchannel/close/index.md | 2 +- .../broadcastchannel/message_event/index.md | 79 +-- .../messageerror_event/index.md | 10 +- .../web/api/broadcastchannel/name/index.md | 2 +- files/zh-cn/web/api/btoa/index.md | 16 +- .../bytelengthqueuingstrategy/index.md | 25 +- .../highwatermark/index.md | 2 +- .../api/bytelengthqueuingstrategy/index.md | 23 +- .../bytelengthqueuingstrategy/size/index.md | 23 +- files/zh-cn/web/api/cache/add/index.md | 14 +- files/zh-cn/web/api/cache/addall/index.md | 26 +- files/zh-cn/web/api/cache/delete/index.md | 6 +- files/zh-cn/web/api/cache/index.md | 51 +- files/zh-cn/web/api/cache/keys/index.md | 10 +- files/zh-cn/web/api/cache/match/index.md | 20 +- files/zh-cn/web/api/cache/matchall/index.md | 10 +- files/zh-cn/web/api/cache/put/index.md | 30 +- files/zh-cn/web/api/caches/index.md | 26 +- .../web/api/cachestorage/delete/index.md | 20 +- files/zh-cn/web/api/cachestorage/has/index.md | 25 +- files/zh-cn/web/api/cachestorage/index.md | 54 +- .../zh-cn/web/api/cachestorage/match/index.md | 24 +- .../zh-cn/web/api/cachestorage/open/index.md | 24 +- files/zh-cn/web/api/canvas_api/index.md | 6 +- .../manipulating_video_using_canvas/index.md | 44 +- .../tutorial/advanced_animations/index.md | 54 +- .../applying_styles_and_colors/index.md | 268 +++++----- .../tutorial/basic_animations/index.md | 475 ++++++++--------- .../canvas_api/tutorial/basic_usage/index.md | 60 +-- .../tutorial/compositing/example/index.md | 478 ++++++++++-------- .../canvas_api/tutorial/compositing/index.md | 45 +- .../tutorial/drawing_shapes/index.md | 156 +++--- .../canvas_api/tutorial/drawing_text/index.md | 15 +- .../tutorial/optimizing_canvas/index.md | 24 +- .../pixel_manipulation_with_canvas/index.md | 236 +++++---- .../tutorial/transformations/index.md | 44 +- .../canvas_api/tutorial/using_images/index.md | 155 +++--- 100 files changed, 1979 insertions(+), 1792 deletions(-) diff --git a/files/zh-cn/web/api/abortcontroller/index.md b/files/zh-cn/web/api/abortcontroller/index.md index 70e2091a7c3c96..be2b7122b5dd6e 100644 --- a/files/zh-cn/web/api/abortcontroller/index.md +++ b/files/zh-cn/web/api/abortcontroller/index.md @@ -36,17 +36,17 @@ slug: Web/API/AbortController ```js let controller; -const url = 'video.mp4'; +const url = "video.mp4"; -const downloadBtn = document.querySelector('.download'); -const abortBtn = document.querySelector('.abort'); +const downloadBtn = document.querySelector(".download"); +const abortBtn = document.querySelector(".abort"); -downloadBtn.addEventListener('click', fetchVideo); +downloadBtn.addEventListener("click", fetchVideo); -abortBtn.addEventListener('click', () => { +abortBtn.addEventListener("click", () => { if (controller) { controller.abort(); - console.log('中止下载'); + console.log("中止下载"); } }); @@ -55,7 +55,7 @@ function fetchVideo() { const signal = controller.signal; fetch(url, { signal }) .then((response) => { - console.log('下载完成', response); + console.log("下载完成", response); }) .catch((err) => { console.error(`下载错误:${err.message}`); diff --git a/files/zh-cn/web/api/abortcontroller/signal/index.md b/files/zh-cn/web/api/abortcontroller/signal/index.md index f36f31b90b1986..f9469003602e6f 100644 --- a/files/zh-cn/web/api/abortcontroller/signal/index.md +++ b/files/zh-cn/web/api/abortcontroller/signal/index.md @@ -23,21 +23,21 @@ slug: Web/API/AbortController/signal const controller = new AbortController(); const signal = controller.signal; -const url = 'video.mp4'; -const downloadBtn = document.querySelector('.download'); -const abortBtn = document.querySelector('.abort'); +const url = "video.mp4"; +const downloadBtn = document.querySelector(".download"); +const abortBtn = document.querySelector(".abort"); -downloadBtn.addEventListener('click', fetchVideo); +downloadBtn.addEventListener("click", fetchVideo); -abortBtn.addEventListener('click', () => { +abortBtn.addEventListener("click", () => { controller.abort(); - console.log('Download aborted'); + console.log("Download aborted"); }); function fetchVideo() { fetch(url, { signal }) .then((response) => { - console.log('Download complete', response); + console.log("Download complete", response); }) .catch((err) => { console.error(`Download error: ${err.message}`); diff --git a/files/zh-cn/web/api/abortsignal/abort_event/index.md b/files/zh-cn/web/api/abortsignal/abort_event/index.md index 4d0b440cbcbe6d..c17b329fde3f14 100644 --- a/files/zh-cn/web/api/abortsignal/abort_event/index.md +++ b/files/zh-cn/web/api/abortsignal/abort_event/index.md @@ -12,8 +12,8 @@ slug: Web/API/AbortSignal/abort_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 等方法中使用事件名称,或者设置一个事件处理器属性。 ```js -addEventListener('abort', (event) => { }) -onabort = (event) => { } +addEventListener("abort", (event) => {}); +onabort = (event) => {}; ``` ## 事件类型 @@ -30,8 +30,8 @@ onabort = (event) => { } const controller = new AbortController(); const signal = controller.signal; -signal.addEventListener('abort', () => { - console.log('Request aborted'); +signal.addEventListener("abort", () => { + console.log("Request aborted"); }); ``` @@ -41,7 +41,7 @@ signal.addEventListener('abort', () => { const controller = new AbortController(); const signal = controller.signal; signal.onabort = () => { - console.log('Request aborted'); + console.log("Request aborted"); }; ``` diff --git a/files/zh-cn/web/api/abortsignal/abort_static/index.md b/files/zh-cn/web/api/abortsignal/abort_static/index.md index d78eadfaf1c5fc..ff102016ad0f82 100644 --- a/files/zh-cn/web/api/abortsignal/abort_static/index.md +++ b/files/zh-cn/web/api/abortsignal/abort_static/index.md @@ -23,8 +23,8 @@ return controller.signal; ## 语法 ```js -abort() -abort(reason) +abort(); +abort(reason); ``` ### 参数 diff --git a/files/zh-cn/web/api/abortsignal/aborted/index.md b/files/zh-cn/web/api/abortsignal/aborted/index.md index 16a6dc6ab26cc6..82bf633b1fd7fe 100644 --- a/files/zh-cn/web/api/abortsignal/aborted/index.md +++ b/files/zh-cn/web/api/abortsignal/aborted/index.md @@ -22,9 +22,9 @@ const signal = controller.signal; // … if (signal.aborted) { - console.log('Request has been aborted'); + console.log("Request has been aborted"); } else { - console.log('Request not aborted'); + console.log("Request not aborted"); } ``` diff --git a/files/zh-cn/web/api/abortsignal/index.md b/files/zh-cn/web/api/abortsignal/index.md index 65ef104ace0709..9574314214fa6b 100644 --- a/files/zh-cn/web/api/abortsignal/index.md +++ b/files/zh-cn/web/api/abortsignal/index.md @@ -51,21 +51,21 @@ _**`AbortSignal`** 接口继续它父接口 {{domxref("EventTarget")}} 的方法 const controller = new AbortController(); const signal = controller.signal; -const url = 'video.mp4'; -const downloadBtn = document.querySelector('.download'); -const abortBtn = document.querySelector('.abort'); +const url = "video.mp4"; +const downloadBtn = document.querySelector(".download"); +const abortBtn = document.querySelector(".abort"); -downloadBtn.addEventListener('click', fetchVideo); +downloadBtn.addEventListener("click", fetchVideo); -abortBtn.addEventListener('click', () => { +abortBtn.addEventListener("click", () => { controller.abort(); - console.log('Download aborted'); + console.log("Download aborted"); }); function fetchVideo() { fetch(url, { signal }) .then((response) => { - console.log('Download complete', response); + console.log("Download complete", response); }) .catch((err) => { console.error(`Download error: ${err.message}`); @@ -84,7 +84,7 @@ function fetchVideo() { 以下代码片段展示了如何成功地下载一个文件或者在五秒钟后处理一个超时的错误。注意,当出现超时时,`fetch()` promise 会以“`TimeoutError`”`DOMException` 拒绝。这允许代码区分超时(可能需要通知用户)和用户中止。 ```js -const url = 'video.mp4'; +const url = "video.mp4"; try { const res = await fetch(url, { signal: AbortSignal.timeout(5000) }); @@ -94,7 +94,9 @@ try { if (err.name === "TimeoutError") { console.error("Timeout: It took more than 5 seconds to get the result!"); } else if (err.name === "AbortError") { - console.error("Fetch aborted by user action (browser stop button, closing tab, etc."); + console.error( + "Fetch aborted by user action (browser stop button, closing tab, etc.", + ); } else if (err.name === "TypeError") { console.error("AbortSignal.timeout() method is not supported"); } else { @@ -112,20 +114,18 @@ try { ```js try { - const controller = new AbortController() - const timeoutId = setTimeout(() => controller.abort(), 5000) - const res = await fetch(url, { signal: controller.signal }) - const body = await res.json() -} -catch (e) { - if (e.name === "AbortError") { - // Notify the user of abort. - // Note this will never be a timeout error! - } else { - // A network error, or some other problem. - console.log(`Type: ${e.name}, Message: ${e.message}`) - } - + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), 5000); + const res = await fetch(url, { signal: controller.signal }); + const body = await res.json(); +} catch (e) { + if (e.name === "AbortError") { + // Notify the user of abort. + // Note this will never be a timeout error! + } else { + // A network error, or some other problem. + console.log(`Type: ${e.name}, Message: ${e.message}`); + } } finally { clearTimeout(timeoutId); } diff --git a/files/zh-cn/web/api/abortsignal/reason/index.md b/files/zh-cn/web/api/abortsignal/reason/index.md index eb50bb517537d2..bc83e049021c62 100644 --- a/files/zh-cn/web/api/abortsignal/reason/index.md +++ b/files/zh-cn/web/api/abortsignal/reason/index.md @@ -27,10 +27,10 @@ if (signal.aborted) { if (signal.reason) { console.log(`Request aborted with reason: ${signal.reason}`); } else { - console.log('Request aborted but no reason was given.'); + console.log("Request aborted but no reason was given."); } } else { - console.log('Request not aborted'); + console.log("Request not aborted"); } ``` diff --git a/files/zh-cn/web/api/abortsignal/throwifaborted/index.md b/files/zh-cn/web/api/abortsignal/throwifaborted/index.md index ceeb439d269207..66fed605c51653 100644 --- a/files/zh-cn/web/api/abortsignal/throwifaborted/index.md +++ b/files/zh-cn/web/api/abortsignal/throwifaborted/index.md @@ -14,7 +14,7 @@ slug: Web/API/AbortSignal/throwIfAborted ## 语法 ```js -throwIfAborted() +throwIfAborted(); ``` ### 参数 @@ -57,7 +57,7 @@ async function waitForCondition(func, targetValue, { signal } = {}) { 一个基于 {{jsxref("Promise")}} 的 API 应该通过使用 `AbortSignal` abort {{domxref("AbortSignal.reason", "reason")}} 拒绝任何未敲定的 promise 来响应中止信号。例如,考虑以下 `myCoolPromiseAPI`,它接收一个信号并且返回一个 promise。如果 signal 已经中止或者检测到中止事件,则 promise 将被立刻拒绝。否则它将正常返回并且兑现。 ```js -function myCoolPromiseAPI(/* … ,*/ {signal}) { +function myCoolPromiseAPI(/* … ,*/ { signal }) { return new Promise((resolve, reject) => { // If the signal is already aborted, immediately throw in order to reject the promise. if (signal.aborted) { @@ -68,7 +68,7 @@ function myCoolPromiseAPI(/* … ,*/ {signal}) { // Call resolve(result) when done. // Watch for 'abort' signals - signal.addEventListener('abort', () => { + signal.addEventListener("abort", () => { // Stop the main operation // Reject the promise wth the abort reason. reject(signal.reason); @@ -86,9 +86,9 @@ const signal = controller.signal; startSpinner(); myCoolPromiseAPI({ /* … ,*/ signal }) - .then((result) => { }) + .then((result) => {}) .catch((err) => { - if (err.name === 'AbortError') return; + if (err.name === "AbortError") return; showUserErrorMessage(); }) .then(() => stopSpinner()); diff --git a/files/zh-cn/web/api/abortsignal/timeout_static/index.md b/files/zh-cn/web/api/abortsignal/timeout_static/index.md index 10bab3dcfeff4d..537c635c6a9eea 100644 --- a/files/zh-cn/web/api/abortsignal/timeout_static/index.md +++ b/files/zh-cn/web/api/abortsignal/timeout_static/index.md @@ -17,7 +17,7 @@ original_slug: Web/API/AbortSignal/timeout ## 语法 ```js -timeout(time) +timeout(time); ``` ### 参数 @@ -46,7 +46,9 @@ try { if (err.name === "TimeoutError") { console.error("Timeout: It took more than 5 seconds to get the result!"); } else if (err.name === "AbortError") { - console.error("Fetch aborted by user action (browser stop button, closing tab, etc."); + console.error( + "Fetch aborted by user action (browser stop button, closing tab, etc.", + ); } else if (err.name === "TypeError") { console.error("AbortSignal.timeout() method is not supported"); } else { diff --git a/files/zh-cn/web/api/accelerometer/index.md b/files/zh-cn/web/api/accelerometer/index.md index db9bfed9099d02..219b5a035726b0 100644 --- a/files/zh-cn/web/api/accelerometer/index.md +++ b/files/zh-cn/web/api/accelerometer/index.md @@ -30,9 +30,9 @@ If a feature policy blocks the use of a feature, it is because your code is inco Acceleration is typically read in the {{domxref('Sensor.onreading')}} event callback. In the example below this occurs sixty times a second. ```js -let accelerometer = new Accelerometer({frequency: 60}); +let accelerometer = new Accelerometer({ frequency: 60 }); -accelerometer.addEventListener('reading', e => { +accelerometer.addEventListener("reading", (e) => { console.log("Acceleration along the X-axis " + accelerometer.x); console.log("Acceleration along the Y-axis " + accelerometer.y); console.log("Acceleration along the Z-axis " + accelerometer.z); diff --git a/files/zh-cn/web/api/analysernode/getfloatfrequencydata/index.md b/files/zh-cn/web/api/analysernode/getfloatfrequencydata/index.md index e3c55e17336d66..6df58a4e362364 100644 --- a/files/zh-cn/web/api/analysernode/getfloatfrequencydata/index.md +++ b/files/zh-cn/web/api/analysernode/getfloatfrequencydata/index.md @@ -47,63 +47,68 @@ analyser.getFloatFrequencyData(myDataArray); ```html - + ``` diff --git a/files/zh-cn/web/api/analysernode/index.md b/files/zh-cn/web/api/analysernode/index.md index 3ccc7db4755d5f..bfafcf4807e2b2 100644 --- a/files/zh-cn/web/api/analysernode/index.md +++ b/files/zh-cn/web/api/analysernode/index.md @@ -88,7 +88,7 @@ _继承方法自_ _{{domxref("AudioNode")}}_. 更多的例子/信息,查看 [Voice-change-O-matic](https://mdn.github.io/voice-change-o-matic/) 演示 (相关代码在 [app.js 的 128 行\~205 行](https://github.com/mdn/voice-change-o-matic/blob/gh-pages/scripts/app.js#L128-L205)). ```js -var audioCtx = new(window.AudioContext || window.webkitAudioContext)(); +var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var analyser = audioCtx.createAnalyser(); // ... @@ -105,26 +105,24 @@ var canvasCtx = canvas.getContext("2d"); // 绘制一个当前音频源的示波器 function draw() { - drawVisual = requestAnimationFrame(draw); analyser.getByteTimeDomainData(dataArray); - canvasCtx.fillStyle = 'rgb(200, 200, 200)'; + canvasCtx.fillStyle = "rgb(200, 200, 200)"; canvasCtx.fillRect(0, 0, canvas.width, canvas.height); canvasCtx.lineWidth = 2; - canvasCtx.strokeStyle = 'rgb(0, 0, 0)'; + canvasCtx.strokeStyle = "rgb(0, 0, 0)"; canvasCtx.beginPath(); - var sliceWidth = canvas.width * 1.0 / bufferLength; + var sliceWidth = (canvas.width * 1.0) / bufferLength; var x = 0; for (var i = 0; i < bufferLength; i++) { - var v = dataArray[i] / 128.0; - var y = v * canvas.height / 2; + var y = (v * canvas.height) / 2; if (i === 0) { canvasCtx.moveTo(x, y); @@ -137,7 +135,7 @@ function draw() { canvasCtx.lineTo(canvas.width, canvas.height / 2); canvasCtx.stroke(); -}; +} draw(); ``` diff --git a/files/zh-cn/web/api/animation/effect/index.md b/files/zh-cn/web/api/animation/effect/index.md index b0c93fc7c720f3..9a6e6839e63811 100644 --- a/files/zh-cn/web/api/animation/effect/index.md +++ b/files/zh-cn/web/api/animation/effect/index.md @@ -14,7 +14,7 @@ Animation.effect 属性可以获取或设置动画的目标效果。目标效果 var effect = animation.effect; // Set an Animation's target effect -animation.effect = new KeyframeEffect({ opacity: [ 1, 0 ] }, 300); +animation.effect = new KeyframeEffect({ opacity: [1, 0] }, 300); ``` ### 值 diff --git a/files/zh-cn/web/api/animation/finish/index.md b/files/zh-cn/web/api/animation/finish/index.md index 8b516959f1e3ad..3ef9ec876e9889 100644 --- a/files/zh-cn/web/api/animation/finish/index.md +++ b/files/zh-cn/web/api/animation/finish/index.md @@ -45,11 +45,9 @@ interfaceElement.addEventListener("mousedown", function() { The following example finishes all the animations on a single element, regardless of their direction of playback. ```js -elem.getAnimations().forEach( - function(animation){ - return animation.finish(); - } -); +elem.getAnimations().forEach(function (animation) { + return animation.finish(); +}); ``` ## 规范 diff --git a/files/zh-cn/web/api/animation/finished/index.md b/files/zh-cn/web/api/animation/finished/index.md index 0068d0554d2c4f..e14509881e8190 100644 --- a/files/zh-cn/web/api/animation/finished/index.md +++ b/files/zh-cn/web/api/animation/finished/index.md @@ -25,16 +25,12 @@ var animationsPromise = animation.finished; ```js Promise.all( - elem.getAnimations().map( - function(animation) { - return animation.finished - } - ) -).then( - function() { - return elem.remove(); - } -); + elem.getAnimations().map(function (animation) { + return animation.finished; + }), +).then(function () { + return elem.remove(); +}); ``` ## 规范 diff --git a/files/zh-cn/web/api/animation/play/index.md b/files/zh-cn/web/api/animation/play/index.md index 7ee8d8a28b6d00..3fcacfd4030c2c 100644 --- a/files/zh-cn/web/api/animation/play/index.md +++ b/files/zh-cn/web/api/animation/play/index.md @@ -27,29 +27,28 @@ animation.play(); ```js // 蛋糕拥有其自己的动画: -var nommingCake = document.getElementById('eat-me_sprite').animate( -[ - { transform: 'translateY(0)' }, - { transform: 'translateY(-80%)' } -], { - fill: 'forwards', - easing: 'steps(4, end)', - duration: aliceChange.effect.timing.duration / 2 -}); +var nommingCake = document + .getElementById("eat-me_sprite") + .animate( + [{ transform: "translateY(0)" }, { transform: "translateY(-80%)" }], + { + fill: "forwards", + easing: "steps(4, end)", + duration: aliceChange.effect.timing.duration / 2, + }, + ); // 暂停蛋糕的动画,以避免动画立即播放。 nommingCake.pause(); // 该函数会在用户点击时触发 -var growAlice = function() { - +var growAlice = function () { // Play Alice's animation. aliceChange.play(); // Play the cake's animation. nommingCake.play(); - -} +}; // 当用户持续按下或点击时,调用 growAlice 函数使得所有的动画播放。 cake.addEventListener("mousedown", growAlice, false); diff --git a/files/zh-cn/web/api/animation/playstate/index.md b/files/zh-cn/web/api/animation/playstate/index.md index 180e0a75f94ad2..c0f8b17cf11ce7 100644 --- a/files/zh-cn/web/api/animation/playstate/index.md +++ b/files/zh-cn/web/api/animation/playstate/index.md @@ -37,29 +37,25 @@ Animation.playState = newState; ```js // 创建泪珠动画 -tears.forEach(function(el) { - el.animate( - tearsFalling, - { - delay: getRandomMsRange(-1000, 1000), // 获取每一滴随机泪珠 - duration: getRandomMsRange(2000, 6000), // 获取每一滴随机泪珠 - iterations: Infinity, - easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)" - }); - el.playState = 'paused'; +tears.forEach(function (el) { + el.animate(tearsFalling, { + delay: getRandomMsRange(-1000, 1000), // 获取每一滴随机泪珠 + duration: getRandomMsRange(2000, 6000), // 获取每一滴随机泪珠 + iterations: Infinity, + easing: "cubic-bezier(0.6, 0.04, 0.98, 0.335)", + }); + el.playState = "paused"; }); - // 结尾需要现出时播放眼泪降落动画 -tears.forEach(function(el) { - el.playState = 'playing'; +tears.forEach(function (el) { + el.playState = "playing"; }); - // 暂停并重置正在哭泣时的泪滴动画 -tears.forEach(function(el) { +tears.forEach(function (el) { el.playState = "paused"; el.currentTime = 0; }); diff --git a/files/zh-cn/web/api/atob/index.md b/files/zh-cn/web/api/atob/index.md index e695e8eae709cf..fb8a0e47eb9c7c 100644 --- a/files/zh-cn/web/api/atob/index.md +++ b/files/zh-cn/web/api/atob/index.md @@ -23,7 +23,7 @@ var decodedData = scope.atob(encodedData); ```js let encodedData = window.btoa("Hello, world"); // 编码 -let decodedData = window.atob(encodedData); // 解码 +let decodedData = window.atob(encodedData); // 解码 ``` ## 规范 diff --git a/files/zh-cn/web/api/attr/localname/index.md b/files/zh-cn/web/api/attr/localname/index.md index 71311a7d0aaf55..cd119133c4baec 100644 --- a/files/zh-cn/web/api/attr/localname/index.md +++ b/files/zh-cn/web/api/attr/localname/index.md @@ -33,7 +33,7 @@ name = attribute.localName ```js const element = document.querySelector("#example"); -element.addEventListener("click", function() { +element.addEventListener("click", function () { const attribute = element.attributes[0]; alert(attribute.localName); }); diff --git a/files/zh-cn/web/api/attr/namespaceuri/index.md b/files/zh-cn/web/api/attr/namespaceuri/index.md index 3d829d482ab70a..6fe957f40caac0 100644 --- a/files/zh-cn/web/api/attr/namespaceuri/index.md +++ b/files/zh-cn/web/api/attr/namespaceuri/index.md @@ -20,8 +20,11 @@ namespace = attribute.namespaceURI 在这个片段中,正在检查一个属性的 {{domxref("localName")}} 和 `namespaceURI`。如果 `namespaceURI` 返回 XUL 命名空间,并且 localName 返回 "browser",则该节点被理解为 XUL ``。 ```js -if (attribute.localName == "value" && - attribute.namespaceURI == "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul") { +if ( + attribute.localName == "value" && + attribute.namespaceURI == + "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" +) { // this is a XUL value } ``` diff --git a/files/zh-cn/web/api/audiobuffer/copyfromchannel/index.md b/files/zh-cn/web/api/audiobuffer/copyfromchannel/index.md index d74cdd41253152..86e6355f5750c6 100644 --- a/files/zh-cn/web/api/audiobuffer/copyfromchannel/index.md +++ b/files/zh-cn/web/api/audiobuffer/copyfromchannel/index.md @@ -26,8 +26,8 @@ myArrayBuffer.copyFromChannel(destination,channelNumber,startInChannel); ```js var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); -var anotherArray = new Float32Array; -myArrayBuffer.copyFromChannel(anotherArray,1,0); +var anotherArray = new Float32Array(); +myArrayBuffer.copyFromChannel(anotherArray, 1, 0); ``` ## 规范 diff --git a/files/zh-cn/web/api/audiobuffer/duration/index.md b/files/zh-cn/web/api/audiobuffer/duration/index.md index 52600e93c4c30e..0f786cff4e2b1e 100644 --- a/files/zh-cn/web/api/audiobuffer/duration/index.md +++ b/files/zh-cn/web/api/audiobuffer/duration/index.md @@ -29,7 +29,7 @@ var channels = 2; var frameCount = audioCtx.sampleRate * 2.0; var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); -button.onclick = function() { +button.onclick = function () { // Fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { @@ -43,7 +43,7 @@ button.onclick = function() { } console.log(myArrayBuffer.duration); -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/audiobuffer/getchanneldata/index.md b/files/zh-cn/web/api/audiobuffer/getchanneldata/index.md index 210488649213d2..0fee98d67b0aaf 100644 --- a/files/zh-cn/web/api/audiobuffer/getchanneldata/index.md +++ b/files/zh-cn/web/api/audiobuffer/getchanneldata/index.md @@ -29,9 +29,9 @@ var nowBuffering = myArrayBuffer.getChannelData(channel); ```js var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); -var button = document.querySelector('button'); -var pre = document.querySelector('pre'); -var myScript = document.querySelector('script'); +var button = document.querySelector("button"); +var pre = document.querySelector("pre"); +var myScript = document.querySelector("script"); pre.innerHTML = myScript.innerHTML; @@ -43,17 +43,17 @@ var frameCount = audioCtx.sampleRate * 2.0; var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); -button.onclick = function() { +button.onclick = function () { // Fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { - // This gives us the actual ArrayBuffer that contains the data - var nowBuffering = myArrayBuffer.getChannelData(channel); - for (var i = 0; i < frameCount; i++) { - // Math.random() is in [0; 1.0] - // audio needs to be in [-1.0; 1.0] - nowBuffering[i] = Math.random() * 2 - 1; - } + // This gives us the actual ArrayBuffer that contains the data + var nowBuffering = myArrayBuffer.getChannelData(channel); + for (var i = 0; i < frameCount; i++) { + // Math.random() is in [0; 1.0] + // audio needs to be in [-1.0; 1.0] + nowBuffering[i] = Math.random() * 2 - 1; + } } // Get an AudioBufferSourceNode. @@ -66,7 +66,7 @@ button.onclick = function() { source.connect(audioCtx.destination); // start the source playing source.start(); -} +}; ``` ## Specification diff --git a/files/zh-cn/web/api/audiobuffer/index.md b/files/zh-cn/web/api/audiobuffer/index.md index f42931031d5195..8e4740c643b9f0 100644 --- a/files/zh-cn/web/api/audiobuffer/index.md +++ b/files/zh-cn/web/api/audiobuffer/index.md @@ -40,9 +40,13 @@ var channels = 2; // Create an empty two second stereo buffer at the // sample rate of the AudioContext var frameCount = audioCtx.sampleRate * 2.0; -var myArrayBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate); +var myArrayBuffer = audioCtx.createBuffer( + channels, + frameCount, + audioCtx.sampleRate, +); -button.onclick = function() { +button.onclick = function () { // Fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { @@ -68,8 +72,7 @@ button.onclick = function() { // start the source playing source.start(); - -} +}; ``` ## 规格参数 diff --git a/files/zh-cn/web/api/audiobuffer/length/index.md b/files/zh-cn/web/api/audiobuffer/length/index.md index 2a0a3e87030825..5ac816c531332c 100644 --- a/files/zh-cn/web/api/audiobuffer/length/index.md +++ b/files/zh-cn/web/api/audiobuffer/length/index.md @@ -31,7 +31,7 @@ var channels = 2; var frameCount = audioCtx.sampleRate * 2.0; var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); -button.onclick = function() { +button.onclick = function () { // Fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { @@ -45,7 +45,7 @@ button.onclick = function() { } console.log(myArrayBuffer.length); -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/audiobuffer/numberofchannels/index.md b/files/zh-cn/web/api/audiobuffer/numberofchannels/index.md index 36c61d4284931f..59f6df1a7da403 100644 --- a/files/zh-cn/web/api/audiobuffer/numberofchannels/index.md +++ b/files/zh-cn/web/api/audiobuffer/numberofchannels/index.md @@ -29,7 +29,7 @@ var channels = 2; var frameCount = audioCtx.sampleRate * 2.0; var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); -button.onclick = function() { +button.onclick = function () { // Fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { @@ -43,7 +43,7 @@ button.onclick = function() { } console.log(myArrayBuffer.numberOfChannels); -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/audiobuffer/samplerate/index.md b/files/zh-cn/web/api/audiobuffer/samplerate/index.md index 4447d0888f65f5..1d41c04653e141 100644 --- a/files/zh-cn/web/api/audiobuffer/samplerate/index.md +++ b/files/zh-cn/web/api/audiobuffer/samplerate/index.md @@ -29,7 +29,7 @@ var channels = 2; var frameCount = audioCtx.sampleRate * 2.0; var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); -button.onclick = function() { +button.onclick = function () { // Fill the buffer with white noise; // just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { @@ -43,7 +43,7 @@ button.onclick = function() { } console.log(myArrayBuffer.sampleRate); -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/audiobuffersourcenode/index.md b/files/zh-cn/web/api/audiobuffersourcenode/index.md index 3ef135d00c4d17..ce91f61034533c 100644 --- a/files/zh-cn/web/api/audiobuffersourcenode/index.md +++ b/files/zh-cn/web/api/audiobuffersourcenode/index.md @@ -73,9 +73,9 @@ _从父级的 {{domxref("AudioNode")}} 继承方法。_ ```js var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); -var button = document.querySelector('button'); -var pre = document.querySelector('pre'); -var myScript = document.querySelector('script'); +var button = document.querySelector("button"); +var pre = document.querySelector("pre"); +var myScript = document.querySelector("script"); pre.innerHTML = myScript.innerHTML; @@ -87,17 +87,17 @@ var frameCount = audioCtx.sampleRate * 2.0; var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate); -button.onclick = function() { +button.onclick = function () { // Fill the buffer with white noise; //just random values between -1.0 and 1.0 for (var channel = 0; channel < channels; channel++) { - // This gives us the actual ArrayBuffer that contains the data - var nowBuffering = myArrayBuffer.getChannelData(channel); - for (var i = 0; i < frameCount; i++) { - // Math.random() is in [0; 1.0] - // audio needs to be in [-1.0; 1.0] - nowBuffering[i] = Math.random() * 2 - 1; - } + // This gives us the actual ArrayBuffer that contains the data + var nowBuffering = myArrayBuffer.getChannelData(channel); + for (var i = 0; i < frameCount; i++) { + // Math.random() is in [0; 1.0] + // audio needs to be in [-1.0; 1.0] + nowBuffering[i] = Math.random() * 2 - 1; + } } // Get an AudioBufferSourceNode. @@ -110,7 +110,7 @@ button.onclick = function() { source.connect(audioCtx.destination); // start the source playing source.start(); -} +}; ``` > **备注:** 音频数据解码的例子请查看 {{domxref("AudioContext.decodeAudioData")}} 页面。 diff --git a/files/zh-cn/web/api/audiobuffersourcenode/start/index.md b/files/zh-cn/web/api/audiobuffersourcenode/start/index.md index f914b93e3e0273..77b81dcb43ed6d 100644 --- a/files/zh-cn/web/api/audiobuffersourcenode/start/index.md +++ b/files/zh-cn/web/api/audiobuffersourcenode/start/index.md @@ -44,7 +44,7 @@ source.start(); The following more complex example will, 1 second from now, start playing 10 seconds worth of sound starting 3 seconds into the audio buffer. ```js -source.start(audioCtx.currentTime + 1,3,10); +source.start(audioCtx.currentTime + 1, 3, 10); ``` > **备注:** For a more complete example showing `start()` in use, check out our {{domxref("AudioContext.decodeAudioData()")}} example, You can also [run the code example live](http://mdn.github.io/decode-audio-data/), or [view the source](https://github.com/mdn/decode-audio-data). diff --git a/files/zh-cn/web/api/audiocontext/baselatency/index.md b/files/zh-cn/web/api/audiocontext/baselatency/index.md index 7a3761bbe91cbf..2eab6f4f629fbd 100644 --- a/files/zh-cn/web/api/audiocontext/baselatency/index.md +++ b/files/zh-cn/web/api/audiocontext/baselatency/index.md @@ -24,11 +24,11 @@ A double representing the base latency in seconds. ```js //default latency ("interactive") const audioCtx1 = new AudioContext(); -console.log(audioCtx1.baseLatency);//0.01 +console.log(audioCtx1.baseLatency); //0.01 //higher latency ("playback") -const audioCtx2 = new AudioContext({ latencyHint: 'playback' }); -console.log(audioCtx2.baseLatency);//0.02 +const audioCtx2 = new AudioContext({ latencyHint: "playback" }); +console.log(audioCtx2.baseLatency); //0.02 ``` ## Specifications diff --git a/files/zh-cn/web/api/audiocontext/close/index.md b/files/zh-cn/web/api/audiocontext/close/index.md index fdb06cfe7606c5..5d3df594ea651e 100644 --- a/files/zh-cn/web/api/audiocontext/close/index.md +++ b/files/zh-cn/web/api/audiocontext/close/index.md @@ -27,13 +27,13 @@ audioCtx.close().then(function() { ... }); 下面这段代码是[AudioContext states demo](https://github.com/mdn/audiocontext-states/settings) ([直接运行](http://mdn.github.io/audiocontext-states/)) 中的,点击停止按钮调用`close()`。promise 释放后,回到初始状态。 ```js -stopBtn.onclick = function() { - audioCtx.close().then(function() { - startBtn.removeAttribute('disabled'); - susresBtn.setAttribute('disabled','disabled'); - stopBtn.setAttribute('disabled','disabled'); +stopBtn.onclick = function () { + audioCtx.close().then(function () { + startBtn.removeAttribute("disabled"); + susresBtn.setAttribute("disabled", "disabled"); + stopBtn.setAttribute("disabled", "disabled"); }); -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/audiocontext/createmediaelementsource/index.md b/files/zh-cn/web/api/audiocontext/createmediaelementsource/index.md index 05b820c9c30b11..3e6cfe88e761ea 100644 --- a/files/zh-cn/web/api/audiocontext/createmediaelementsource/index.md +++ b/files/zh-cn/web/api/audiocontext/createmediaelementsource/index.md @@ -33,9 +33,9 @@ var source = audioCtx.createMediaElementSource(myMediaElement); ```js var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); -var myAudio = document.querySelector('audio'); -var pre = document.querySelector('pre'); -var myScript = document.querySelector('script'); +var myAudio = document.querySelector("audio"); +var pre = document.querySelector("pre"); +var myScript = document.querySelector("script"); pre.innerHTML = myScript.innerHTML; @@ -57,12 +57,16 @@ var HEIGHT = window.innerHeight; document.onmousemove = updatePage; function updatePage(e) { - CurY = (window.Event) ? e.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop); - - gainNode.gain.value = CurY/HEIGHT; + CurY = window.Event + ? e.pageY + : event.clientY + + (document.documentElement.scrollTop + ? document.documentElement.scrollTop + : document.body.scrollTop); + + gainNode.gain.value = CurY / HEIGHT; } - // connect the AudioBufferSourceNode to the gainNode // and the gainNode to the destination, so we can play the // music and adjust the volume using the mouse cursor diff --git a/files/zh-cn/web/api/audiocontext/createmediastreamdestination/index.md b/files/zh-cn/web/api/audiocontext/createmediastreamdestination/index.md index 8eefbda59e7a23..f0683975138526 100644 --- a/files/zh-cn/web/api/audiocontext/createmediastreamdestination/index.md +++ b/files/zh-cn/web/api/audiocontext/createmediastreamdestination/index.md @@ -31,7 +31,7 @@ When the button is clicked, the oscillator starts, and the `MediaRecorder` is st From here, you can play and save the opus file. ```html - + createMediaStreamDestination() demo @@ -39,42 +39,42 @@ From here, you can play and save the opus file.

createMediaStreamDestination() demo

-

Encoding a pure sine wave to an Opus file

+

Encoding a pure sine wave to an Opus file

diff --git a/files/zh-cn/web/api/audiocontext/createmediastreamsource/index.md b/files/zh-cn/web/api/audiocontext/createmediastreamsource/index.md index 1e049d078919d3..15aaea1a77cf46 100644 --- a/files/zh-cn/web/api/audiocontext/createmediastreamsource/index.md +++ b/files/zh-cn/web/api/audiocontext/createmediastreamsource/index.md @@ -34,54 +34,55 @@ var source = audioCtx.createMediaStreamSource(stream); > **备注:** 你可以查看[在线演示](https://mdn.github.io/webaudio-examples/stream-source-buffer/),或者[查看源码](https://github.com/mdn/webaudio-examples/tree/main/stream-source-buffer)。 ```js -var pre = document.querySelector('pre'); -var video = document.querySelector('video'); -var myScript = document.querySelector('script'); -var range = document.querySelector('input'); +var pre = document.querySelector("pre"); +var video = document.querySelector("video"); +var myScript = document.querySelector("script"); +var range = document.querySelector("input"); // getUserMedia 获取流 // 把流放入 MediaStreamAudioSourceNode // 输出到 video 元素 if (navigator.mediaDevices) { - console.log('getUserMedia supported.'); - navigator.mediaDevices.getUserMedia ({audio: true, video: true}) - .then(function(stream) { - video.srcObject = stream; - video.onloadedmetadata = function(e) { - video.play(); - video.muted = true; - }; - - // 创建 MediaStreamAudioSourceNode - // Feed the HTMLMediaElement into it - var audioCtx = new AudioContext(); - var source = audioCtx.createMediaStreamSource(stream); - - // 创建二阶滤波器 - var biquadFilter = audioCtx.createBiquadFilter(); - biquadFilter.type = "lowshelf"; - biquadFilter.frequency.value = 1000; + console.log("getUserMedia supported."); + navigator.mediaDevices + .getUserMedia({ audio: true, video: true }) + .then(function (stream) { + video.srcObject = stream; + video.onloadedmetadata = function (e) { + video.play(); + video.muted = true; + }; + + // 创建 MediaStreamAudioSourceNode + // Feed the HTMLMediaElement into it + var audioCtx = new AudioContext(); + var source = audioCtx.createMediaStreamSource(stream); + + // 创建二阶滤波器 + var biquadFilter = audioCtx.createBiquadFilter(); + biquadFilter.type = "lowshelf"; + biquadFilter.frequency.value = 1000; + biquadFilter.gain.value = range.value; + + // 把 AudioBufferSourceNode 连接到 gainNode + // gainNode 连接到目的地,所以我们可以播放 + // 音乐并用鼠标调节音量 + source.connect(biquadFilter); + biquadFilter.connect(audioCtx.destination); + + // Get new mouse pointer coordinates when mouse is moved + // then set new gain value + + range.oninput = function () { biquadFilter.gain.value = range.value; - - // 把 AudioBufferSourceNode 连接到 gainNode - // gainNode 连接到目的地,所以我们可以播放 - // 音乐并用鼠标调节音量 - source.connect(biquadFilter); - biquadFilter.connect(audioCtx.destination); - - // Get new mouse pointer coordinates when mouse is moved - // then set new gain value - - range.oninput = function() { - biquadFilter.gain.value = range.value; - } + }; }) - .catch(function(err) { - console.log('The following gUM error occured: ' + err); + .catch(function (err) { + console.log("The following gUM error occured: " + err); }); } else { - console.log('getUserMedia not supported on your browser!'); + console.log("getUserMedia not supported on your browser!"); } // dump script to pre element diff --git a/files/zh-cn/web/api/audiocontext/resume/index.md b/files/zh-cn/web/api/audiocontext/resume/index.md index da2f2ca20426fc..cc9f87a7959486 100644 --- a/files/zh-cn/web/api/audiocontext/resume/index.md +++ b/files/zh-cn/web/api/audiocontext/resume/index.md @@ -25,17 +25,17 @@ audioCtx.resume().then(function() { ... }); 下面的代码是 [AudioContext states demo](https://github.com/mdn/audiocontext-states/settings) ([see it running live](http://mdn.github.io/audiocontext-states/)) 的一部分。当点击暂停/恢复按钮的时候,需要{{domxref("AudioContext.state")}}做判断:如果是运行状态,调用{{domxref("suspend()")}},如果是暂停状态,调用`resume()。每次点击事件成功后,按钮的文字也会随着变成对应的状态`。 ```js -susresBtn.onclick = function() { - if(audioCtx.state === 'running') { - audioCtx.suspend().then(function() { - susresBtn.textContent = 'Resume context'; +susresBtn.onclick = function () { + if (audioCtx.state === "running") { + audioCtx.suspend().then(function () { + susresBtn.textContent = "Resume context"; }); - } else if(audioCtx.state === 'suspended') { - audioCtx.resume().then(function() { - susresBtn.textContent = 'Suspend context'; + } else if (audioCtx.state === "suspended") { + audioCtx.resume().then(function () { + susresBtn.textContent = "Suspend context"; }); } -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/audiocontext/suspend/index.md b/files/zh-cn/web/api/audiocontext/suspend/index.md index 5792d9f48928af..e30ac70625b236 100644 --- a/files/zh-cn/web/api/audiocontext/suspend/index.md +++ b/files/zh-cn/web/api/audiocontext/suspend/index.md @@ -25,17 +25,17 @@ A {{jsxref("Promise")}} that resolves with void. The promise is rejected if the The following snippet is taken from our [AudioContext states demo](https://github.com/mdn/audiocontext-states/settings) ([see it running live](http://mdn.github.io/audiocontext-states/).) When the suspend/resume button is clicked, the {{domxref("AudioContext.state")}} is queried — if it is `running`, `suspend()` is called; if it is `suspended`, {{domxref("resume")}} is called. In each case, the text label of the button is updated as appropriate once the promise resolves. ```js -susresBtn.onclick = function() { - if(audioCtx.state === 'running') { - audioCtx.suspend().then(function() { - susresBtn.textContent = 'Resume context'; +susresBtn.onclick = function () { + if (audioCtx.state === "running") { + audioCtx.suspend().then(function () { + susresBtn.textContent = "Resume context"; }); - } else if(audioCtx.state === 'suspended') { - audioCtx.resume().then(function() { - susresBtn.textContent = 'Suspend context'; + } else if (audioCtx.state === "suspended") { + audioCtx.resume().then(function () { + susresBtn.textContent = "Suspend context"; }); } -} +}; ``` ## Specifications diff --git a/files/zh-cn/web/api/audiodestinationnode/index.md b/files/zh-cn/web/api/audiodestinationnode/index.md index 61c64668b16828..8aea1315e8d3a0 100644 --- a/files/zh-cn/web/api/audiodestinationnode/index.md +++ b/files/zh-cn/web/api/audiodestinationnode/index.md @@ -45,7 +45,7 @@ _从{{domxref("AudioNode")}}继承的属性_. ## 方法 -*继承 {{domxref("AudioNode")}} 的方法。* +_继承 {{domxref("AudioNode")}} 的方法。_ ## 例子 diff --git a/files/zh-cn/web/api/audionode/index.md b/files/zh-cn/web/api/audionode/index.md index ed4048d16af2da..c210e6152ea4c2 100644 --- a/files/zh-cn/web/api/audionode/index.md +++ b/files/zh-cn/web/api/audionode/index.md @@ -29,18 +29,18 @@ slug: Web/API/AudioNode - : Represents an enumerated value describing the way channels must be matched between the inputs and the outputs. Possible values are: - | Value | Description | Used as default for the following `AudioNode` children | - | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | + | Value | Description | Used as default for the following `AudioNode` children | + | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `"max"` | The number of channels is the maximum of the number of channels all connections. That implies that `channelCount` is ignored and only up-mixing happens | {{domxref("GainNode")}}, {{domxref("DelayNode")}}, {{domxref("ScriptProcessorNode")}}, {{domxref("ChannelSplitterNode")}}, {{domxref("ChannelMergerNode")}}, {{domxref("BiquadFilterNode")}}, {{domxref("WaveShaperNode")}} | - | `"clamped-max"` | The number of channels is the maximum of the number of channels of all connections, _clamped_ to the value of `channelCount`. | {{domxref("PannerNode")}}, {{domxref("ConvolverNode")}} | - | `"explicit"` | The number of channels is defined by the value of `channelCount`. | {{domxref("AudioDestinationNode")}}, {{domxref("AnalyserNode")}}, {{domxref("DynamicsCompressorNode")}} | + | `"clamped-max"` | The number of channels is the maximum of the number of channels of all connections, _clamped_ to the value of `channelCount`. | {{domxref("PannerNode")}}, {{domxref("ConvolverNode")}} | + | `"explicit"` | The number of channels is defined by the value of `channelCount`. | {{domxref("AudioDestinationNode")}}, {{domxref("AnalyserNode")}}, {{domxref("DynamicsCompressorNode")}} | - {{domxref("AudioNode.channelInterpretation")}} - : Represents an enumerated value describing the meaning of the channels. This interpretation will define how the up-mixing and the down-mixing will happen. The possible values are `"speakers"` or `"discrete"`. In the case of `"speakers"`, the ordering of the channels have the following meaning, and the channels are often represented by a standard abbreviation: - | Value | Description | + | Value | Description | | -------- | -------------------------------------------------------------------------------------------------- | | _Mono_ | `0: M: mono` | | _Stereo_ | `0: L: left 1: R: right` | diff --git a/files/zh-cn/web/api/audioparamdescriptor/index.md b/files/zh-cn/web/api/audioparamdescriptor/index.md index af406bb601182b..e0628497a42581 100644 --- a/files/zh-cn/web/api/audioparamdescriptor/index.md +++ b/files/zh-cn/web/api/audioparamdescriptor/index.md @@ -27,17 +27,19 @@ The **`AudioParamDescriptor`** dictionary of the [Web Audio API](/zh-CN/docs/Web ```js // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { - static get parameterDescriptors () { - return [{ - name: 'customGain', - defaultValue: 1, - minValue: 0, - maxValue: 1, - automationRate: 'a-rate' - }] + static get parameterDescriptors() { + return [ + { + name: "customGain", + defaultValue: 1, + minValue: 0, + maxValue: 1, + automationRate: "a-rate", + }, + ]; } -// … + // … } ``` diff --git a/files/zh-cn/web/api/audiotrack/index.md b/files/zh-cn/web/api/audiotrack/index.md index f911b54d1a2d36..156e990c361bc9 100644 --- a/files/zh-cn/web/api/audiotrack/index.md +++ b/files/zh-cn/web/api/audiotrack/index.md @@ -36,14 +36,14 @@ var tracks = el.audioTracks; 第一个示例获取媒体上的第一个音轨: ```js -var firstTrack = tracks [0]; +var firstTrack = tracks[0]; ``` 下一个示例扫描所有媒体的音轨,启用用户首选语言中的任何一种 (取自变量`userLanguage`) 并禁用任何其他语音。 ```js -tracks.forEach(function(track){ - if(track.language === userLanguage){ +tracks.forEach(function (track) { + if (track.language === userLanguage) { track.enabled = true; } else { track.enabled = false; diff --git a/files/zh-cn/web/api/audioworkletnode/index.md b/files/zh-cn/web/api/audioworkletnode/index.md index bc7ce4ada56c7e..e5c1d76491bcfa 100644 --- a/files/zh-cn/web/api/audioworkletnode/index.md +++ b/files/zh-cn/web/api/audioworkletnode/index.md @@ -43,27 +43,30 @@ _AudioWorkletNode 接口未定义其自己的任何方法。_ ```js // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { - process (inputs, outputs, parameters) { - const output = outputs[0] - output.forEach(channel => { + process(inputs, outputs, parameters) { + const output = outputs[0]; + output.forEach((channel) => { for (let i = 0; i < channel.length; i++) { - channel[i] = Math.random() * 2 - 1 + channel[i] = Math.random() * 2 - 1; } - }) - return true + }); + return true; } } -registerProcessor('white-noise-processor', WhiteNoiseProcessor) +registerProcessor("white-noise-processor", WhiteNoiseProcessor); ``` 接下来,在脚本主文件中一个 `AudioWorkletNode` 实例,并传递处理器的名称,然后将该实例连接到一个 audio graph. ```js -const audioContext = new AudioContext() -await audioContext.audioWorklet.addModule('white-noise-processor.js') -const whiteNoiseNode = new AudioWorkletNode(audioContext, 'white-noise-processor') -whiteNoiseNode.connect(audioContext.destination) +const audioContext = new AudioContext(); +await audioContext.audioWorklet.addModule("white-noise-processor.js"); +const whiteNoiseNode = new AudioWorkletNode( + audioContext, + "white-noise-processor", +); +whiteNoiseNode.connect(audioContext.destination); ``` ## 规范 diff --git a/files/zh-cn/web/api/audioworkletprocessor/index.md b/files/zh-cn/web/api/audioworkletprocessor/index.md index 49965a242a1a43..ff04b739bde03d 100644 --- a/files/zh-cn/web/api/audioworkletprocessor/index.md +++ b/files/zh-cn/web/api/audioworkletprocessor/index.md @@ -44,8 +44,8 @@ The resulting `AudioParam`s reside in the {{domxref("AudioWorkletNode.parameters 1. 创建一个独立的文件; 2. 在这个文件中: - 1. Extend the `AudioWorkletProcessor` class (see ["Deriving classes" section](#Deriving_classes)) and supply your own {{domxref("AudioWorkletProcessor.process", "process()")}} method in it; - 2. Register the processor using {{domxref("AudioWorkletGlobalScope.registerProcessor()")}} method; + 1. Extend the `AudioWorkletProcessor` class (see ["Deriving classes" section](#Deriving_classes)) and supply your own {{domxref("AudioWorkletProcessor.process", "process()")}} method in it; + 2. Register the processor using {{domxref("AudioWorkletGlobalScope.registerProcessor()")}} method; 3. Load the file using {{domxref("Worklet.addModule", "addModule()")}} method on your audio context's {{domxref("BaseAudioContext.audioWorklet", "audioWorklet")}} property; 4. Create an {{domxref("AudioWorkletNode")}} based on the processor. The processor will be instantiated internally by the `AudioWorkletNode` constructor. @@ -60,27 +60,30 @@ First, we need to define a custom `AudioWorkletProcessor`, which will output whi ```js // white-noise-processor.js class WhiteNoiseProcessor extends AudioWorkletProcessor { - process (inputs, outputs, parameters) { - const output = outputs[0] - output.forEach(channel => { + process(inputs, outputs, parameters) { + const output = outputs[0]; + output.forEach((channel) => { for (let i = 0; i < channel.length; i++) { - channel[i] = Math.random() * 2 - 1 + channel[i] = Math.random() * 2 - 1; } - }) - return true + }); + return true; } } -registerProcessor('white-noise-processor', WhiteNoiseProcessor) +registerProcessor("white-noise-processor", WhiteNoiseProcessor); ``` Next, in our main script file we'll load the processor, create an instance of {{domxref("AudioWorkletNode")}}, passing it the name of the processor, then connect the node to an audio graph. ```js -const audioContext = new AudioContext() -await audioContext.audioWorklet.addModule('white-noise-processor.js') -const whiteNoiseNode = new AudioWorkletNode(audioContext, 'white-noise-processor') -whiteNoiseNode.connect(audioContext.destination) +const audioContext = new AudioContext(); +await audioContext.audioWorklet.addModule("white-noise-processor.js"); +const whiteNoiseNode = new AudioWorkletNode( + audioContext, + "white-noise-processor", +); +whiteNoiseNode.connect(audioContext.destination); ``` ## Specifications diff --git a/files/zh-cn/web/api/authenticatorresponse/clientdatajson/index.md b/files/zh-cn/web/api/authenticatorresponse/clientdatajson/index.md index 1aa48e718049f0..e34a4c887b3dd2 100644 --- a/files/zh-cn/web/api/authenticatorresponse/clientdatajson/index.md +++ b/files/zh-cn/web/api/authenticatorresponse/clientdatajson/index.md @@ -41,16 +41,16 @@ After the `clientDataJSON` object is converted from an `ArrayBuffer` to a JavaSc ```js function arrayBufferToStr(buf) { - return String.fromCharCode.apply(null, new Uint8Array(buf)); + return String.fromCharCode.apply(null, new Uint8Array(buf)); } // pk is a PublicKeyCredential that is the result of a create() or get() Promise var clientDataStr = arrayBufferToStr(pk.clientDataJSON); var clientDataObj = JSON.parse(clientDataStr); -console.log(clientDataObj.type); // "webauthn.create" or "webauthn.get" +console.log(clientDataObj.type); // "webauthn.create" or "webauthn.get" console.log(clientDataObj.challenge); // base64 encoded String containing the original challenge -console.log(clientDataObj.origin); // the window.origin +console.log(clientDataObj.origin); // the window.origin ``` ## 规范 diff --git a/files/zh-cn/web/api/authenticatorresponse/index.md b/files/zh-cn/web/api/authenticatorresponse/index.md index 70162adfa75f68..54ae60052daa6c 100644 --- a/files/zh-cn/web/api/authenticatorresponse/index.md +++ b/files/zh-cn/web/api/authenticatorresponse/index.md @@ -29,17 +29,21 @@ Below is a list of interfaces based on the AuthenticatorResponse interface. ```js var options = { - challenge: new Uint8Array([/* bytes sent from the server */]) + challenge: new Uint8Array([ + /* bytes sent from the server */ + ]), }; -navigator.credentials.get({ "publicKey": options }) - .then(function (credentialInfoAssertion) { +navigator.credentials + .get({ publicKey: options }) + .then(function (credentialInfoAssertion) { var assertionResponse = credentialInfoAssertion.response; // send assertion response back to the server // to proceed with the control of the credential -}).catch(function (err) { - console.error(err); -}); + }) + .catch(function (err) { + console.error(err); + }); ``` ### Getting an AuthenticatorAttestationResponse diff --git a/files/zh-cn/web/api/background_tasks_api/index.md b/files/zh-cn/web/api/background_tasks_api/index.md index b0b1721c640e49..08429c5a00d3d6 100644 --- a/files/zh-cn/web/api/background_tasks_api/index.md +++ b/files/zh-cn/web/api/background_tasks_api/index.md @@ -30,18 +30,20 @@ slug: Web/API/Background_Tasks_API 因为后台任务 API 还是相当新的,而你的代码可能需要在那些不仍不支持此 API 的浏览器上运行。你可以把 {{domxref("WindowTimers.setTimeout()", "setTimeout()")}} 用作回调选项来做这样的事。这个并不是 {{Glossary("polyfill")}} ,因为它在功能上并不相同; `setTimeout()` 并不会让你利用空闲时段,而是使你的代码在情况允许时执行你的代码,以使我们可以尽可能地避免造成用户体验性能表现延迟的后果。 ```js -window.requestIdleCallback = window.requestIdleCallback || function(handler) { - let startTime = Date.now(); - - return setTimeout(function() { - handler({ - didTimeout: false, - timeRemaining: function() { - return Math.max(0, 50.0 - (Date.now() - startTime)); - } - }); - }, 1); -} +window.requestIdleCallback = + window.requestIdleCallback || + function (handler) { + let startTime = Date.now(); + + return setTimeout(function () { + handler({ + didTimeout: false, + timeRemaining: function () { + return Math.max(0, 50.0 - (Date.now() - startTime)); + }, + }); + }, 1); + }; ``` 如果 {{domxref("Window.requestIdleCallback", "window.requestIdleCallback")}} 是 undefined, 我们在这里把它创建出来。这个函数首先会记录我们调用具体实现的时间。我们将用它计算填充程序{{domxref("IdleDeadline.timeRemaining()", "timeRemaining()")}}返回的值。 @@ -53,9 +55,11 @@ window.requestIdleCallback = window.requestIdleCallback || function(handler) { 我们{{domxref("Window.cancelIdleCallback", "cancelIdleCallback()")}}的具体实现要简单的多。 ```js -window.cancelIdleCallback = window.cancelIdleCallback || function(id) { - clearTimeout(id); -} +window.cancelIdleCallback = + window.cancelIdleCallback || + function (id) { + clearTimeout(id); + }; ``` 如果`cancelIdleCallback()`没有定义,它将创建一个来简单地把指定回调 ID 传递给{{domxref("WindowTimers.clearTimeout", "clearTimeout()")}}。 @@ -119,7 +123,7 @@ body { .logBox { margin-top: 16px; width: 400px; - height:500px; + height: 500px; border-radius: 6px; border: 1px solid black; box-shadow: 4px 4px 2px black; @@ -135,7 +139,9 @@ body { } #log { - font: 12px "Courier", monospace; + font: + 12px "Courier", + monospace; padding: 6px; overflow: auto; overflow-y: scroll; @@ -230,22 +236,26 @@ let statusRefreshScheduled = false; - `statusRefreshScheduled` 我们用它来追踪我们是否已经为即将到来的帧安排了状态显示框的更新,所以我们每一帧只执行一次。 ```js hidden -window.requestIdleCallback = window.requestIdleCallback || function(handler) { - let startTime = Date.now(); - - return setTimeout(function() { - handler({ - didTimeout: false, - timeRemaining: function() { - return Math.max(0, 50.0 - (Date.now() - startTime)); - } - }); - }, 1); -}; - -window.cancelIdleCallback = window.cancelIdleCallback || function(id) { - clearTimeout(id); -}; +window.requestIdleCallback = + window.requestIdleCallback || + function (handler) { + let startTime = Date.now(); + + return setTimeout(function () { + handler({ + didTimeout: false, + timeRemaining: function () { + return Math.max(0, 50.0 - (Date.now() - startTime)); + }, + }); + }, 1); + }; + +window.cancelIdleCallback = + window.cancelIdleCallback || + function (id) { + clearTimeout(id); + }; ``` #### 管理任务队列 @@ -260,7 +270,7 @@ window.cancelIdleCallback = window.cancelIdleCallback || function(id) { function enqueueTask(taskHandler, taskData) { taskList.push({ handler: taskHandler, - data: taskData + data: taskData, }); totalTaskCount++; @@ -288,7 +298,10 @@ function enqueueTask(taskHandler, taskData) { ```js function runTaskQueue(deadline) { - while ((deadline.timeRemaining() > 0 || deadline.didTimeout) && taskList.length) { + while ( + (deadline.timeRemaining() > 0 || deadline.didTimeout) && + taskList.length + ) { let task = taskList.shift(); currentTaskNumber++; @@ -297,7 +310,7 @@ function runTaskQueue(deadline) { } if (taskList.length) { - taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000} ); + taskHandle = requestIdleCallback(runTaskQueue, { timeout: 1000 }); } else { taskHandle = 0; } @@ -325,9 +338,9 @@ function runTaskQueue(deadline) { ```js function scheduleStatusRefresh() { - if (!statusRefreshScheduled) { - requestAnimationFrame(updateDisplay); - statusRefreshScheduled = true; + if (!statusRefreshScheduled) { + requestAnimationFrame(updateDisplay); + statusRefreshScheduled = true; } } ``` @@ -340,7 +353,8 @@ function scheduleStatusRefresh() { ```js function updateDisplay() { - let scrolledToEnd = logElem.scrollHeight - logElem.clientHeight <= logElem.scrollTop + 1; + let scrolledToEnd = + logElem.scrollHeight - logElem.clientHeight <= logElem.scrollTop + 1; if (totalTaskCount) { if (progressBarElem.max != totalTaskCount) { @@ -360,7 +374,7 @@ function updateDisplay() { } if (scrolledToEnd) { - logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight; + logElem.scrollTop = logElem.scrollHeight - logElem.clientHeight; } statusRefreshScheduled = false; @@ -385,7 +399,7 @@ function updateDisplay() { ```js function log(text) { if (!logFragment) { - logFragment = document.createDocumentFragment(); + logFragment = document.createDocumentFragment(); } let el = document.createElement("div"); @@ -410,8 +424,8 @@ function log(text) { function logTaskHandler(data) { log("Running task #" + currentTaskNumber + ""); - for (i=0; i **备注:** 完整的示例参照 [script-processor-node](https://mdn.github.io/webaudio-examples/script-processor-node/) github (查看源码 [source code](https://github.com/mdn/webaudio-examples/blob/master/script-processor-node/index.html).) ```js -var myScript = document.querySelector('script'); -var myPre = document.querySelector('pre'); -var playButton = document.querySelector('button'); +var myScript = document.querySelector("script"); +var myPre = document.querySelector("pre"); +var playButton = document.querySelector("button"); // Create AudioContext and buffer source var audioCtx = new AudioContext(); @@ -55,22 +59,27 @@ console.log(scriptNode.bufferSize); function getData() { request = new XMLHttpRequest(); - request.open('GET', 'viper.ogg', true); - request.responseType = 'arraybuffer'; - request.onload = function() { + request.open("GET", "viper.ogg", true); + request.responseType = "arraybuffer"; + request.onload = function () { var audioData = request.response; - audioCtx.decodeAudioData(audioData, function(buffer) { - myBuffer = buffer; - source.buffer = myBuffer; - }, - function(e){"Error with decoding audio data" + e.err}); - } + audioCtx.decodeAudioData( + audioData, + function (buffer) { + myBuffer = buffer; + source.buffer = myBuffer; + }, + function (e) { + "Error with decoding audio data" + e.err; + }, + ); + }; request.send(); } // Give the node a function to process audio events -scriptNode.onaudioprocess = function(audioProcessingEvent) { +scriptNode.onaudioprocess = function (audioProcessingEvent) { // The input buffer is the song we loaded earlier var inputBuffer = audioProcessingEvent.inputBuffer; @@ -88,25 +97,25 @@ scriptNode.onaudioprocess = function(audioProcessingEvent) { outputData[sample] = inputData[sample]; // add noise to each output sample - outputData[sample] += ((Math.random() * 2) - 1) * 0.2; + outputData[sample] += (Math.random() * 2 - 1) * 0.2; } } -} +}; getData(); // wire up play button -playButton.onclick = function() { +playButton.onclick = function () { source.connect(scriptNode); scriptNode.connect(audioCtx.destination); source.start(); -} +}; // When the buffer source stops playing, disconnect everything -source.onended = function() { +source.onended = function () { source.disconnect(scriptNode); scriptNode.disconnect(audioCtx.destination); -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/baseaudiocontext/decodeaudiodata/index.md b/files/zh-cn/web/api/baseaudiocontext/decodeaudiodata/index.md index 339b12530c0007..45de7d558f3192 100644 --- a/files/zh-cn/web/api/baseaudiocontext/decodeaudiodata/index.md +++ b/files/zh-cn/web/api/baseaudiocontext/decodeaudiodata/index.md @@ -45,10 +45,10 @@ audioCtx.decodeAudioData(audioData).then(function(decodedData) { var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var source; -var pre = document.querySelector('pre'); -var myScript = document.querySelector('script'); -var play = document.querySelector('.play'); -var stop = document.querySelector('.stop'); +var pre = document.querySelector("pre"); +var myScript = document.querySelector("script"); +var play = document.querySelector(".play"); +var stop = document.querySelector(".stop"); // use XHR to load an audio track, and // decodeAudioData to decode it and stick it in a buffer. @@ -58,41 +58,43 @@ function getData() { source = audioCtx.createBufferSource(); var request = new XMLHttpRequest(); - request.open('GET', 'viper.ogg', true); + request.open("GET", "viper.ogg", true); - request.responseType = 'arraybuffer'; + request.responseType = "arraybuffer"; - - request.onload = function() { + request.onload = function () { var audioData = request.response; - audioCtx.decodeAudioData(audioData, function(buffer) { + audioCtx.decodeAudioData( + audioData, + function (buffer) { source.buffer = buffer; source.connect(audioCtx.destination); source.loop = true; }, - function(e){"Error with decoding audio data" + e.err}); - - } + function (e) { + "Error with decoding audio data" + e.err; + }, + ); + }; request.send(); } // wire up buttons to stop and play audio -play.onclick = function() { +play.onclick = function () { getData(); source.start(0); - play.setAttribute('disabled', 'disabled'); -} + play.setAttribute("disabled", "disabled"); +}; -stop.onclick = function() { +stop.onclick = function () { source.stop(0); - play.removeAttribute('disabled'); -} - + play.removeAttribute("disabled"); +}; // dump script to pre element @@ -102,8 +104,8 @@ pre.innerHTML = myScript.innerHTML; ### 新的 promise-based 语法 ```js -ctx.decodeAudioData(compressedBuffer).then(function(decodedData) { - // use the decoded data here +ctx.decodeAudioData(compressedBuffer).then(function (decodedData) { + // use the decoded data here }); ``` diff --git a/files/zh-cn/web/api/baseaudiocontext/state/index.md b/files/zh-cn/web/api/baseaudiocontext/state/index.md index 641ecd0e512b92..27e509fbd8821c 100644 --- a/files/zh-cn/web/api/baseaudiocontext/state/index.md +++ b/files/zh-cn/web/api/baseaudiocontext/state/index.md @@ -27,9 +27,9 @@ var myState = audioCtx.state; 下面这段代码是[AudioContext states demo](https://github.com/mdn/audiocontext-states/settings) (直接运行) 中的,其中{{domxref("AudioContext.onstatechange")}}处理器会在每次当前状态发生变化时把它输出到控制台。 ```js -audioCtx.onstatechange = function() { +audioCtx.onstatechange = function () { console.log(audioCtx.state); -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/baseaudiocontext/statechange_event/index.md b/files/zh-cn/web/api/baseaudiocontext/statechange_event/index.md index 7cd79dcdb5bf25..e414ac4de9ee3a 100644 --- a/files/zh-cn/web/api/baseaudiocontext/statechange_event/index.md +++ b/files/zh-cn/web/api/baseaudiocontext/statechange_event/index.md @@ -19,9 +19,9 @@ audioCtx.onstatechange = function() { ... }; 下面这段代码是[AudioContext states DEMO](https://github.com/mdn/audiocontext-states/settings) ([直接运行](http://mdn.github.io/audiocontext-states/)) 中的,其中 `onstatechange` 处理器会在每次当前 {{domxref("state")}} 发生变化时把它输出到控制台。 ```js -audioCtx.onstatechange = function() { +audioCtx.onstatechange = function () { console.log(audioCtx.state); -} +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/batterymanager/charging/index.md b/files/zh-cn/web/api/batterymanager/charging/index.md index 9c3fd590f497c5..b06d70a97ba3f3 100644 --- a/files/zh-cn/web/api/batterymanager/charging/index.md +++ b/files/zh-cn/web/api/batterymanager/charging/index.md @@ -26,11 +26,10 @@ var charging = battery.charging ### JavaScript ```js -navigator.getBattery().then(function(battery) { +navigator.getBattery().then(function (battery) { + var charging = battery.charging; - var charging = battery.charging; - - document.querySelector('#charging').textContent = charging ; + document.querySelector("#charging").textContent = charging; }); ``` diff --git a/files/zh-cn/web/api/beforeunloadevent/index.md b/files/zh-cn/web/api/beforeunloadevent/index.md index f1571ec496195e..8fccab930666e8 100644 --- a/files/zh-cn/web/api/beforeunloadevent/index.md +++ b/files/zh-cn/web/api/beforeunloadevent/index.md @@ -33,12 +33,12 @@ slug: Web/API/BeforeUnloadEvent ## 示例 ```js -window.addEventListener("beforeunload", function( event ) { - event.returnValue = "\o/"; +window.addEventListener("beforeunload", function (event) { + event.returnValue = "\\o/"; }); //等同于 -window.addEventListener("beforeunload", function( event ) { +window.addEventListener("beforeunload", function (event) { event.preventDefault(); }); ``` @@ -47,10 +47,10 @@ window.addEventListener("beforeunload", function( event ) { ```js window.addEventListener("beforeunload", function (e) { - var confirmationMessage = "\o/"; + var confirmationMessage = "\\o/"; - (e || window.event).returnValue = confirmationMessage; //Gecko + IE - return confirmationMessage; //Webkit, Safari, Chrome etc. + (e || window.event).returnValue = confirmationMessage; //Gecko + IE + return confirmationMessage; //Webkit, Safari, Chrome etc. }); ``` diff --git a/files/zh-cn/web/api/blob/blob/index.md b/files/zh-cn/web/api/blob/blob/index.md index 144c248d1dfc48..d2f5eae721a6c2 100644 --- a/files/zh-cn/web/api/blob/blob/index.md +++ b/files/zh-cn/web/api/blob/blob/index.md @@ -25,7 +25,7 @@ var aBlob = new Blob( array, options ); ```js var aFileParts = ['hey!']; // 一个包含 DOMString 的数组 -var oMyBlob = new Blob(aFileParts, {type : 'text/html'}); // 得到 blob +var oMyBlob = new Blob(aFileParts, { type: "text/html" }); // 得到 blob ``` ## 标准 diff --git a/files/zh-cn/web/api/blob/index.md b/files/zh-cn/web/api/blob/index.md index 258637c1164fc3..2f7f69f922d816 100644 --- a/files/zh-cn/web/api/blob/index.md +++ b/files/zh-cn/web/api/blob/index.md @@ -45,8 +45,10 @@ Blob 表示的不一定是 JavaScript 原生格式的数据。{{DOMxRef("File")} {{DOMxRef("Blob.Blob", "Blob()")}} 构造函数可以通过其他对象创建 blob。例如,用一个 JSON 字符串构造一个 blob: ```js -const obj = {hello: 'world'}; -const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json'}); +const obj = { hello: "world" }; +const blob = new Blob([JSON.stringify(obj, null, 2)], { + type: "application/json", +}); ``` ### 创建一个指向类型化数组的 URL @@ -56,10 +58,11 @@ const blob = new Blob([JSON.stringify(obj, null, 2)], {type : 'application/json' #### HTML ```html -

此示例创建一个类型化数组,其中包含空格以及 A 到 - Z 的 ASCII 字符。然后将其转换为一个对象 - URL。并创建一个打开该对象 URL 的链接。点击这个链接以查看对象 - URL 解码后的内容。

+

+ 此示例创建一个类型化数组,其中包含空格以及 A 到 Z 的 ASCII + 字符。然后将其转换为一个对象 URL。并创建一个打开该对象 URL + 的链接。点击这个链接以查看对象 URL 解码后的内容。 +

``` #### JavaScript @@ -77,7 +80,7 @@ function showViewLiveResultButton() { const button = document.createElement("button"); button.textContent = "查看上面示例代码的渲染结果"; p.append(button); - button.addEventListener('click', () => window.open(location.href)); + button.addEventListener("click", () => window.open(location.href)); return true; } return false; @@ -85,8 +88,9 @@ function showViewLiveResultButton() { if (!showViewLiveResultButton()) { function typedArrayToURL(typedArray, mimeType) { - return URL.createObjectURL(new Blob([typedArray.buffer], - {type: mimeType})) + return URL.createObjectURL( + new Blob([typedArray.buffer], { type: mimeType }), + ); } const bytes = new Uint8Array(59); @@ -94,11 +98,11 @@ if (!showViewLiveResultButton()) { bytes[i] = 32 + i; } - const url = typedArrayToURL(bytes, 'text/plain'); + const url = typedArrayToURL(bytes, "text/plain"); - const link = document.createElement('a'); + const link = document.createElement("a"); link.href = url; - link.innerText = '打开这个数组的 URL'; + link.innerText = "打开这个数组的 URL"; document.body.appendChild(link); } @@ -114,8 +118,8 @@ if (!showViewLiveResultButton()) { ```js const reader = new FileReader(); -reader.addEventListener('loadend', () => { - // reader.result 包含被转化为类型化数组的 blob 中的内容 +reader.addEventListener("loadend", () => { + // reader.result 包含被转化为类型化数组的 blob 中的内容 }); reader.readAsArrayBuffer(blob); ``` @@ -123,7 +127,7 @@ reader.readAsArrayBuffer(blob); 另一种读取 `Blob` 中内容的方式是使用 {{domxref("Response")}} 对象。下述代码将 `Blob` 中的内容读取为文本: ```js -const text = await (new Response(blob)).text(); +const text = await new Response(blob).text(); ``` 或者,也可以使用 {{DOMxRef("Blob.prototype.text()")}}: diff --git a/files/zh-cn/web/api/blob/size/index.md b/files/zh-cn/web/api/blob/size/index.md index 44948b86af72f3..3de3ba0cea23c5 100644 --- a/files/zh-cn/web/api/blob/size/index.md +++ b/files/zh-cn/web/api/blob/size/index.md @@ -18,7 +18,7 @@ slug: Web/API/Blob/size ### HTML ```html - + Choose files… ``` @@ -32,11 +32,11 @@ output { ### JavaScript ```js -const input = document.getElementById('input'); -const output = document.getElementById('output'); +const input = document.getElementById("input"); +const output = document.getElementById("output"); -input.addEventListener('change', (event) => { - output.innerText = ''; +input.addEventListener("change", (event) => { + output.innerText = ""; for (const file of event.target.files) { output.innerText += `${file.name} has a size of ${file.size} bytes.\n`; diff --git a/files/zh-cn/web/api/blob/type/index.md b/files/zh-cn/web/api/blob/type/index.md index 054d3ffc762fa3..52f34a0b1f802f 100644 --- a/files/zh-cn/web/api/blob/type/index.md +++ b/files/zh-cn/web/api/blob/type/index.md @@ -47,11 +47,9 @@ input.addEventListener("change", (event) => { } const allAllowed = Array.from(files).every((file) => - allowedFileTypes.includes(file.type) + allowedFileTypes.includes(file.type), ); - output.innerText = allAllowed - ? "所有文件都符合!" - : "请只选择图片文件。"; + output.innerText = allAllowed ? "所有文件都符合!" : "请只选择图片文件。"; }); ``` diff --git a/files/zh-cn/web/api/broadcast_channel_api/index.md b/files/zh-cn/web/api/broadcast_channel_api/index.md index ba48770dca8b3d..751c324c87b466 100644 --- a/files/zh-cn/web/api/broadcast_channel_api/index.md +++ b/files/zh-cn/web/api/broadcast_channel_api/index.md @@ -23,7 +23,7 @@ slug: Web/API/Broadcast_Channel_API ```js // 连接到广播频道 -var bc = new BroadcastChannel('test_channel'); +var bc = new BroadcastChannel("test_channel"); ``` ### 发送消息 @@ -32,7 +32,7 @@ var bc = new BroadcastChannel('test_channel'); ```js // 发送简单消息的示例 -bc.postMessage('This is a test message.'); +bc.postMessage("This is a test message."); ``` 不只是 {{domxref("DOMString")}},任意类型的对象都可以被发送。此 API 不会将消息与任何的语义相关联,因此通道的参与者有必要知道预期的消息类型和消息的消费方式。 @@ -43,7 +43,9 @@ bc.postMessage('This is a test message.'); ```js // 简单示例,用于将事件打印到控制台 -bc.onmessage = function (ev) { console.log(ev); } +bc.onmessage = function (ev) { + console.log(ev); +}; ``` ### 与频道断开连接 @@ -52,7 +54,7 @@ bc.onmessage = function (ev) { console.log(ev); } ```js // 断开频道连接 -bc.close() +bc.close(); ``` ## 总结 diff --git a/files/zh-cn/web/api/broadcastchannel/broadcastchannel/index.md b/files/zh-cn/web/api/broadcastchannel/broadcastchannel/index.md index ac06d5ebc47c07..44a21c3eb4c3d5 100644 --- a/files/zh-cn/web/api/broadcastchannel/broadcastchannel/index.md +++ b/files/zh-cn/web/api/broadcastchannel/broadcastchannel/index.md @@ -12,7 +12,7 @@ slug: Web/API/BroadcastChannel/BroadcastChannel ## 语法 ```js -new BroadcastChannel(channelName) +new BroadcastChannel(channelName); ``` ### 参数 diff --git a/files/zh-cn/web/api/broadcastchannel/close/index.md b/files/zh-cn/web/api/broadcastchannel/close/index.md index 19273578461f1a..d7bd10eca7a4e1 100644 --- a/files/zh-cn/web/api/broadcastchannel/close/index.md +++ b/files/zh-cn/web/api/broadcastchannel/close/index.md @@ -19,7 +19,7 @@ var str = channel.close(); ```js // 连接到指定频道 -var bc = new BroadcastChannel('test_channel'); +var bc = new BroadcastChannel("test_channel"); // 其他操作 (如:postMessage, …) diff --git a/files/zh-cn/web/api/broadcastchannel/message_event/index.md b/files/zh-cn/web/api/broadcastchannel/message_event/index.md index 9492957f685f45..b5c2b3e1bb252b 100644 --- a/files/zh-cn/web/api/broadcastchannel/message_event/index.md +++ b/files/zh-cn/web/api/broadcastchannel/message_event/index.md @@ -12,8 +12,8 @@ slug: Web/API/BroadcastChannel/message_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 等方法中使用事件名称,或设置事件处理器属性。 ```js -addEventListener('message', (event) => { }) -onmessage = (event) => { } +addEventListener("message", (event) => {}); +onmessage = (event) => {}; ``` ## 事件类型 @@ -45,46 +45,49 @@ _除了下面列出的属性之外,还可以使用父接口 {{domxref("Event") ```html hidden

发送者

-
+
``` ```css hidden body { - border: 1px solid black; - padding: .5rem; - height: 150px; - font-family: "Fira Sans", sans-serif; + border: 1px solid black; + padding: 0.5rem; + height: 150px; + font-family: "Fira Sans", sans-serif; } h1 { - font: 1.6em "Fira Sans", sans-serif; - margin-bottom: 1rem; + font: + 1.6em "Fira Sans", + sans-serif; + margin-bottom: 1rem; } textarea { - padding: .2rem; + padding: 0.2rem; } -label, br { - margin: .5rem 0; +label, +br { + margin: 0.5rem 0; } button { - vertical-align: top; - height: 1.5rem; + vertical-align: top; + height: 1.5rem; } ``` ```js -const channel = new BroadcastChannel('example-channel'); -const messageControl = document.querySelector('#message'); -const broadcastMessageButton = document.querySelector('#broadcast-message'); +const channel = new BroadcastChannel("example-channel"); +const messageControl = document.querySelector("#message"); +const broadcastMessageButton = document.querySelector("#broadcast-message"); -broadcastMessageButton.addEventListener('click', () => { - channel.postMessage(messageControl.value); -}) +broadcastMessageButton.addEventListener("click", () => { + channel.postMessage(messageControl.value); +}); ``` ### 接收者 1 @@ -96,21 +99,23 @@ broadcastMessageButton.addEventListener('click', () => { ```css hidden body { - border: 1px solid black; - padding: .5rem; - height: 100px; - font-family: "Fira Sans", sans-serif; + border: 1px solid black; + padding: 0.5rem; + height: 100px; + font-family: "Fira Sans", sans-serif; } h1 { - font: 1.6em "Fira Sans", - sans-serif; margin-bottom: 1rem; + font: + 1.6em "Fira Sans", + sans-serif; + margin-bottom: 1rem; } ``` ```js -const channel = new BroadcastChannel('example-channel'); -channel.addEventListener('message', (event) => { +const channel = new BroadcastChannel("example-channel"); +channel.addEventListener("message", (event) => { received.textContent = event.data; }); ``` @@ -124,21 +129,23 @@ channel.addEventListener('message', (event) => { ```css hidden body { - border: 1px solid black; - padding: .5rem; - height: 100px; - font-family: "Fira Sans", sans-serif; + border: 1px solid black; + padding: 0.5rem; + height: 100px; + font-family: "Fira Sans", sans-serif; } h1 { - font: 1.6em "Fira Sans", sans-serif; - margin-bottom: 1rem; + font: + 1.6em "Fira Sans", + sans-serif; + margin-bottom: 1rem; } ``` ```js -const channel = new BroadcastChannel('example-channel'); -channel.addEventListener('message', (event) => { +const channel = new BroadcastChannel("example-channel"); +channel.addEventListener("message", (event) => { received.textContent = event.data; }); ``` diff --git a/files/zh-cn/web/api/broadcastchannel/messageerror_event/index.md b/files/zh-cn/web/api/broadcastchannel/messageerror_event/index.md index fda64cb88399b3..803c914d340b2d 100644 --- a/files/zh-cn/web/api/broadcastchannel/messageerror_event/index.md +++ b/files/zh-cn/web/api/broadcastchannel/messageerror_event/index.md @@ -1,5 +1,5 @@ --- -title: 'BroadcastChannel: messageerror event' +title: "BroadcastChannel: messageerror event" slug: Web/API/BroadcastChannel/messageerror_event --- @@ -39,13 +39,13 @@ slug: Web/API/BroadcastChannel/messageerror_event 以下代码使用 [`addEventListener`](/zh-CN/docs/Web/API/EventTarget/addEventListener) 来监听消息和错误: ```js -const channel = new BroadcastChannel('example-channel'); +const channel = new BroadcastChannel("example-channel"); -channel.addEventListener('message', (event) => { +channel.addEventListener("message", (event) => { received.textContent = event.data; }); -channel.addEventListener('messageerror', (event) => { +channel.addEventListener("messageerror", (event) => { console.error(event); }); ``` @@ -53,7 +53,7 @@ channel.addEventListener('messageerror', (event) => { 使用 [`onmessage`](/zh-CN/docs/Web/API/BroadcastChannel/onmessage) 和 [`onmessageerror`](/zh-CN/docs/Web/API/BroadcastChannel/onmessageerror) 事件处理程序来实现相同效果: ```js -const channel = new BroadcastChannel('example-channel'); +const channel = new BroadcastChannel("example-channel"); channel.onmessage = (event) => { received.textContent = event.data; diff --git a/files/zh-cn/web/api/broadcastchannel/name/index.md b/files/zh-cn/web/api/broadcastchannel/name/index.md index 37b5c805ffb136..1f0d80d6751b32 100644 --- a/files/zh-cn/web/api/broadcastchannel/name/index.md +++ b/files/zh-cn/web/api/broadcastchannel/name/index.md @@ -19,7 +19,7 @@ var str = channel.name; ```js // 连接到指定频道 -var bc = new BroadcastChannel('test_channel'); +var bc = new BroadcastChannel("test_channel"); // 其他操作 (如:postMessage, …) diff --git a/files/zh-cn/web/api/btoa/index.md b/files/zh-cn/web/api/btoa/index.md index 4a7a04f5841368..caff321204e899 100644 --- a/files/zh-cn/web/api/btoa/index.md +++ b/files/zh-cn/web/api/btoa/index.md @@ -12,7 +12,7 @@ slug: Web/API/btoa ## 语法 ```js -btoa(stringToEncode) +btoa(stringToEncode); ``` ### 参数 @@ -32,7 +32,7 @@ btoa(stringToEncode) ## 示例 ```js -const encodedData = btoa('Hello, world'); // 编码字符串 +const encodedData = btoa("Hello, world"); // 编码字符串 const decodedData = atob(encodedData); // 解码字符串 ``` @@ -46,10 +46,10 @@ const decodedData = atob(encodedData); // 解码字符串 const ok = "a"; console.log(ok.codePointAt(0).toString(16)); // 61:占用 < 1 byte -const notOK = "✓" +const notOK = "✓"; console.log(notOK.codePointAt(0).toString(16)); // 2713:占用 > 1 byte -console.log(btoa(ok)); // YQ== +console.log(btoa(ok)); // YQ== console.log(btoa(notOK)); // error ``` @@ -64,7 +64,7 @@ function toBinary(string) { codeUnits[i] = string.charCodeAt(i); } const charCodes = new Uint8Array(codeUnits.buffer); - let result = ''; + let result = ""; for (let i = 0; i < charCodes.byteLength; i++) { result += String.fromCharCode(charCodes[i]); } @@ -76,7 +76,7 @@ const myString = "☸☹☺☻☼☾☿"; const converted = toBinary(myString); const encoded = btoa(converted); -console.log(encoded); // OCY5JjomOyY8Jj4mPyY= +console.log(encoded); // OCY5JjomOyY8Jj4mPyY= ``` 如果你按上述的方法进行了编码,你当然需要一种方法来进行解码: @@ -88,7 +88,7 @@ function fromBinary(binary) { bytes[i] = binary.charCodeAt(i); } const charCodes = new Uint16Array(bytes.buffer); - let result = ''; + let result = ""; for (let i = 0; i < charCodes.length; i++) { result += String.fromCharCode(charCodes[i]); } @@ -97,7 +97,7 @@ function fromBinary(binary) { const decoded = atob(encoded); const original = fromBinary(decoded); -console.log(original); // ☸☹☺☻☼☾☿ +console.log(original); // ☸☹☺☻☼☾☿ ``` 参见 {{Glossary("Base64")}} 术语的 [Solution #1 – escaping the string before encoding it](/zh-CN/docs/Glossary/Base64#solution_1_–_javascripts_utf-16__base64) 示例中的 `utf8_to_b64` 和 `b64_to_utf8` 函数。 diff --git a/files/zh-cn/web/api/bytelengthqueuingstrategy/bytelengthqueuingstrategy/index.md b/files/zh-cn/web/api/bytelengthqueuingstrategy/bytelengthqueuingstrategy/index.md index 754c00c767d1e4..09c4534e34880e 100644 --- a/files/zh-cn/web/api/bytelengthqueuingstrategy/bytelengthqueuingstrategy/index.md +++ b/files/zh-cn/web/api/bytelengthqueuingstrategy/bytelengthqueuingstrategy/index.md @@ -10,7 +10,7 @@ slug: Web/API/ByteLengthQueuingStrategy/ByteLengthQueuingStrategy ## 语法 ```js -new ByteLengthQueuingStrategy(highWaterMark) +new ByteLengthQueuingStrategy(highWaterMark); ``` ### 参数 @@ -31,17 +31,20 @@ new ByteLengthQueuingStrategy(highWaterMark) ```js const queuingStrategy = new ByteLengthQueuingStrategy({ highWaterMark: 1 }); -const readableStream = new ReadableStream({ - start(controller) { - // … +const readableStream = new ReadableStream( + { + start(controller) { + // … + }, + pull(controller) { + // … + }, + cancel(err) { + console.log("stream error:", err); + }, }, - pull(controller) { - // … - }, - cancel(err) { - console.log("stream error:", err); - } -}, queuingStrategy); + queuingStrategy, +); const size = queuingStrategy.size(chunk); ``` diff --git a/files/zh-cn/web/api/bytelengthqueuingstrategy/highwatermark/index.md b/files/zh-cn/web/api/bytelengthqueuingstrategy/highwatermark/index.md index 1ba7d8abb3d80a..cf5da6dcba9331 100644 --- a/files/zh-cn/web/api/bytelengthqueuingstrategy/highwatermark/index.md +++ b/files/zh-cn/web/api/bytelengthqueuingstrategy/highwatermark/index.md @@ -32,7 +32,7 @@ const readableStream = new ReadableStream( console.log("stream error:", err); }, }, - queuingStrategy + queuingStrategy, ); const size = queuingStrategy.size(chunk); diff --git a/files/zh-cn/web/api/bytelengthqueuingstrategy/index.md b/files/zh-cn/web/api/bytelengthqueuingstrategy/index.md index 77f29262f94fd5..3a0c09237cf76d 100644 --- a/files/zh-cn/web/api/bytelengthqueuingstrategy/index.md +++ b/files/zh-cn/web/api/bytelengthqueuingstrategy/index.md @@ -27,17 +27,20 @@ slug: Web/API/ByteLengthQueuingStrategy ```js const queueingStrategy = new ByteLengthQueuingStrategy({ highWaterMark: 1 }); -const readableStream = new ReadableStream({ - start(controller) { - // … +const readableStream = new ReadableStream( + { + start(controller) { + // … + }, + pull(controller) { + // … + }, + cancel(err) { + console.log("stream error:", err); + }, }, - pull(controller) { - // … - }, - cancel(err) { - console.log("stream error:", err); - } -}, queueingStrategy); + queueingStrategy, +); const size = queueingStrategy.size(chunk); ``` diff --git a/files/zh-cn/web/api/bytelengthqueuingstrategy/size/index.md b/files/zh-cn/web/api/bytelengthqueuingstrategy/size/index.md index 2e37e0249f9e84..591dcc48011d89 100644 --- a/files/zh-cn/web/api/bytelengthqueuingstrategy/size/index.md +++ b/files/zh-cn/web/api/bytelengthqueuingstrategy/size/index.md @@ -27,17 +27,20 @@ size(chunk) ```js const queuingStrategy = new ByteLengthQueuingStrategy({ highWaterMark: 1 }); -const readableStream = new ReadableStream({ - start(controller) { - // … +const readableStream = new ReadableStream( + { + start(controller) { + // … + }, + pull(controller) { + // … + }, + cancel(err) { + console.log("stream error:", err); + }, }, - pull(controller) { - // … - }, - cancel(err) { - console.log("stream error:", err); - } -}, queuingStrategy); + queuingStrategy, +); const size = queueingStrategy.size(chunk); ``` diff --git a/files/zh-cn/web/api/cache/add/index.md b/files/zh-cn/web/api/cache/add/index.md index 46c3bfe7a7abaf..93be2cebf3052f 100644 --- a/files/zh-cn/web/api/cache/add/index.md +++ b/files/zh-cn/web/api/cache/add/index.md @@ -10,10 +10,10 @@ slug: Web/API/Cache/add ```js fetch(url).then(function (response) { if (!response.ok) { - throw new TypeError('bad response status'); + throw new TypeError("bad response status"); } return cache.put(url, response); -}) +}); ``` 对于更复杂的操作,您可以直接使用{{domxref("Cache.put","Cache.put()")}}这个 API。 @@ -25,7 +25,7 @@ fetch(url).then(function (response) { ## 语法 ```js -cache.add(request).then(function() { +cache.add(request).then(function () { //request has been added to the cache }); ``` @@ -50,11 +50,11 @@ void 返回值的 {{jsxref("Promise")}} 下面的代码块等待 {{domxref("InstallEvent")}} 事件触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理该应用程序的安装过程。包括调用 {{domxref("CacheStorage.open")}} 来创建一个新的缓存,然后使用 {{domxref("Cache.add")}} 来添加一个请求资源到该缓存。 ```js -this.addEventListener('install', function(event) { +this.addEventListener("install", function (event) { event.waitUntil( - caches.open('v1').then(function(cache) { - return cache.add('/sw-test/index.html'); - }) + caches.open("v1").then(function (cache) { + return cache.add("/sw-test/index.html"); + }), ); }); ``` diff --git a/files/zh-cn/web/api/cache/addall/index.md b/files/zh-cn/web/api/cache/addall/index.md index 7bf7097713fb20..891db25c026f63 100644 --- a/files/zh-cn/web/api/cache/addall/index.md +++ b/files/zh-cn/web/api/cache/addall/index.md @@ -41,22 +41,22 @@ A {{jsxref("Promise")}} that resolves with void. 此代码块等待一个 {{domxref("InstallEvent")}} 事件触发,然后运行 {{domxref("ExtendableEvent.waitUntil","waitUntil")}} 来处理该应用程序的安装进程。包括调用 {{domxref("CacheStorage.open")}} 创建一个新的 cache,然后使用 `addAll()` 添加一系列资源。 ```js -this.addEventListener('install', function(event) { +this.addEventListener("install", function (event) { event.waitUntil( - caches.open('v1').then(function(cache) { + caches.open("v1").then(function (cache) { return cache.addAll([ - '/sw-test/', - '/sw-test/index.html', - '/sw-test/style.css', - '/sw-test/app.js', - '/sw-test/image-list.js', - '/sw-test/star-wars-logo.jpg', - '/sw-test/gallery/', - '/sw-test/gallery/bountyHunters.jpg', - '/sw-test/gallery/myLittleVader.jpg', - '/sw-test/gallery/snowTroopers.jpg' + "/sw-test/", + "/sw-test/index.html", + "/sw-test/style.css", + "/sw-test/app.js", + "/sw-test/image-list.js", + "/sw-test/star-wars-logo.jpg", + "/sw-test/gallery/", + "/sw-test/gallery/bountyHunters.jpg", + "/sw-test/gallery/myLittleVader.jpg", + "/sw-test/gallery/snowTroopers.jpg", ]); - }) + }), ); }); ``` diff --git a/files/zh-cn/web/api/cache/delete/index.md b/files/zh-cn/web/api/cache/delete/index.md index 62835e1effa646..31744c9bde9262 100644 --- a/files/zh-cn/web/api/cache/delete/index.md +++ b/files/zh-cn/web/api/cache/delete/index.md @@ -35,11 +35,11 @@ cache.delete(request,{options}).then(function(true) { ## 示例 ```js -caches.open('v1').then(function(cache) { - cache.delete('/images/image.png').then(function(response) { +caches.open("v1").then(function (cache) { + cache.delete("/images/image.png").then(function (response) { someUIUpdateFunction(); }); -}) +}); ``` ## 规范 diff --git a/files/zh-cn/web/api/cache/index.md b/files/zh-cn/web/api/cache/index.md index c0b505991828a8..4c3e143e6d3a57 100644 --- a/files/zh-cn/web/api/cache/index.md +++ b/files/zh-cn/web/api/cache/index.md @@ -55,51 +55,52 @@ var CACHE_VERSION = 1; // 简写标识符映射到特定版本的缓存。 var CURRENT_CACHES = { - font: 'font-cache-v' + CACHE_VERSION + font: "font-cache-v" + CACHE_VERSION, }; -self.addEventListener('activate', function(event) { - var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) { +self.addEventListener("activate", function (event) { + var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function (key) { return CURRENT_CACHES[key]; }); // 在 promise 成功完成之前,活跃的 worker 不会被视作已激活。 event.waitUntil( - caches.keys().then(function(cacheNames) { + caches.keys().then(function (cacheNames) { return Promise.all( - cacheNames.map(function(cacheName) { + cacheNames.map(function (cacheName) { if (expectedCacheNames.indexOf(cacheName) == -1) { - console.log('Deleting out of date cache:', cacheName); + console.log("Deleting out of date cache:", cacheName); return caches.delete(cacheName); } - }) + }), ); - }) + }), ); }); -self.addEventListener('fetch', function(event) { - console.log('Handling fetch event for', event.request.url); +self.addEventListener("fetch", function (event) { + console.log("Handling fetch event for", event.request.url); event.respondWith( - // 打开以'font'开头的 Cache 对象。 - caches.open(CURRENT_CACHES['font']).then(function(cache) { - return cache.match(event.request).then(function(response) { - if (response) { - console.log(' Found response in cache:', response); - - return response; - } - }).catch(function(error) { - - // 处理 match() 或 fetch() 引起的异常。 - console.error(' Error in fetch handler:', error); + caches.open(CURRENT_CACHES["font"]).then(function (cache) { + return cache + .match(event.request) + .then(function (response) { + if (response) { + console.log(" Found response in cache:", response); + + return response; + } + }) + .catch(function (error) { + // 处理 match() 或 fetch() 引起的异常。 + console.error(" Error in fetch handler:", error); - throw error; - }); - }) + throw error; + }); + }), ); }); ``` diff --git a/files/zh-cn/web/api/cache/keys/index.md b/files/zh-cn/web/api/cache/keys/index.md index e990840b730268..e6252502f48e21 100644 --- a/files/zh-cn/web/api/cache/keys/index.md +++ b/files/zh-cn/web/api/cache/keys/index.md @@ -14,7 +14,7 @@ slug: Web/API/Cache/keys ## 语法 ```js -cache.keys(request,{options}).then(function(keys) { +cache.keys(request, { options }).then(function (keys) { //do something with your array of requests }); ``` @@ -39,13 +39,13 @@ cache.keys(request,{options}).then(function(keys) { ## 示例 ```js -caches.open('v1').then(function(cache) { - cache.keys().then(function(keys) { - keys.forEach(function(request, index, array) { +caches.open("v1").then(function (cache) { + cache.keys().then(function (keys) { + keys.forEach(function (request, index, array) { cache.delete(request); }); }); -}) +}); ``` ## 规范 diff --git a/files/zh-cn/web/api/cache/match/index.md b/files/zh-cn/web/api/cache/match/index.md index 9da638f3cae477..f0307312bd4a3d 100644 --- a/files/zh-cn/web/api/cache/match/index.md +++ b/files/zh-cn/web/api/cache/match/index.md @@ -10,7 +10,7 @@ slug: Web/API/Cache/match ## 语法 ```js -cache.match(request,{options}).then(function(response) { +cache.match(request, { options }).then(function (response) { //操作 response }); ``` @@ -43,18 +43,20 @@ cache.match(request,{options}).then(function(response) { 在这个例子中,我们决定只缓存通过 GET 取得的 HTML 文档。如果 `if()` 条件是 false,那么这个 fetch 处理器就不会处理这个请求。如果还有其他的 fetch 处理器被注册,它们将有机会调用 `event.respondWith()` 如果没有 fetch 处理器调用 `event.respondWith()` ,该请求就会像没有 service worker 介入一样由浏览器处理。如果 `fetch()` 返回了有效的 HTTP 响应,相应码是 4xx 或 5xx,那么`catch()` 就**不会**被调用。 ```js -self.addEventListener('fetch', function(event) { +self.addEventListener("fetch", function (event) { // 我们只想在用 GET 方法请求 HTML 文档时调用 event.respondWith()。 - if (event.request.method === 'GET' && - event.request.headers.get('accept').indexOf('text/html') !== -1) { - console.log('Handling fetch event for', event.request.url); + if ( + event.request.method === "GET" && + event.request.headers.get("accept").indexOf("text/html") !== -1 + ) { + console.log("Handling fetch event for", event.request.url); event.respondWith( - fetch(event.request).catch(function(e) { - console.error('Fetch failed; returning offline page instead.', e); - return caches.open(OFFLINE_CACHE).then(function(cache) { + fetch(event.request).catch(function (e) { + console.error("Fetch failed; returning offline page instead.", e); + return caches.open(OFFLINE_CACHE).then(function (cache) { return cache.match(OFFLINE_URL); }); - }) + }), ); } }); diff --git a/files/zh-cn/web/api/cache/matchall/index.md b/files/zh-cn/web/api/cache/matchall/index.md index a1f3fa19c581df..12dd622e5cf0e5 100644 --- a/files/zh-cn/web/api/cache/matchall/index.md +++ b/files/zh-cn/web/api/cache/matchall/index.md @@ -10,7 +10,7 @@ slug: Web/API/Cache/matchAll ## 语法 ```js -cache.matchAll(request,{options}).then(function(response) { +cache.matchAll(request, { options }).then(function (response) { //do something with the response array }); ``` @@ -37,13 +37,13 @@ cache.matchAll(request,{options}).then(function(response) { ## 示例 ```js -caches.open('v1').then(function(cache) { - cache.matchAll('/images/').then(function(response) { - response.forEach(function(element, index, array) { +caches.open("v1").then(function (cache) { + cache.matchAll("/images/").then(function (response) { + response.forEach(function (element, index, array) { cache.delete(element); }); }); -}) +}); ``` ## 规范 diff --git a/files/zh-cn/web/api/cache/put/index.md b/files/zh-cn/web/api/cache/put/index.md index a8ae1db1fef7a8..f9aa0d3b6fcacf 100644 --- a/files/zh-cn/web/api/cache/put/index.md +++ b/files/zh-cn/web/api/cache/put/index.md @@ -10,12 +10,12 @@ slug: Web/API/Cache/put 通常,你只想 {{domxref("GloblFetch.fetch","fetch()")}} 一个或多个请求,然后直接添加结果到 cache 中。这种情况下,最好使用 {{domxref("Cache.add","Cache.add()")}}/{{domxref("Cache.addAll","Cache.addAll()")}},因为它们是一个或者多个这些操作的便捷方法。 ```js -fetch(url).then(function(response) { +fetch(url).then(function (response) { if (!response.ok) { - throw new TypeError('Bad response status'); + throw new TypeError("Bad response status"); } return cache.put(url, response); -}) +}); ``` > **备注:** `put()` 将覆盖先前存储在匹配请求的 cache 中的任何键/值对。 @@ -55,17 +55,21 @@ This example is from the MDN [sw-test example](https://github.com/mdn/sw-test/) ```js var response; -var cachedResponse = caches.match(event.request).catch(function() { - return fetch(event.request); -}).then(function(r) { - response = r; - caches.open('v1').then(function(cache) { - cache.put(event.request, response); +var cachedResponse = caches + .match(event.request) + .catch(function () { + return fetch(event.request); + }) + .then(function (r) { + response = r; + caches.open("v1").then(function (cache) { + cache.put(event.request, response); + }); + return response.clone(); + }) + .catch(function () { + return caches.match("/sw-test/gallery/myLittleVader.jpg"); }); - return response.clone(); -}).catch(function() { - return caches.match('/sw-test/gallery/myLittleVader.jpg'); -}); ``` ## 规范 diff --git a/files/zh-cn/web/api/caches/index.md b/files/zh-cn/web/api/caches/index.md index e828074a306af3..bcbf6c280db89f 100644 --- a/files/zh-cn/web/api/caches/index.md +++ b/files/zh-cn/web/api/caches/index.md @@ -18,22 +18,22 @@ slug: Web/API/caches 以下示例展示了你在 [service worker](/zh-CN/docs/Web/API/Service_Worker_API) 上下文中应该如何运用 cache 对资源进行离线存储。 ```js -this.addEventListener('install', function(event) { +this.addEventListener("install", function (event) { event.waitUntil( - caches.open('v1').then(function(cache) { + caches.open("v1").then(function (cache) { return cache.addAll([ - '/sw-test/', - '/sw-test/index.html', - '/sw-test/style.css', - '/sw-test/app.js', - '/sw-test/image-list.js', - '/sw-test/star-wars-logo.jpg', - '/sw-test/gallery/', - '/sw-test/gallery/bountyHunters.jpg', - '/sw-test/gallery/myLittleVader.jpg', - '/sw-test/gallery/snowTroopers.jpg' + "/sw-test/", + "/sw-test/index.html", + "/sw-test/style.css", + "/sw-test/app.js", + "/sw-test/image-list.js", + "/sw-test/star-wars-logo.jpg", + "/sw-test/gallery/", + "/sw-test/gallery/bountyHunters.jpg", + "/sw-test/gallery/myLittleVader.jpg", + "/sw-test/gallery/snowTroopers.jpg", ]); - }) + }), ); }); ``` diff --git a/files/zh-cn/web/api/cachestorage/delete/index.md b/files/zh-cn/web/api/cachestorage/delete/index.md index ec3806134c85d3..f1cfc049ae5635 100644 --- a/files/zh-cn/web/api/cachestorage/delete/index.md +++ b/files/zh-cn/web/api/cachestorage/delete/index.md @@ -29,17 +29,19 @@ caches.delete(cacheName).then(function(true) { 在此代码片段中,我们等待一个 activate 事件,然后运行一个 {{domxref("ExtendableEvent.waitUntil","waitUntil()")}} 块,其在一个新的 service worker 被激活前清除所有旧的、未使用的 cache. 这里我们有一个白名单,其中包含我们想要保留的 cache 的 name. 我们使用 {{domxref("CacheStorage.keys")}} 返回 {{domxref("CacheStorage")}} 对象中 cache 的键,然后检查每个键值,以查看它是否在白名单中。如果没有,我们使用 `delete()` 删除它。 ```js -this.addEventListener('activate', function(event) { - var cacheWhitelist = ['v2']; +this.addEventListener("activate", function (event) { + var cacheWhitelist = ["v2"]; event.waitUntil( - caches.keys().then(function(keyList) { - return Promise.all(keyList.map(function(key) { - if (cacheWhitelist.indexOf(key) === -1) { - return caches.delete(key); - } - })); - }) + caches.keys().then(function (keyList) { + return Promise.all( + keyList.map(function (key) { + if (cacheWhitelist.indexOf(key) === -1) { + return caches.delete(key); + } + }), + ); + }), ); }); ``` diff --git a/files/zh-cn/web/api/cachestorage/has/index.md b/files/zh-cn/web/api/cachestorage/has/index.md index 86c63f1e1d4bc5..78ce9e3ff435cb 100644 --- a/files/zh-cn/web/api/cachestorage/has/index.md +++ b/files/zh-cn/web/api/cachestorage/has/index.md @@ -29,17 +29,20 @@ caches.has(cacheName).then(function(boolean) { 在下面的例子中首先检测是否有名为 v1 的缓存存在,如果存在我们会向其添加内容,,如果不存在我们会做些对应的初始化动作。 ```js -caches.has('v1').then(function(hasCache) { - if (!hasCache) { - someCacheSetupfunction(); - } else { - caches.open('v1').then(function(cache) { - return cache.addAll(myAssets); - }); - } -}).catch(function() { - // 处理异常 -}); +caches + .has("v1") + .then(function (hasCache) { + if (!hasCache) { + someCacheSetupfunction(); + } else { + caches.open("v1").then(function (cache) { + return cache.addAll(myAssets); + }); + } + }) + .catch(function () { + // 处理异常 + }); ``` ## 规范 diff --git a/files/zh-cn/web/api/cachestorage/index.md b/files/zh-cn/web/api/cachestorage/index.md index 1e7991c820b6d5..94952485646650 100644 --- a/files/zh-cn/web/api/cachestorage/index.md +++ b/files/zh-cn/web/api/cachestorage/index.md @@ -41,37 +41,43 @@ slug: Web/API/CacheStorage 最后,使用 {{domxref("FetchEvent.respondWith")}} 返回自定义响应最终等于的内容。 ```js -this.addEventListener('install', function(event) { +this.addEventListener("install", function (event) { event.waitUntil( - caches.open('v1').then(function(cache) { + caches.open("v1").then(function (cache) { return cache.addAll([ - '/sw-test/', - '/sw-test/index.html', - '/sw-test/style.css', - '/sw-test/app.js', - '/sw-test/image-list.js', - '/sw-test/star-wars-logo.jpg', - '/sw-test/gallery/bountyHunters.jpg', - '/sw-test/gallery/myLittleVader.jpg', - '/sw-test/gallery/snowTroopers.jpg' + "/sw-test/", + "/sw-test/index.html", + "/sw-test/style.css", + "/sw-test/app.js", + "/sw-test/image-list.js", + "/sw-test/star-wars-logo.jpg", + "/sw-test/gallery/bountyHunters.jpg", + "/sw-test/gallery/myLittleVader.jpg", + "/sw-test/gallery/snowTroopers.jpg", ]); - }) + }), ); }); -this.addEventListener('fetch', function(event) { +this.addEventListener("fetch", function (event) { var response; - event.respondWith(caches.match(event.request).catch(function() { - return fetch(event.request); - }).then(function(r) { - response = r; - caches.open('v1').then(function(cache) { - cache.put(event.request, response); - }); - return response.clone(); - }).catch(function() { - return caches.match('/sw-test/gallery/myLittleVader.jpg'); - })); + event.respondWith( + caches + .match(event.request) + .catch(function () { + return fetch(event.request); + }) + .then(function (r) { + response = r; + caches.open("v1").then(function (cache) { + cache.put(event.request, response); + }); + return response.clone(); + }) + .catch(function () { + return caches.match("/sw-test/gallery/myLittleVader.jpg"); + }), + ); }); ``` diff --git a/files/zh-cn/web/api/cachestorage/match/index.md b/files/zh-cn/web/api/cachestorage/match/index.md index 8ad06f8913505a..35d26a094f3da4 100644 --- a/files/zh-cn/web/api/cachestorage/match/index.md +++ b/files/zh-cn/web/api/cachestorage/match/index.md @@ -45,16 +45,22 @@ caches.match(request, options).then(function(response) { 3. 如果此操作失败(例如,因为网络已关闭),则返回备用响应。 ```js -caches.match(event.request).then(function(response) { - return response || fetch(event.request).then(function(r) { - caches.open('v1').then(function(cache) { - cache.put(event.request, r); - }); - return r.clone(); +caches + .match(event.request) + .then(function (response) { + return ( + response || + fetch(event.request).then(function (r) { + caches.open("v1").then(function (cache) { + cache.put(event.request, r); + }); + return r.clone(); + }) + ); + }) + .catch(function () { + return caches.match("/sw-test/gallery/myLittleVader.jpg"); }); -}).catch(function() { - return caches.match('/sw-test/gallery/myLittleVader.jpg'); -}); ``` ## 规范 diff --git a/files/zh-cn/web/api/cachestorage/open/index.md b/files/zh-cn/web/api/cachestorage/open/index.md index 9478d8c850e6b2..f84276fb83780a 100644 --- a/files/zh-cn/web/api/cachestorage/open/index.md +++ b/files/zh-cn/web/api/cachestorage/open/index.md @@ -15,7 +15,7 @@ slug: Web/API/CacheStorage/open // "caches" is a global read-only variable, which is an instance of CacheStorage, // For more info, refer to: https://developer.mozilla.org/zh-CN/docs/Web/API/caches -caches.open(cacheName).then(function(cache) { +caches.open(cacheName).then(function (cache) { // Do something with your cache }); ``` @@ -38,16 +38,20 @@ caches.open(cacheName).then(function(cache) { 3. 如果此操作失败(例如,因为网络已关闭),则返回备用响应。 ```js -var cachedResponse = caches.match(event.request).catch(function() { - return fetch(event.request); -}).then(function(response) { - caches.open('v1').then(function(cache) { - cache.put(event.request, response); +var cachedResponse = caches + .match(event.request) + .catch(function () { + return fetch(event.request); + }) + .then(function (response) { + caches.open("v1").then(function (cache) { + cache.put(event.request, response); + }); + return response.clone(); + }) + .catch(function () { + return caches.match("/sw-test/gallery/myLittleVader.jpg"); }); - return response.clone(); -}).catch(function() { - return caches.match('/sw-test/gallery/myLittleVader.jpg'); -}); ``` ## 规范 diff --git a/files/zh-cn/web/api/canvas_api/index.md b/files/zh-cn/web/api/canvas_api/index.md index c849ed5c9ed3a6..4e4cf47d245df1 100644 --- a/files/zh-cn/web/api/canvas_api/index.md +++ b/files/zh-cn/web/api/canvas_api/index.md @@ -26,10 +26,10 @@ Canvas API 主要聚焦于 2D 图形。而同样使用``元素的 [WebGL 由 {{domxref("CanvasRenderingContext2D")}} 接口完成实际的绘制。{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} 属性让长方形变成绿色。{{domxref("CanvasRenderingContext2D.fillRect()", "fillRect()")}} 方法将它的左上角放在 (10, 10),把它的大小设置成宽 150 高 100。 ```js -const canvas = document.getElementById('canvas'); -const ctx = canvas.getContext('2d'); +const canvas = document.getElementById("canvas"); +const ctx = canvas.getContext("2d"); -ctx.fillStyle = 'green'; +ctx.fillStyle = "green"; ctx.fillRect(10, 10, 150, 100); ``` diff --git a/files/zh-cn/web/api/canvas_api/manipulating_video_using_canvas/index.md b/files/zh-cn/web/api/canvas_api/manipulating_video_using_canvas/index.md index 7321ac4949be1a..b0a76ad5b1ac38 100644 --- a/files/zh-cn/web/api/canvas_api/manipulating_video_using_canvas/index.md +++ b/files/zh-cn/web/api/canvas_api/manipulating_video_using_canvas/index.md @@ -14,14 +14,13 @@ slug: Web/API/Canvas_API/Manipulating_video_using_canvas 以下是用于渲染该内容的 XHTML 文档。 ```html - + @@ -40,11 +39,11 @@ slug: Web/API/Canvas_API/Manipulating_video_using_canvas
-
- - + +
@@ -114,21 +113,20 @@ slug: Web/API/Canvas_API/Manipulating_video_using_canvas 下方展示的 `computeFrame()` 方法负责真实获取一帧数据并执行色度键控效果。 ```js - processor.computeFrame = function computeFrame() { - this.ctx1.drawImage(this.video, 0, 0, this.width, this.height); - let frame = this.ctx1.getImageData(0, 0, this.width, this.height); - let l = frame.data.length / 4; - - for (let i = 0; i < l; i++) { - let r = frame.data[i * 4 + 0]; - let g = frame.data[i * 4 + 1]; - let b = frame.data[i * 4 + 2]; - if (g > 100 && r > 100 && b < 43) - frame.data[i * 4 + 3] = 0; - } - this.ctx2.putImageData(frame, 0, 0); - return; +processor.computeFrame = function computeFrame() { + this.ctx1.drawImage(this.video, 0, 0, this.width, this.height); + let frame = this.ctx1.getImageData(0, 0, this.width, this.height); + let l = frame.data.length / 4; + + for (let i = 0; i < l; i++) { + let r = frame.data[i * 4 + 0]; + let g = frame.data[i * 4 + 1]; + let b = frame.data[i * 4 + 2]; + if (g > 100 && r > 100 && b < 43) frame.data[i * 4 + 3] = 0; } + this.ctx2.putImageData(frame, 0, 0); + return; +}; ``` 当这段例行程序被调用时,video 元素正显示最新的视频数据帧,就像这样: diff --git a/files/zh-cn/web/api/canvas_api/tutorial/advanced_animations/index.md b/files/zh-cn/web/api/canvas_api/tutorial/advanced_animations/index.md index 2778321dee5720..073a36292f2172 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/advanced_animations/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/advanced_animations/index.md @@ -18,21 +18,21 @@ slug: Web/API/Canvas_API/Tutorial/Advanced_animations 跟平常一样,我们需要先画一个 context(画布场景)。为了画出这个球,我们又会创建一个包含一些相关属性以及 `draw()` 函数的 `ball` 对象,来完成绘制。 ```js -var canvas = document.getElementById('canvas'); -var ctx = canvas.getContext('2d'); +var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); var ball = { x: 100, y: 100, radius: 25, - color: 'blue', - draw: function() { + color: "blue", + draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); - } + }, }; ball.draw(); @@ -45,8 +45,8 @@ ball.draw(); 现在我们有了一个小球,正准备添加一些基本动画,正如我们[上一章](/zh-CN/docs/Web/API/Canvas_API/Tutorial/Basic_animations)所学的。又是这样,{{domxref("window.requestAnimationFrame()")}} 再一次帮助我们控制动画。小球依旧依靠添加速率矢量进行移动。在每一帧里面,我们依旧用{{domxref("CanvasRenderingContext2D.clearRect", "clear", "", 1)}} 清理掉之前帧里旧的圆形。 ```js -var canvas = document.getElementById('canvas'); -var ctx = canvas.getContext('2d'); +var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); var raf; var ball = { @@ -55,29 +55,29 @@ var ball = { vx: 5, vy: 2, radius: 25, - color: 'blue', - draw: function() { + color: "blue", + draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); - } + }, }; function draw() { - ctx.clearRect(0,0, canvas.width, canvas.height); + ctx.clearRect(0, 0, canvas.width, canvas.height); ball.draw(); ball.x += ball.vx; ball.y += ball.vy; raf = window.requestAnimationFrame(draw); } -canvas.addEventListener('mouseover', function(e){ +canvas.addEventListener("mouseover", function (e) { raf = window.requestAnimationFrame(draw); }); -canvas.addEventListener('mouseout', function(e){ +canvas.addEventListener("mouseout", function (e) { window.cancelAnimationFrame(raf); }); @@ -168,8 +168,8 @@ ball.draw(); 为了让动作更真实,你可以像这样处理速度,例如: ```js -ball.vy *= .99; -ball.vy += .25; +ball.vy *= 0.99; +ball.vy += 0.25; ``` 这会逐帧减少垂直方向的速度,所以小球最终将只会在地板上弹跳。 @@ -243,8 +243,8 @@ ball.draw(); 现在,我们使用的是 {{domxref("CanvasRenderingContext2D.clearRect", "clearRect")}} 函数帮我们清除前一帧动画。若用一个半透明的 {{domxref("CanvasRenderingContext2D.fillRect", "fillRect")}} 函数取代之,就可轻松制作长尾效果。 ```js -ctx.fillStyle = 'rgba(255,255,255,0.3)'; -ctx.fillRect(0,0,canvas.width,canvas.height); +ctx.fillStyle = "rgba(255,255,255,0.3)"; +ctx.fillRect(0, 0, canvas.width, canvas.height); ``` ### 第三个示例 @@ -321,8 +321,8 @@ ball.draw(); ``` ```js -var canvas = document.getElementById('canvas'); -var ctx = canvas.getContext('2d'); +var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); var raf; var running = false; @@ -332,19 +332,19 @@ var ball = { vx: 5, vy: 1, radius: 25, - color: 'blue', - draw: function() { + color: "blue", + draw: function () { ctx.beginPath(); ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true); ctx.closePath(); ctx.fillStyle = this.color; ctx.fill(); - } + }, }; function clear() { - ctx.fillStyle = 'rgba(255,255,255,0.3)'; - ctx.fillRect(0,0,canvas.width,canvas.height); + ctx.fillStyle = "rgba(255,255,255,0.3)"; + ctx.fillRect(0, 0, canvas.width, canvas.height); } function draw() { @@ -363,7 +363,7 @@ function draw() { raf = window.requestAnimationFrame(draw); } -canvas.addEventListener('mousemove', function(e){ +canvas.addEventListener("mousemove", function (e) { if (!running) { clear(); ball.x = e.offsetX; @@ -372,14 +372,14 @@ canvas.addEventListener('mousemove', function(e){ } }); -canvas.addEventListener('click',function(e){ +canvas.addEventListener("click", function (e) { if (!running) { raf = window.requestAnimationFrame(draw); running = true; } }); -canvas.addEventListener('mouseout', function(e){ +canvas.addEventListener("mouseout", function (e) { window.cancelAnimationFrame(raf); running = false; }); diff --git a/files/zh-cn/web/api/canvas_api/tutorial/applying_styles_and_colors/index.md b/files/zh-cn/web/api/canvas_api/tutorial/applying_styles_and_colors/index.md index 3a8efb3ad0ff0a..2410ceadcf857e 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/applying_styles_and_colors/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/applying_styles_and_colors/index.md @@ -34,12 +34,16 @@ ctx.fillStyle = "rgba(255,165,0,1)"; ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - for (var i=0;i<6;i++){ - for (var j=0;j<6;j++){ - ctx.fillStyle = 'rgb(' + Math.floor(255-42.5*i) + ',' + - Math.floor(255-42.5*j) + ',0)'; - ctx.fillRect(j*25,i*25,25,25); + var ctx = document.getElementById("canvas").getContext("2d"); + for (var i = 0; i < 6; i++) { + for (var j = 0; j < 6; j++) { + ctx.fillStyle = + "rgb(" + + Math.floor(255 - 42.5 * i) + + "," + + Math.floor(255 - 42.5 * j) + + ",0)"; + ctx.fillRect(j * 25, i * 25, 25, 25); } } } @@ -62,18 +66,22 @@ draw(); 这个示例与上面的有点类似,但这次用到的是 `strokeStyle` 属性,画的不是方格,而是用 `arc` 方法来画圆。 ```js - function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - for (var i=0;i<6;i++){ - for (var j=0;j<6;j++){ - ctx.strokeStyle = 'rgb(0,' + Math.floor(255-42.5*i) + ',' + - Math.floor(255-42.5*j) + ')'; - ctx.beginPath(); - ctx.arc(12.5+j*25,12.5+i*25,10,0,Math.PI*2,true); - ctx.stroke(); - } +function draw() { + var ctx = document.getElementById("canvas").getContext("2d"); + for (var i = 0; i < 6; i++) { + for (var j = 0; j < 6; j++) { + ctx.strokeStyle = + "rgb(0," + + Math.floor(255 - 42.5 * i) + + "," + + Math.floor(255 - 42.5 * j) + + ")"; + ctx.beginPath(); + ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true); + ctx.stroke(); } } +} ``` ```html hidden @@ -113,26 +121,26 @@ ctx.fillStyle = "rgba(255,0,0,0.5)"; ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); // 画背景 - ctx.fillStyle = '#FD0'; - ctx.fillRect(0,0,75,75); - ctx.fillStyle = '#6C0'; - ctx.fillRect(75,0,75,75); - ctx.fillStyle = '#09F'; - ctx.fillRect(0,75,75,75); - ctx.fillStyle = '#F30'; - ctx.fillRect(75,75,75,75); - ctx.fillStyle = '#FFF'; + ctx.fillStyle = "#FD0"; + ctx.fillRect(0, 0, 75, 75); + ctx.fillStyle = "#6C0"; + ctx.fillRect(75, 0, 75, 75); + ctx.fillStyle = "#09F"; + ctx.fillRect(0, 75, 75, 75); + ctx.fillStyle = "#F30"; + ctx.fillRect(75, 75, 75, 75); + ctx.fillStyle = "#FFF"; // 设置透明度值 ctx.globalAlpha = 0.2; // 画半透明圆 - for (var i=0;i<7;i++){ - ctx.beginPath(); - ctx.arc(75,75,10+10*i,0,Math.PI*2,true); - ctx.fill(); + for (var i = 0; i < 7; i++) { + ctx.beginPath(); + ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI * 2, true); + ctx.fill(); } } ``` @@ -153,23 +161,23 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); // 画背景 - ctx.fillStyle = 'rgb(255,221,0)'; - ctx.fillRect(0,0,150,37.5); - ctx.fillStyle = 'rgb(102,204,0)'; - ctx.fillRect(0,37.5,150,37.5); - ctx.fillStyle = 'rgb(0,153,255)'; - ctx.fillRect(0,75,150,37.5); - ctx.fillStyle = 'rgb(255,51,0)'; - ctx.fillRect(0,112.5,150,37.5); + ctx.fillStyle = "rgb(255,221,0)"; + ctx.fillRect(0, 0, 150, 37.5); + ctx.fillStyle = "rgb(102,204,0)"; + ctx.fillRect(0, 37.5, 150, 37.5); + ctx.fillStyle = "rgb(0,153,255)"; + ctx.fillRect(0, 75, 150, 37.5); + ctx.fillStyle = "rgb(255,51,0)"; + ctx.fillRect(0, 112.5, 150, 37.5); // 画半透明矩形 - for (var i=0;i<10;i++){ - ctx.fillStyle = 'rgba(255,255,255,'+(i+1)/10+')'; - for (var j=0;j<4;j++){ - ctx.fillRect(5+i*14,5+j*37.5,14,27.5) + for (var i = 0; i < 10; i++) { + ctx.fillStyle = "rgba(255,255,255," + (i + 1) / 10 + ")"; + for (var j = 0; j < 4; j++) { + ctx.fillRect(5 + i * 14, 5 + j * 37.5, 14, 27.5); } } } @@ -216,12 +224,12 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - for (var i = 0; i < 10; i++){ - ctx.lineWidth = 1+i; + var ctx = document.getElementById("canvas").getContext("2d"); + for (var i = 0; i < 10; i++) { + ctx.lineWidth = 1 + i; ctx.beginPath(); - ctx.moveTo(5+i*14,5); - ctx.lineTo(5+i*14,140); + ctx.moveTo(5 + i * 14, 5); + ctx.lineTo(5 + i * 14, 140); ctx.stroke(); } } @@ -263,26 +271,26 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - var lineCap = ['butt','round','square']; + var ctx = document.getElementById("canvas").getContext("2d"); + var lineCap = ["butt", "round", "square"]; // 创建路径 - ctx.strokeStyle = '#09f'; + ctx.strokeStyle = "#09f"; ctx.beginPath(); - ctx.moveTo(10,10); - ctx.lineTo(140,10); - ctx.moveTo(10,140); - ctx.lineTo(140,140); + ctx.moveTo(10, 10); + ctx.lineTo(140, 10); + ctx.moveTo(10, 140); + ctx.lineTo(140, 140); ctx.stroke(); // 画线条 - ctx.strokeStyle = 'black'; - for (var i=0;i - 在输入框中输入miterLimit的值,并点击重绘按钮查看效果。

+ + 在输入框中输入miterLimit的值,并点击重绘按钮查看效果。

- - + +
@@ -401,7 +410,9 @@ function draw() { ``` ```js hidden -document.getElementById('miterLimit').value = document.getElementById('canvas').getContext('2d').miterLimit; +document.getElementById("miterLimit").value = document + .getElementById("canvas") + .getContext("2d").miterLimit; draw(); ``` @@ -418,14 +429,14 @@ draw(); ``` ```js -var ctx = document.getElementById('canvas').getContext('2d'); +var ctx = document.getElementById("canvas").getContext("2d"); var offset = 0; function draw() { - ctx.clearRect(0,0, canvas.width, canvas.height); + ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.setLineDash([4, 2]); ctx.lineDashOffset = -offset; - ctx.strokeRect(10,10, 100, 100); + ctx.strokeRect(10, 10, 100, 100); } function march() { @@ -452,8 +463,8 @@ march(); - : createRadialGradient 方法接受 6 个参数,前三个定义一个以 (x1,y1) 为原点,半径为 r1 的圆,后三个参数则定义另一个以 (x2,y2) 为原点,半径为 r2 的圆。 ```js -var lineargradient = ctx.createLinearGradient(0,0,150,150); -var radialgradient = ctx.createRadialGradient(75,75,0,75,75,100); +var lineargradient = ctx.createLinearGradient(0, 0, 150, 150); +var radialgradient = ctx.createRadialGradient(75, 75, 0, 75, 75, 100); ``` 创建出 `canvasGradient` 对象后,我们就可以用 `addColorStop` 方法给它上色了。 @@ -464,9 +475,9 @@ var radialgradient = ctx.createRadialGradient(75,75,0,75,75,100); 你可以根据需要添加任意多个色标(color stops)。下面是最简单的线性黑白渐变的例子。 ```js -var lineargradient = ctx.createLinearGradient(0,0,150,150); -lineargradient.addColorStop(0,'white'); -lineargradient.addColorStop(1,'black'); +var lineargradient = ctx.createLinearGradient(0, 0, 150, 150); +lineargradient.addColorStop(0, "white"); +lineargradient.addColorStop(1, "black"); ``` #### `createLinearGradient` 的例子 @@ -481,27 +492,26 @@ lineargradient.addColorStop(1,'black'); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); // Create gradients - var lingrad = ctx.createLinearGradient(0,0,0,150); - lingrad.addColorStop(0, '#00ABEB'); - lingrad.addColorStop(0.5, '#fff'); - lingrad.addColorStop(0.5, '#26C000'); - lingrad.addColorStop(1, '#fff'); + var lingrad = ctx.createLinearGradient(0, 0, 0, 150); + lingrad.addColorStop(0, "#00ABEB"); + lingrad.addColorStop(0.5, "#fff"); + lingrad.addColorStop(0.5, "#26C000"); + lingrad.addColorStop(1, "#fff"); - var lingrad2 = ctx.createLinearGradient(0,50,0,95); - lingrad2.addColorStop(0.5, '#000'); - lingrad2.addColorStop(1, 'rgba(0,0,0,0)'); + var lingrad2 = ctx.createLinearGradient(0, 50, 0, 95); + lingrad2.addColorStop(0.5, "#000"); + lingrad2.addColorStop(1, "rgba(0,0,0,0)"); // assign gradients to fill and stroke styles ctx.fillStyle = lingrad; ctx.strokeStyle = lingrad2; // draw shapes - ctx.fillRect(10,10,130,130); - ctx.strokeRect(50,50,50,50); - + ctx.fillRect(10, 10, 130, 130); + ctx.strokeRect(50, 50, 50, 50); } ``` @@ -521,38 +531,38 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); // 创建渐变 - var radgrad = ctx.createRadialGradient(45,45,10,52,50,30); - radgrad.addColorStop(0, '#A7D30C'); - radgrad.addColorStop(0.9, '#019F62'); - radgrad.addColorStop(1, 'rgba(1,159,98,0)'); - - var radgrad2 = ctx.createRadialGradient(105,105,20,112,120,50); - radgrad2.addColorStop(0, '#FF5F98'); - radgrad2.addColorStop(0.75, '#FF0188'); - radgrad2.addColorStop(1, 'rgba(255,1,136,0)'); - - var radgrad3 = ctx.createRadialGradient(95,15,15,102,20,40); - radgrad3.addColorStop(0, '#00C9FF'); - radgrad3.addColorStop(0.8, '#00B5E2'); - radgrad3.addColorStop(1, 'rgba(0,201,255,0)'); - - var radgrad4 = ctx.createRadialGradient(0,150,50,0,140,90); - radgrad4.addColorStop(0, '#F4F201'); - radgrad4.addColorStop(0.8, '#E4C700'); - radgrad4.addColorStop(1, 'rgba(228,199,0,0)'); + var radgrad = ctx.createRadialGradient(45, 45, 10, 52, 50, 30); + radgrad.addColorStop(0, "#A7D30C"); + radgrad.addColorStop(0.9, "#019F62"); + radgrad.addColorStop(1, "rgba(1,159,98,0)"); + + var radgrad2 = ctx.createRadialGradient(105, 105, 20, 112, 120, 50); + radgrad2.addColorStop(0, "#FF5F98"); + radgrad2.addColorStop(0.75, "#FF0188"); + radgrad2.addColorStop(1, "rgba(255,1,136,0)"); + + var radgrad3 = ctx.createRadialGradient(95, 15, 15, 102, 20, 40); + radgrad3.addColorStop(0, "#00C9FF"); + radgrad3.addColorStop(0.8, "#00B5E2"); + radgrad3.addColorStop(1, "rgba(0,201,255,0)"); + + var radgrad4 = ctx.createRadialGradient(0, 150, 50, 0, 140, 90); + radgrad4.addColorStop(0, "#F4F201"); + radgrad4.addColorStop(0.8, "#E4C700"); + radgrad4.addColorStop(1, "rgba(228,199,0,0)"); // 画图形 ctx.fillStyle = radgrad4; - ctx.fillRect(0,0,150,150); + ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad3; - ctx.fillRect(0,0,150,150); + ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad2; - ctx.fillRect(0,0,150,150); + ctx.fillRect(0, 0, 150, 150); ctx.fillStyle = radgrad; - ctx.fillRect(0,0,150,150); + ctx.fillRect(0, 0, 150, 150); } ``` @@ -583,8 +593,8 @@ draw(); ```js var img = new Image(); -img.src = 'someimage.png'; -var ptrn = ctx.createPattern(img,'repeat'); +img.src = "someimage.png"; +var ptrn = ctx.createPattern(img, "repeat"); ``` > **备注:** 与 drawImage 有点不同,你需要确认 image 对象已经装载完毕,否则图案可能效果不对的。 @@ -595,19 +605,17 @@ var ptrn = ctx.createPattern(img,'repeat'); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); // 创建新 image 对象,用作图案 var img = new Image(); - img.src = 'canvas_createpattern.png'; - img.onload = function() { - + img.src = "canvas_createpattern.png"; + img.onload = function () { // 创建图案 - var ptrn = ctx.createPattern(img, 'repeat'); + var ptrn = ctx.createPattern(img, "repeat"); ctx.fillStyle = ptrn; ctx.fillRect(0, 0, 150, 150); - - } + }; } ``` @@ -640,7 +648,7 @@ The result looks like this: ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); ctx.shadowOffsetX = 2; ctx.shadowOffsetY = 2; @@ -680,10 +688,10 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); ctx.beginPath(); - ctx.arc(50, 50, 30, 0, Math.PI*2, true); - ctx.arc(50, 50, 15, 0, Math.PI*2, true); + ctx.arc(50, 50, 30, 0, Math.PI * 2, true); + ctx.arc(50, 50, 15, 0, Math.PI * 2, true); ctx.fill("evenodd"); } ``` diff --git a/files/zh-cn/web/api/canvas_api/tutorial/basic_animations/index.md b/files/zh-cn/web/api/canvas_api/tutorial/basic_animations/index.md index 53bb4cf4089ac1..073834bd77b6f1 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/basic_animations/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/basic_animations/index.md @@ -14,13 +14,13 @@ slug: Web/API/Canvas_API/Tutorial/Basic_animations 你可以通过以下的步骤来画出一帧: 1. **清空 canvas** - 除非接下来要画的内容会完全充满 canvas(例如背景图),否则你需要清空所有。最简单的做法就是用 `clearRect` 方法。 + 除非接下来要画的内容会完全充满 canvas(例如背景图),否则你需要清空所有。最简单的做法就是用 `clearRect` 方法。 2. **保存 canvas 状态** - 如果你要改变一些会改变 canvas 状态的设置(样式,变形之类的),又要在每画一帧之时都是原始状态的话,你需要先保存一下。 + 如果你要改变一些会改变 canvas 状态的设置(样式,变形之类的),又要在每画一帧之时都是原始状态的话,你需要先保存一下。 3. **绘制动画图形(animated shapes)** - 这一步才是重绘动画帧。 + 这一步才是重绘动画帧。 4. **恢复 canvas 状态** - 如果已经保存了 canvas 的状态,可以先恢复它,然后重绘下一帧。 + 如果已经保存了 canvas 的状态,可以先恢复它,然后重绘下一帧。 ## 操控动画 @@ -51,45 +51,51 @@ slug: Web/API/Canvas_API/Tutorial/Basic_animations var sun = new Image(); var moon = new Image(); var earth = new Image(); -function init(){ - sun.src = 'canvas_sun.png'; - moon.src = 'canvas_moon.png'; - earth.src = 'canvas_earth.png'; +function init() { + sun.src = "canvas_sun.png"; + moon.src = "canvas_moon.png"; + earth.src = "canvas_earth.png"; window.requestAnimationFrame(draw); } function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); - ctx.globalCompositeOperation = 'destination-over'; - ctx.clearRect(0,0,300,300); // clear canvas + ctx.globalCompositeOperation = "destination-over"; + ctx.clearRect(0, 0, 300, 300); // clear canvas - ctx.fillStyle = 'rgba(0,0,0,0.4)'; - ctx.strokeStyle = 'rgba(0,153,255,0.4)'; + ctx.fillStyle = "rgba(0,0,0,0.4)"; + ctx.strokeStyle = "rgba(0,153,255,0.4)"; ctx.save(); - ctx.translate(150,150); + ctx.translate(150, 150); // Earth var time = new Date(); - ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() ); - ctx.translate(105,0); - ctx.fillRect(0,-12,50,24); // Shadow - ctx.drawImage(earth,-12,-12); + ctx.rotate( + ((2 * Math.PI) / 60) * time.getSeconds() + + ((2 * Math.PI) / 60000) * time.getMilliseconds(), + ); + ctx.translate(105, 0); + ctx.fillRect(0, -12, 50, 24); // Shadow + ctx.drawImage(earth, -12, -12); // Moon ctx.save(); - ctx.rotate( ((2*Math.PI)/6)*time.getSeconds() + ((2*Math.PI)/6000)*time.getMilliseconds() ); - ctx.translate(0,28.5); - ctx.drawImage(moon,-3.5,-3.5); + ctx.rotate( + ((2 * Math.PI) / 6) * time.getSeconds() + + ((2 * Math.PI) / 6000) * time.getMilliseconds(), + ); + ctx.translate(0, 28.5); + ctx.drawImage(moon, -3.5, -3.5); ctx.restore(); ctx.restore(); ctx.beginPath(); - ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit + ctx.arc(150, 150, 105, 0, Math.PI * 2, false); // Earth orbit ctx.stroke(); - ctx.drawImage(sun,0,0,300,300); + ctx.drawImage(sun, 0, 0, 300, 300); window.requestAnimationFrame(draw); } @@ -108,14 +114,14 @@ init(); 这个例子实现一个动态时钟,可以显示当前时间。 ```js -function clock(){ +function clock() { var now = new Date(); - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); ctx.save(); - ctx.clearRect(0,0,150,150); - ctx.translate(75,75); - ctx.scale(0.4,0.4); - ctx.rotate(-Math.PI/2); + ctx.clearRect(0, 0, 150, 150); + ctx.translate(75, 75); + ctx.scale(0.4, 0.4); + ctx.rotate(-Math.PI / 2); ctx.strokeStyle = "black"; ctx.fillStyle = "white"; ctx.lineWidth = 8; @@ -123,11 +129,11 @@ function clock(){ // Hour marks ctx.save(); - for (var i=0;i<12;i++){ + for (var i = 0; i < 12; i++) { ctx.beginPath(); - ctx.rotate(Math.PI/6); - ctx.moveTo(100,0); - ctx.lineTo(120,0); + ctx.rotate(Math.PI / 6); + ctx.moveTo(100, 0); + ctx.lineTo(120, 0); ctx.stroke(); } ctx.restore(); @@ -135,69 +141,71 @@ function clock(){ // Minute marks ctx.save(); ctx.lineWidth = 5; - for (i=0;i<60;i++){ - if (i%5!=0) { + for (i = 0; i < 60; i++) { + if (i % 5 != 0) { ctx.beginPath(); - ctx.moveTo(117,0); - ctx.lineTo(120,0); + ctx.moveTo(117, 0); + ctx.lineTo(120, 0); ctx.stroke(); } - ctx.rotate(Math.PI/30); + ctx.rotate(Math.PI / 30); } ctx.restore(); var sec = now.getSeconds(); var min = now.getMinutes(); - var hr = now.getHours(); - hr = hr>=12 ? hr-12 : hr; + var hr = now.getHours(); + hr = hr >= 12 ? hr - 12 : hr; ctx.fillStyle = "black"; // write Hours ctx.save(); - ctx.rotate( hr*(Math.PI/6) + (Math.PI/360)*min + (Math.PI/21600)*sec ) + ctx.rotate( + hr * (Math.PI / 6) + (Math.PI / 360) * min + (Math.PI / 21600) * sec, + ); ctx.lineWidth = 14; ctx.beginPath(); - ctx.moveTo(-20,0); - ctx.lineTo(80,0); + ctx.moveTo(-20, 0); + ctx.lineTo(80, 0); ctx.stroke(); ctx.restore(); // write Minutes ctx.save(); - ctx.rotate( (Math.PI/30)*min + (Math.PI/1800)*sec ) + ctx.rotate((Math.PI / 30) * min + (Math.PI / 1800) * sec); ctx.lineWidth = 10; ctx.beginPath(); - ctx.moveTo(-28,0); - ctx.lineTo(112,0); + ctx.moveTo(-28, 0); + ctx.lineTo(112, 0); ctx.stroke(); ctx.restore(); // Write seconds ctx.save(); - ctx.rotate(sec * Math.PI/30); + ctx.rotate((sec * Math.PI) / 30); ctx.strokeStyle = "#D40000"; ctx.fillStyle = "#D40000"; ctx.lineWidth = 6; ctx.beginPath(); - ctx.moveTo(-30,0); - ctx.lineTo(83,0); + ctx.moveTo(-30, 0); + ctx.lineTo(83, 0); ctx.stroke(); ctx.beginPath(); - ctx.arc(0,0,10,0,Math.PI*2,true); + ctx.arc(0, 0, 10, 0, Math.PI * 2, true); ctx.fill(); ctx.beginPath(); - ctx.arc(95,0,10,0,Math.PI*2,true); + ctx.arc(95, 0, 10, 0, Math.PI * 2, true); ctx.stroke(); ctx.fillStyle = "rgba(0,0,0,0)"; - ctx.arc(0,0,3,0,Math.PI*2,true); + ctx.arc(0, 0, 3, 0, Math.PI * 2, true); ctx.fill(); ctx.restore(); ctx.beginPath(); ctx.lineWidth = 14; - ctx.strokeStyle = '#325FA2'; - ctx.arc(0,0,142,0,Math.PI*2,true); + ctx.strokeStyle = "#325FA2"; + ctx.arc(0, 0, 142, 0, Math.PI * 2, true); ctx.stroke(); ctx.restore(); @@ -224,7 +232,7 @@ var img = new Image(); // User Variables - customize these to change the image being scrolled, its // direction, and the speed. -img.src = 'capitan_meadows,_yosemite_national_park.jpg'; +img.src = "capitan_meadows,_yosemite_national_park.jpg"; var CanvasXSize = 800; var CanvasYSize = 200; var speed = 30; // lower is faster @@ -241,68 +249,68 @@ var clearX; var clearY; var ctx; -img.onload = function() { - imgW = img.width * scale; - imgH = img.height * scale; +img.onload = function () { + imgW = img.width * scale; + imgH = img.height * scale; - if (imgW > CanvasXSize) { - // image larger than canvas - x = CanvasXSize - imgW; - } - if (imgW > CanvasXSize) { - // image width larger than canvas - clearX = imgW; - } else { - clearX = CanvasXSize; - } - if (imgH > CanvasYSize) { - // image height larger than canvas - clearY = imgH; - } else { - clearY = CanvasYSize; - } + if (imgW > CanvasXSize) { + // image larger than canvas + x = CanvasXSize - imgW; + } + if (imgW > CanvasXSize) { + // image width larger than canvas + clearX = imgW; + } else { + clearX = CanvasXSize; + } + if (imgH > CanvasYSize) { + // image height larger than canvas + clearY = imgH; + } else { + clearY = CanvasYSize; + } - // get canvas context - ctx = document.getElementById('canvas').getContext('2d'); + // get canvas context + ctx = document.getElementById("canvas").getContext("2d"); - // set refresh rate - return setInterval(draw, speed); -} + // set refresh rate + return setInterval(draw, speed); +}; function draw() { - ctx.clearRect(0, 0, clearX, clearY); // clear the canvas + ctx.clearRect(0, 0, clearX, clearY); // clear the canvas - // if image is <= Canvas Size - if (imgW <= CanvasXSize) { - // reset, start from beginning - if (x > CanvasXSize) { - x = -imgW + x; - } - // draw additional image1 - if (x > 0) { - ctx.drawImage(img, -imgW + x, y, imgW, imgH); - } - // draw additional image2 - if (x - imgW > 0) { - ctx.drawImage(img, -imgW * 2 + x, y, imgW, imgH); - } + // if image is <= Canvas Size + if (imgW <= CanvasXSize) { + // reset, start from beginning + if (x > CanvasXSize) { + x = -imgW + x; } + // draw additional image1 + if (x > 0) { + ctx.drawImage(img, -imgW + x, y, imgW, imgH); + } + // draw additional image2 + if (x - imgW > 0) { + ctx.drawImage(img, -imgW * 2 + x, y, imgW, imgH); + } + } - // image is > Canvas Size - else { - // reset, start from beginning - if (x > (CanvasXSize)) { - x = CanvasXSize - imgW; - } - // draw aditional image - if (x > (CanvasXSize-imgW)) { - ctx.drawImage(img, x - imgW + 1, y, imgW, imgH); - } + // image is > Canvas Size + else { + // reset, start from beginning + if (x > CanvasXSize) { + x = CanvasXSize - imgW; } - // draw image - ctx.drawImage(img, x, y,imgW, imgH); - // amount to move - x += dx; + // draw aditional image + if (x > CanvasXSize - imgW) { + ctx.drawImage(img, x - imgW + 1, y, imgW, imgH); + } + } + // draw image + ctx.drawImage(img, x, y, imgW, imgH); + // amount to move + x += dx; } ``` @@ -321,129 +329,136 @@ function draw() { ## 鼠标追踪动画 ```html - + - - - - - Document - - - - - - qwerewr - - + + + + + Document + + + + + + qwerewr + ``` diff --git a/files/zh-cn/web/api/canvas_api/tutorial/basic_usage/index.md b/files/zh-cn/web/api/canvas_api/tutorial/basic_usage/index.md index 9a97e104dd035f..c74d0ad9288095 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/basic_usage/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/basic_usage/index.md @@ -35,7 +35,7 @@ slug: Web/API/Canvas_API/Tutorial/Basic_usage
- + ``` @@ -52,8 +52,8 @@ slug: Web/API/Canvas_API/Tutorial/Basic_usage canvas 起初是空白的。为了展示,首先脚本需要找到渲染上下文,然后在它的上面绘制。{{HTMLElement("canvas")}} 元素有一个叫做 {{domxref("HTMLCanvasElement.getContext", "getContext()")}} 的方法,这个方法是用来获得渲染上下文和它的绘画功能。`getContext()`接受一个参数,即上下文的类型。对于 2D 图像而言,如本教程,你可以使用 {{domxref("CanvasRenderingContext2D")}}。 ```js -var canvas = document.getElementById('tutorial'); -var ctx = canvas.getContext('2d'); +var canvas = document.getElementById("tutorial"); +var ctx = canvas.getContext("2d"); ``` 代码的第一行通过使用 {{domxref("document.getElementById()")}} 方法来为 {{HTMLElement("canvas")}} 元素得到 DOM 对象。一旦有了元素对象,你可以通过使用它的 getContext() 方法来访问绘画上下文。 @@ -63,10 +63,10 @@ var ctx = canvas.getContext('2d'); 替换内容是用于在不支持 {{HTMLElement("canvas")}} 标签的浏览器中展示的。通过简单的测试 `getContext()` 方法的存在,脚本可以检查编程支持性。上面的代码片段现在变成了这个样子: ```js -var canvas = document.getElementById('tutorial'); +var canvas = document.getElementById("tutorial"); -if (canvas.getContext){ - var ctx = canvas.getContext('2d'); +if (canvas.getContext) { + var ctx = canvas.getContext("2d"); // drawing code here } else { // canvas-unsupported code here @@ -84,15 +84,17 @@ if (canvas.getContext){ Canvas tutorial @@ -113,25 +115,25 @@ if (canvas.getContext){ ```html - - - - - - + + + + + ``` diff --git a/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.md b/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.md index 16dffd5500130a..18a9f25c0e86c9 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/compositing/example/index.md @@ -16,40 +16,62 @@ slug: Web/API/Canvas_API/Tutorial/Compositing/Example ```js var canvas1 = document.createElement("canvas"); var canvas2 = document.createElement("canvas"); -var gco = [ 'source-over','source-in','source-out','source-atop', - 'destination-over','destination-in','destination-out','destination-atop', - 'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken', - 'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light', - 'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity' - ].reverse(); +var gco = [ + "source-over", + "source-in", + "source-out", + "source-atop", + "destination-over", + "destination-in", + "destination-out", + "destination-atop", + "lighter", + "copy", + "xor", + "multiply", + "screen", + "overlay", + "darken", + "lighten", + "color-dodge", + "color-burn", + "hard-light", + "soft-light", + "difference", + "exclusion", + "hue", + "saturation", + "color", + "luminosity", +].reverse(); var gcoText = [ -'这是默认设置,并在现有画布上下文之上绘制新图形。', -'新图形只在新图形和目标画布重叠的地方绘制。其他的都是透明的。', -'在不与现有画布内容重叠的地方绘制新图形。', -'新图形只在与现有画布内容重叠的地方绘制。', -'在现有的画布内容后面绘制新的图形。', -'现有的画布内容保持在新图形和现有画布内容重叠的位置。其他的都是透明的。', -'现有内容保持在新图形不重叠的地方。', -'现有的画布只保留与新图形重叠的部分,新的图形是在画布内容后面绘制的。', -'两个重叠图形的颜色是通过颜色值相加来确定的。', -'只显示新图形。', -'图像中,那些重叠和正常绘制之外的其他地方是透明的。', -'将顶层像素与底层相应像素相乘,结果是一幅更黑暗的图片。', -'像素被倒转,相乘,再倒转,结果是一幅更明亮的图片。', -'multiply 和 screen 的结合,原本暗的地方更暗,原本亮的地方更亮。', -'保留两个图层中最暗的像素。', -'保留两个图层中最亮的像素。', -'将底层除以顶层的反置。', -'将反置的底层除以顶层,然后将结果反过来。', -'屏幕相乘(A combination of multiply and screen)类似于叠加,但上下图层互换了。', -'用顶层减去底层或者相反来得到一个正值。', -'一个柔和版本的强光(hard-light)。纯黑或纯白不会导致纯黑或纯白。', -'和 difference 相似,但对比度较低。', -'保留了底层的亮度(luma)和色度(chroma),同时采用了顶层的色调(hue)。', -'保留底层的亮度(luma)和色调(hue),同时采用顶层的色度(chroma)。', -'保留了底层的亮度(luma),同时采用了顶层的色调 (hue) 和色度 (chroma)。', -'保持底层的色调(hue)和色度(chroma),同时采用顶层的亮度(luma)。' - ].reverse(); + "这是默认设置,并在现有画布上下文之上绘制新图形。", + "新图形只在新图形和目标画布重叠的地方绘制。其他的都是透明的。", + "在不与现有画布内容重叠的地方绘制新图形。", + "新图形只在与现有画布内容重叠的地方绘制。", + "在现有的画布内容后面绘制新的图形。", + "现有的画布内容保持在新图形和现有画布内容重叠的位置。其他的都是透明的。", + "现有内容保持在新图形不重叠的地方。", + "现有的画布只保留与新图形重叠的部分,新的图形是在画布内容后面绘制的。", + "两个重叠图形的颜色是通过颜色值相加来确定的。", + "只显示新图形。", + "图像中,那些重叠和正常绘制之外的其他地方是透明的。", + "将顶层像素与底层相应像素相乘,结果是一幅更黑暗的图片。", + "像素被倒转,相乘,再倒转,结果是一幅更明亮的图片。", + "multiply 和 screen 的结合,原本暗的地方更暗,原本亮的地方更亮。", + "保留两个图层中最暗的像素。", + "保留两个图层中最亮的像素。", + "将底层除以顶层的反置。", + "将反置的底层除以顶层,然后将结果反过来。", + "屏幕相乘(A combination of multiply and screen)类似于叠加,但上下图层互换了。", + "用顶层减去底层或者相反来得到一个正值。", + "一个柔和版本的强光(hard-light)。纯黑或纯白不会导致纯黑或纯白。", + "和 difference 相似,但对比度较低。", + "保留了底层的亮度(luma)和色度(chroma),同时采用了顶层的色调(hue)。", + "保留底层的亮度(luma)和色调(hue),同时采用顶层的色度(chroma)。", + "保留了底层的亮度(luma),同时采用了顶层的色调 (hue) 和色度 (chroma)。", + "保持底层的色调(hue)和色度(chroma),同时采用顶层的亮度(luma)。", +].reverse(); var width = 320; var height = 340; ``` @@ -59,22 +81,22 @@ var height = 340; 当页面加载时,这部分程序会运行,并执行示例代码: ```js -window.onload = function() { - // lum in sRGB - var lum = { - r: 0.33, - g: 0.33, - b: 0.33 - }; - // resize canvas - canvas1.width = width; - canvas1.height = height; - canvas2.width = width; - canvas2.height = height; - lightMix() - colorSphere(); - runComposite(); - return; +window.onload = function () { + // lum in sRGB + var lum = { + r: 0.33, + g: 0.33, + b: 0.33, + }; + // resize canvas + canvas1.width = width; + canvas1.height = height; + canvas2.width = width; + canvas2.height = height; + lightMix(); + colorSphere(); + runComposite(); + return; }; ``` @@ -82,75 +104,75 @@ window.onload = function() { ```js function createCanvas() { - var canvas = document.createElement("canvas"); - canvas.style.background = "url("+op_8x8.data+")"; - canvas.style.border = "1px solid #000"; - canvas.style.margin = "5px"; - canvas.width = width/2; - canvas.height = height/2; - return canvas; + var canvas = document.createElement("canvas"); + canvas.style.background = "url(" + op_8x8.data + ")"; + canvas.style.border = "1px solid #000"; + canvas.style.margin = "5px"; + canvas.width = width / 2; + canvas.height = height / 2; + return canvas; } function runComposite() { - var dl = document.createElement("dl"); - document.body.appendChild(dl); - while(gco.length) { - var pop = gco.pop(); - var dt = document.createElement("dt"); - dt.textContent = pop; - dl.appendChild(dt); - var dd = document.createElement("dd"); - var p = document.createElement("p"); - p.textContent = gcoText.pop(); - dd.appendChild(p); + var dl = document.createElement("dl"); + document.body.appendChild(dl); + while (gco.length) { + var pop = gco.pop(); + var dt = document.createElement("dt"); + dt.textContent = pop; + dl.appendChild(dt); + var dd = document.createElement("dd"); + var p = document.createElement("p"); + p.textContent = gcoText.pop(); + dd.appendChild(p); - var canvasToDrawOn = createCanvas(); - var canvasToDrawFrom = createCanvas(); - var canvasToDrawResult = createCanvas(); + var canvasToDrawOn = createCanvas(); + var canvasToDrawFrom = createCanvas(); + var canvasToDrawResult = createCanvas(); - var ctx = canvasToDrawResult.getContext('2d'); - ctx.clearRect(0, 0, width, height) - ctx.save(); - ctx.drawImage(canvas1, 0, 0, width/2, height/2); - ctx.globalCompositeOperation = pop; - ctx.drawImage(canvas2, 0, 0, width/2, height/2); - ctx.globalCompositeOperation = "source-over"; - ctx.fillStyle = "rgba(0,0,0,0.8)"; - ctx.fillRect(0, height/2 - 20, width/2, 20); - ctx.fillStyle = "#FFF"; - ctx.font = "14px arial"; - ctx.fillText(pop, 5, height/2 - 5); - ctx.restore(); + var ctx = canvasToDrawResult.getContext("2d"); + ctx.clearRect(0, 0, width, height); + ctx.save(); + ctx.drawImage(canvas1, 0, 0, width / 2, height / 2); + ctx.globalCompositeOperation = pop; + ctx.drawImage(canvas2, 0, 0, width / 2, height / 2); + ctx.globalCompositeOperation = "source-over"; + ctx.fillStyle = "rgba(0,0,0,0.8)"; + ctx.fillRect(0, height / 2 - 20, width / 2, 20); + ctx.fillStyle = "#FFF"; + ctx.font = "14px arial"; + ctx.fillText(pop, 5, height / 2 - 5); + ctx.restore(); - var ctx = canvasToDrawOn.getContext('2d'); - ctx.clearRect(0, 0, width, height) - ctx.save(); - ctx.drawImage(canvas1, 0, 0, width/2, height/2); - ctx.fillStyle = "rgba(0,0,0,0.8)"; - ctx.fillRect(0, height/2 - 20, width/2, 20); - ctx.fillStyle = "#FFF"; - ctx.font = "14px arial"; - ctx.fillText('existing content', 5, height/2 - 5); - ctx.restore(); + var ctx = canvasToDrawOn.getContext("2d"); + ctx.clearRect(0, 0, width, height); + ctx.save(); + ctx.drawImage(canvas1, 0, 0, width / 2, height / 2); + ctx.fillStyle = "rgba(0,0,0,0.8)"; + ctx.fillRect(0, height / 2 - 20, width / 2, 20); + ctx.fillStyle = "#FFF"; + ctx.font = "14px arial"; + ctx.fillText("existing content", 5, height / 2 - 5); + ctx.restore(); - var ctx = canvasToDrawFrom.getContext('2d'); - ctx.clearRect(0, 0, width, height) - ctx.save(); - ctx.drawImage(canvas2, 0, 0, width/2, height/2); - ctx.fillStyle = "rgba(0,0,0,0.8)"; - ctx.fillRect(0, height/2 - 20, width/2, 20); - ctx.fillStyle = "#FFF"; - ctx.font = "14px arial"; - ctx.fillText('new content', 5, height/2 - 5); - ctx.restore(); + var ctx = canvasToDrawFrom.getContext("2d"); + ctx.clearRect(0, 0, width, height); + ctx.save(); + ctx.drawImage(canvas2, 0, 0, width / 2, height / 2); + ctx.fillStyle = "rgba(0,0,0,0.8)"; + ctx.fillRect(0, height / 2 - 20, width / 2, 20); + ctx.fillStyle = "#FFF"; + ctx.font = "14px arial"; + ctx.fillText("new content", 5, height / 2 - 5); + ctx.restore(); - dd.appendChild(canvasToDrawOn); - dd.appendChild(canvasToDrawFrom); - dd.appendChild(canvasToDrawResult); + dd.appendChild(canvasToDrawOn); + dd.appendChild(canvasToDrawFrom); + dd.appendChild(canvasToDrawResult); - dl.appendChild(dd); - } -}; + dl.appendChild(dd); + } +} ``` ### 效用函数 (Utility functions) @@ -158,60 +180,68 @@ function runComposite() { 程序需要依赖许多效用函数。 ```js -var lightMix = function() { - var ctx = canvas2.getContext("2d"); - ctx.save(); - ctx.globalCompositeOperation = "lighter"; - ctx.beginPath(); - ctx.fillStyle = "rgba(255,0,0,1)"; - ctx.arc(100, 200, 100, Math.PI*2, 0, false); - ctx.fill() - ctx.beginPath(); - ctx.fillStyle = "rgba(0,0,255,1)"; - ctx.arc(220, 200, 100, Math.PI*2, 0, false); - ctx.fill() - ctx.beginPath(); - ctx.fillStyle = "rgba(0,255,0,1)"; - ctx.arc(160, 100, 100, Math.PI*2, 0, false); - ctx.fill(); - ctx.restore(); - ctx.beginPath(); - ctx.fillStyle = "#f00"; - ctx.fillRect(0,0,30,30) - ctx.fill(); +var lightMix = function () { + var ctx = canvas2.getContext("2d"); + ctx.save(); + ctx.globalCompositeOperation = "lighter"; + ctx.beginPath(); + ctx.fillStyle = "rgba(255,0,0,1)"; + ctx.arc(100, 200, 100, Math.PI * 2, 0, false); + ctx.fill(); + ctx.beginPath(); + ctx.fillStyle = "rgba(0,0,255,1)"; + ctx.arc(220, 200, 100, Math.PI * 2, 0, false); + ctx.fill(); + ctx.beginPath(); + ctx.fillStyle = "rgba(0,255,0,1)"; + ctx.arc(160, 100, 100, Math.PI * 2, 0, false); + ctx.fill(); + ctx.restore(); + ctx.beginPath(); + ctx.fillStyle = "#f00"; + ctx.fillRect(0, 0, 30, 30); + ctx.fill(); }; ``` ```js -var colorSphere = function(element) { - var ctx = canvas1.getContext("2d"); - var width = 360; - var halfWidth = width / 2; - var rotate = (1 / 360) * Math.PI * 2; // per degree - var offset = 0; // scrollbar offset - var oleft = -20; - var otop = -20; - for (var n = 0; n <= 359; n ++) { - var gradient = ctx.createLinearGradient(oleft + halfWidth, otop, oleft + halfWidth, otop + halfWidth); - var color = Color.HSV_RGB({ H: (n + 300) % 360, S: 100, V: 100 }); - gradient.addColorStop(0, "rgba(0,0,0,0)"); - gradient.addColorStop(0.7, "rgba("+color.R+","+color.G+","+color.B+",1)"); - gradient.addColorStop(1, "rgba(255,255,255,1)"); - ctx.beginPath(); - ctx.moveTo(oleft + halfWidth, otop); - ctx.lineTo(oleft + halfWidth, otop + halfWidth); - ctx.lineTo(oleft + halfWidth + 6, otop); - ctx.fillStyle = gradient; - ctx.fill(); - ctx.translate(oleft + halfWidth, otop + halfWidth); - ctx.rotate(rotate); - ctx.translate(-(oleft + halfWidth), -(otop + halfWidth)); - } +var colorSphere = function (element) { + var ctx = canvas1.getContext("2d"); + var width = 360; + var halfWidth = width / 2; + var rotate = (1 / 360) * Math.PI * 2; // per degree + var offset = 0; // scrollbar offset + var oleft = -20; + var otop = -20; + for (var n = 0; n <= 359; n++) { + var gradient = ctx.createLinearGradient( + oleft + halfWidth, + otop, + oleft + halfWidth, + otop + halfWidth, + ); + var color = Color.HSV_RGB({ H: (n + 300) % 360, S: 100, V: 100 }); + gradient.addColorStop(0, "rgba(0,0,0,0)"); + gradient.addColorStop( + 0.7, + "rgba(" + color.R + "," + color.G + "," + color.B + ",1)", + ); + gradient.addColorStop(1, "rgba(255,255,255,1)"); ctx.beginPath(); - ctx.fillStyle = "#00f"; - ctx.fillRect(15,15,30,30) + ctx.moveTo(oleft + halfWidth, otop); + ctx.lineTo(oleft + halfWidth, otop + halfWidth); + ctx.lineTo(oleft + halfWidth + 6, otop); + ctx.fillStyle = gradient; ctx.fill(); - return ctx.canvas; + ctx.translate(oleft + halfWidth, otop + halfWidth); + ctx.rotate(rotate); + ctx.translate(-(oleft + halfWidth), -(otop + halfWidth)); + } + ctx.beginPath(); + ctx.fillStyle = "#00f"; + ctx.fillRect(15, 15, 30, 30); + ctx.fill(); + return ctx.canvas; }; ``` @@ -219,76 +249,78 @@ var colorSphere = function(element) { // HSV (1978) = H: Hue / S: Saturation / V: Value Color = {}; Color.HSV_RGB = function (o) { - var H = o.H / 360, - S = o.S / 100, - V = o.V / 100, - R, G, B; - var A, B, C, D; - if (S == 0) { - R = G = B = Math.round(V * 255); - } else { - if (H >= 1) H = 0; - H = 6 * H; - D = H - Math.floor(H); - A = Math.round(255 * V * (1 - S)); - B = Math.round(255 * V * (1 - (S * D))); - C = Math.round(255 * V * (1 - (S * (1 - D)))); - V = Math.round(255 * V); - switch (Math.floor(H)) { - case 0: - R = V; - G = C; - B = A; - break; - case 1: - R = B; - G = V; - B = A; - break; - case 2: - R = A; - G = V; - B = C; - break; - case 3: - R = A; - G = B; - B = V; - break; - case 4: - R = C; - G = A; - B = V; - break; - case 5: - R = V; - G = A; - B = B; - break; - } + var H = o.H / 360, + S = o.S / 100, + V = o.V / 100, + R, + G, + B; + var A, B, C, D; + if (S == 0) { + R = G = B = Math.round(V * 255); + } else { + if (H >= 1) H = 0; + H = 6 * H; + D = H - Math.floor(H); + A = Math.round(255 * V * (1 - S)); + B = Math.round(255 * V * (1 - S * D)); + C = Math.round(255 * V * (1 - S * (1 - D))); + V = Math.round(255 * V); + switch (Math.floor(H)) { + case 0: + R = V; + G = C; + B = A; + break; + case 1: + R = B; + G = V; + B = A; + break; + case 2: + R = A; + G = V; + B = C; + break; + case 3: + R = A; + G = B; + B = V; + break; + case 4: + R = C; + G = A; + B = V; + break; + case 5: + R = V; + G = A; + B = B; + break; } - return { - R: R, - G: G, - B: B - }; + } + return { + R: R, + G: G, + B: B, + }; }; var createInterlace = function (size, color1, color2) { - var proto = document.createElement("canvas").getContext("2d"); - proto.canvas.width = size * 2; - proto.canvas.height = size * 2; - proto.fillStyle = color1; // top-left - proto.fillRect(0, 0, size, size); - proto.fillStyle = color2; // top-right - proto.fillRect(size, 0, size, size); - proto.fillStyle = color2; // bottom-left - proto.fillRect(0, size, size, size); - proto.fillStyle = color1; // bottom-right - proto.fillRect(size, size, size, size); - var pattern = proto.createPattern(proto.canvas, "repeat"); - pattern.data = proto.canvas.toDataURL(); - return pattern; + var proto = document.createElement("canvas").getContext("2d"); + proto.canvas.width = size * 2; + proto.canvas.height = size * 2; + proto.fillStyle = color1; // top-left + proto.fillRect(0, 0, size, size); + proto.fillStyle = color2; // top-right + proto.fillRect(size, 0, size, size); + proto.fillStyle = color2; // bottom-left + proto.fillRect(0, size, size, size); + proto.fillStyle = color1; // bottom-right + proto.fillRect(size, size, size, size); + var pattern = proto.createPattern(proto.canvas, "repeat"); + pattern.data = proto.canvas.toDataURL(); + return pattern; }; var op_8x8 = createInterlace(8, "#FFF", "#eee"); diff --git a/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.md b/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.md index c6aeaff341533d..9e428c36264b0f 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/compositing/index.md @@ -39,44 +39,45 @@ slug: Web/API/Canvas_API/Tutorial/Compositing ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - ctx.fillRect(0,0,150,150); - ctx.translate(75,75); + var ctx = document.getElementById("canvas").getContext("2d"); + ctx.fillRect(0, 0, 150, 150); + ctx.translate(75, 75); // Create a circular clipping path ctx.beginPath(); - ctx.arc(0,0,60,0,Math.PI*2,true); + ctx.arc(0, 0, 60, 0, Math.PI * 2, true); ctx.clip(); // draw background - var lingrad = ctx.createLinearGradient(0,-75,0,75); - lingrad.addColorStop(0, '#232256'); - lingrad.addColorStop(1, '#143778'); + var lingrad = ctx.createLinearGradient(0, -75, 0, 75); + lingrad.addColorStop(0, "#232256"); + lingrad.addColorStop(1, "#143778"); ctx.fillStyle = lingrad; - ctx.fillRect(-75,-75,150,150); + ctx.fillRect(-75, -75, 150, 150); // draw stars - for (var j=1;j<50;j++){ + for (var j = 1; j < 50; j++) { ctx.save(); - ctx.fillStyle = '#fff'; - ctx.translate(75-Math.floor(Math.random()*150), - 75-Math.floor(Math.random()*150)); - drawStar(ctx,Math.floor(Math.random()*4)+2); + ctx.fillStyle = "#fff"; + ctx.translate( + 75 - Math.floor(Math.random() * 150), + 75 - Math.floor(Math.random() * 150), + ); + drawStar(ctx, Math.floor(Math.random() * 4) + 2); ctx.restore(); } - } -function drawStar(ctx,r){ +function drawStar(ctx, r) { ctx.save(); - ctx.beginPath() - ctx.moveTo(r,0); - for (var i=0;i<9;i++){ - ctx.rotate(Math.PI/5); - if(i%2 == 0) { - ctx.lineTo((r/0.525731)*0.200811,0); + ctx.beginPath(); + ctx.moveTo(r, 0); + for (var i = 0; i < 9; i++) { + ctx.rotate(Math.PI / 5); + if (i % 2 == 0) { + ctx.lineTo((r / 0.525731) * 0.200811, 0); } else { - ctx.lineTo(r,0); + ctx.lineTo(r, 0); } } ctx.closePath(); diff --git a/files/zh-cn/web/api/canvas_api/tutorial/drawing_shapes/index.md b/files/zh-cn/web/api/canvas_api/tutorial/drawing_shapes/index.md index aa0b25753a1b7f..2dd7ed6eaf03bf 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/drawing_shapes/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/drawing_shapes/index.md @@ -34,17 +34,17 @@ slug: Web/API/Canvas_API/Tutorial/Drawing_shapes ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); + var canvas = document.getElementById("canvas"); if (canvas.getContext) { - var ctx = canvas.getContext('2d'); + var ctx = canvas.getContext("2d"); ctx.fillRect(25, 25, 100, 100); ctx.clearRect(45, 45, 60, 60); @@ -99,17 +99,17 @@ function draw() { ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); + var canvas = document.getElementById("canvas"); if (canvas.getContext) { - var ctx = canvas.getContext('2d'); + var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(75, 50); @@ -137,26 +137,26 @@ function draw() { ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); - if (canvas.getContext){ - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + if (canvas.getContext) { + var ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.arc(75, 75, 50, 0, Math.PI * 2, true); // 绘制 ctx.moveTo(110, 75); - ctx.arc(75, 75, 35, 0, Math.PI, false); // 口 (顺时针) + ctx.arc(75, 75, 35, 0, Math.PI, false); // 口 (顺时针) ctx.moveTo(65, 65); - ctx.arc(60, 65, 5, 0, Math.PI * 2, true); // 左眼 + ctx.arc(60, 65, 5, 0, Math.PI * 2, true); // 左眼 ctx.moveTo(95, 65); - ctx.arc(90, 65, 5, 0, Math.PI * 2, true); // 右眼 + ctx.arc(90, 65, 5, 0, Math.PI * 2, true); // 右眼 ctx.stroke(); } } @@ -183,32 +183,32 @@ function draw() { ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); - if (canvas.getContext){ - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + if (canvas.getContext) { + var ctx = canvas.getContext("2d"); - // 填充三角形 - ctx.beginPath(); - ctx.moveTo(25, 25); - ctx.lineTo(105, 25); - ctx.lineTo(25, 105); - ctx.fill(); + // 填充三角形 + ctx.beginPath(); + ctx.moveTo(25, 25); + ctx.lineTo(105, 25); + ctx.lineTo(25, 105); + ctx.fill(); - // 描边三角形 - ctx.beginPath(); - ctx.moveTo(125, 125); - ctx.lineTo(125, 45); - ctx.lineTo(45, 125); - ctx.closePath(); - ctx.stroke(); + // 描边三角形 + ctx.beginPath(); + ctx.moveTo(125, 125); + ctx.lineTo(125, 45); + ctx.lineTo(45, 125); + ctx.closePath(); + ctx.stroke(); } } ``` @@ -246,20 +246,20 @@ x,y 坐标是可变的。半径(radius)和开始角度(startAngle)都是 ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); - if (canvas.getContext){ - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + if (canvas.getContext) { + var ctx = canvas.getContext("2d"); - for(var i = 0; i < 4; i++){ - for(var j = 0; j < 3; j++){ + for (var i = 0; i < 4; i++) { + for (var j = 0; j < 3; j++) { ctx.beginPath(); var x = 25 + j * 50; // x 坐标值 var y = 25 + i * 50; // y 坐标值 @@ -270,7 +270,7 @@ function draw() { ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise); - if (i>1){ + if (i > 1) { ctx.fill(); } else { ctx.stroke(); @@ -306,17 +306,17 @@ function draw() { ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); + var canvas = document.getElementById("canvas"); if (canvas.getContext) { - var ctx = canvas.getContext('2d'); + var ctx = canvas.getContext("2d"); // 二次贝塞尔曲线 ctx.beginPath(); @@ -328,7 +328,7 @@ function draw() { ctx.quadraticCurveTo(125, 100, 125, 62.5); ctx.quadraticCurveTo(125, 25, 75, 25); ctx.stroke(); - } + } } ``` @@ -340,19 +340,19 @@ function draw() { ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); - if (canvas.getContext){ - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + if (canvas.getContext) { + var ctx = canvas.getContext("2d"); - //三次贝塞尔曲线 + //三次贝塞尔曲线 ctx.beginPath(); ctx.moveTo(75, 40); ctx.bezierCurveTo(75, 37, 70, 25, 50, 25); @@ -383,17 +383,17 @@ function draw() { ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); - if (canvas.getContext){ - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + if (canvas.getContext) { + var ctx = canvas.getContext("2d"); roundedRect(ctx, 12, 12, 150, 150, 15); roundedRect(ctx, 19, 19, 150, 150, 9); @@ -407,15 +407,15 @@ function draw() { ctx.lineTo(31, 37); ctx.fill(); - for(var i = 0; i < 8; i++){ + for (var i = 0; i < 8; i++) { ctx.fillRect(51 + i * 16, 35, 4, 4); } - for(i = 0; i < 6; i++){ + for (i = 0; i < 6; i++) { ctx.fillRect(115, 51 + i * 16, 4, 4); } - for(i = 0; i < 8; i++){ + for (i = 0; i < 8; i++) { ctx.fillRect(51 + i * 16, 99, 4, 4); } @@ -460,7 +460,7 @@ function draw() { // 封装的一个用于绘制圆角矩形的函数。 -function roundedRect(ctx, x, y, width, height, radius){ +function roundedRect(ctx, x, y, width, height, radius) { ctx.beginPath(); ctx.moveTo(x, y + radius); ctx.lineTo(x, y + height - radius); @@ -493,9 +493,9 @@ function roundedRect(ctx, x, y, width, height, radius){ - : `Path2D()`会返回一个新初始化的 Path2D 对象(可能将某一个路径作为变量——创建一个它的副本,或者将一个包含 SVG path 数据的字符串作为变量)。 ```js -new Path2D(); // 空的 Path 对象 +new Path2D(); // 空的 Path 对象 new Path2D(path); // 克隆 Path 对象 -new Path2D(d); // 从 SVG 建立 Path 对象 +new Path2D(d); // 从 SVG 建立 Path 对象 ``` 所有的路径方法比如`moveTo`, `rect`, `arc`或`quadraticCurveTo`等,如我们前面见过的,都可以在 Path2D 中使用。 @@ -511,17 +511,17 @@ Path2D API 添加了 `addPath`作为将`path`结合起来的方法。当你想 ```html hidden - - - + + + ``` ```js function draw() { - var canvas = document.getElementById('canvas'); - if (canvas.getContext){ - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + if (canvas.getContext) { + var ctx = canvas.getContext("2d"); var rectangle = new Path2D(); rectangle.rect(10, 10, 50, 50); diff --git a/files/zh-cn/web/api/canvas_api/tutorial/drawing_text/index.md b/files/zh-cn/web/api/canvas_api/tutorial/drawing_text/index.md index 58d5a0add95b68..82d7479cb7ab8f 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/drawing_text/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/drawing_text/index.md @@ -22,7 +22,7 @@ canvas 提供了两种方法来渲染文本: ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); ctx.font = "48px serif"; ctx.fillText("Hello world", 10, 50); } @@ -44,7 +44,7 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); ctx.font = "48px serif"; ctx.strokeText("Hello world", 10, 50); } @@ -107,7 +107,8 @@ ctx.strokeText("Hello world", 0, 100); +ctx.strokeText("Hello world", 0, 100); ``` ```js hidden @@ -123,14 +124,14 @@ function drawCanvas() { eval(textarea.value); } -reset.addEventListener("click", function() { +reset.addEventListener("click", function () { textarea.value = code; drawCanvas(); }); -edit.addEventListener("click", function() { +edit.addEventListener("click", function () { textarea.focus(); -}) +}); textarea.addEventListener("input", drawCanvas); window.addEventListener("load", drawCanvas); @@ -149,7 +150,7 @@ window.addEventListener("load", drawCanvas); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); var text = ctx.measureText("foo"); // TextMetrics object text.width; // 16; } diff --git a/files/zh-cn/web/api/canvas_api/tutorial/optimizing_canvas/index.md b/files/zh-cn/web/api/canvas_api/tutorial/optimizing_canvas/index.md index c9104fc334e0a5..4b9587befedb51 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/optimizing_canvas/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/optimizing_canvas/index.md @@ -56,12 +56,20 @@ ctx.drawImage(myImage, 0.3, 0.5); width: 480px; height: 320px; position: relative; - border: 2px solid black + border: 2px solid black; + } + canvas { + position: absolute; + } + #ui-layer { + z-index: 3; + } + #game-layer { + z-index: 2; + } + #background-layer { + z-index: 1; } - canvas { position: absolute; } - #ui-layer { z-index: 3 } - #game-layer { z-index: 2 } - #background-layer { z-index: 1 } ``` @@ -80,8 +88,8 @@ var scaleY = window.innerHeight / canvas.height; var scaleToFit = Math.min(scaleX, scaleY); var scaleToCover = Math.max(scaleX, scaleY); -stage.style.transformOrigin = '0 0'; //scale from top left -stage.style.transform = 'scale(' + scaleToFit + ')'; +stage.style.transformOrigin = "0 0"; //scale from top left +stage.style.transform = "scale(" + scaleToFit + ")"; ``` ### 关闭透明度 @@ -89,7 +97,7 @@ stage.style.transform = 'scale(' + scaleToFit + ')'; 如果你的游戏使用画布而且不需要透明,当使用 [`HTMLCanvasElement.getContext()`](/zh-CN/docs/Web/API/HTMLCanvasElement/getContext) 创建一个绘图上下文时把 `alpha` 选项设置为 `false` 。这个选项可以帮助浏览器进行内部优化。 ```js -var ctx = canvas.getContext('2d', { alpha: false }); +var ctx = canvas.getContext("2d", { alpha: false }); ``` ### 更多的贴士 diff --git a/files/zh-cn/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.md b/files/zh-cn/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.md index 23c41aa530afb0..1ad14ccf653b72 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.md @@ -81,40 +81,47 @@ var myImageData = ctx.getImageData(left, top, width, height); ```js hidden var img = new Image(); -img.src = 'rhino.jpg'; -var canvas = document.getElementById('canvas'); -var ctx = canvas.getContext('2d'); -img.onload = function() { +img.src = "rhino.jpg"; +var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +img.onload = function () { ctx.drawImage(img, 0, 0); - img.style.display = 'none'; + img.style.display = "none"; }; -var color = document.getElementById('color'); +var color = document.getElementById("color"); function pick(event) { var x = event.layerX; var y = event.layerY; var pixel = ctx.getImageData(x, y, 1, 1); var data = pixel.data; - var rgba = 'rgba(' + data[0] + ',' + data[1] + - ',' + data[2] + ',' + (data[3] / 255) + ')'; - color.style.background = rgba; + var rgba = + "rgba(" + + data[0] + + "," + + data[1] + + "," + + data[2] + + "," + + data[3] / 255 + + ")"; + color.style.background = rgba; color.textContent = rgba; } -canvas.addEventListener('mousemove', pick); +canvas.addEventListener("mousemove", pick); ``` ```js var img = new Image(); -img.crossOrigin = 'anonymous'; -img.src = './assets/rhino.jpg'; -var canvas = document.getElementById('canvas'); -var ctx = canvas.getContext('2d'); -img.onload = function() { +img.crossOrigin = "anonymous"; +img.src = "./assets/rhino.jpg"; +var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); +img.onload = function () { ctx.drawImage(img, 0, 0); - img.style.display = 'none'; + img.style.display = "none"; }; -var hoveredColor = document.getElementById('hovered-color'); -var selectedColor = document.getElementById('selected-color'); - +var hoveredColor = document.getElementById("hovered-color"); +var selectedColor = document.getElementById("selected-color"); function pick(event, destination) { var x = event.layerX; @@ -122,18 +129,18 @@ function pick(event, destination) { var pixel = ctx.getImageData(x, y, 1, 1); var data = pixel.data; - const rgba = `rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3] / 255})`; - destination.style.background = rgba; - destination.textContent = rgba; + const rgba = `rgba(${data[0]}, ${data[1]}, ${data[2]}, ${data[3] / 255})`; + destination.style.background = rgba; + destination.textContent = rgba; - return rgba; + return rgba; } -canvas.addEventListener('mousemove', function(event) { - pick(event, hoveredColor); +canvas.addEventListener("mousemove", function (event) { + pick(event, hoveredColor); }); -canvas.addEventListener('click', function(event) { - pick(event, selectedColor); +canvas.addEventListener("click", function (event) { + pick(event, selectedColor); }); ``` @@ -162,105 +169,105 @@ ctx.putImageData(myImageData, 0, 0); ```html hidden
- - + +
``` ```js hidden var img = new Image(); -img.src = 'rhino.jpg'; -img.onload = function() { +img.src = "rhino.jpg"; +img.onload = function () { draw(this); }; function draw(img) { - var canvas = document.getElementById('canvas'); - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); - img.style.display = 'none'; - var imageData = ctx.getImageData(0,0,canvas.width, canvas.height); + img.style.display = "none"; + var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); var data = imageData.data; - var invert = function() { + var invert = function () { for (var i = 0; i < data.length; i += 4) { - data[i] = 255 - data[i]; // red + data[i] = 255 - data[i]; // red data[i + 1] = 255 - data[i + 1]; // green data[i + 2] = 255 - data[i + 2]; // blue } ctx.putImageData(imageData, 0, 0); }; - var grayscale = function() { + var grayscale = function () { for (var i = 0; i < data.length; i += 4) { - var avg = (data[i] + data[i +1] + data[i +2]) / 3; - data[i] = avg; // red + var avg = (data[i] + data[i + 1] + data[i + 2]) / 3; + data[i] = avg; // red data[i + 1] = avg; // green data[i + 2] = avg; // blue } ctx.putImageData(imageData, 0, 0); }; - var invertbtn = document.getElementById('invertbtn'); - invertbtn.addEventListener('click', invert); - var grayscalebtn = document.getElementById('grayscalebtn'); - grayscalebtn.addEventListener('click', grayscale); + var invertbtn = document.getElementById("invertbtn"); + invertbtn.addEventListener("click", invert); + var grayscalebtn = document.getElementById("grayscalebtn"); + grayscalebtn.addEventListener("click", grayscale); } ``` ```js var img = new Image(); -img.crossOrigin = 'anonymous'; -img.src = './assets/rhino.jpg'; +img.crossOrigin = "anonymous"; +img.src = "./assets/rhino.jpg"; -var canvas = document.getElementById('canvas'); -var ctx = canvas.getContext('2d'); +var canvas = document.getElementById("canvas"); +var ctx = canvas.getContext("2d"); -img.onload = function() { - ctx.drawImage(img, 0, 0); +img.onload = function () { + ctx.drawImage(img, 0, 0); }; -var original = function() { - ctx.drawImage(img, 0, 0); +var original = function () { + ctx.drawImage(img, 0, 0); }; -var invert = function() { - ctx.drawImage(img, 0, 0); - const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); - const data = imageData.data; - for (var i = 0; i < data.length; i += 4) { - data[i] = 255 - data[i]; // red - data[i + 1] = 255 - data[i + 1]; // green - data[i + 2] = 255 - data[i + 2]; // blue - } - ctx.putImageData(imageData, 0, 0); +var invert = function () { + ctx.drawImage(img, 0, 0); + const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + const data = imageData.data; + for (var i = 0; i < data.length; i += 4) { + data[i] = 255 - data[i]; // red + data[i + 1] = 255 - data[i + 1]; // green + data[i + 2] = 255 - data[i + 2]; // blue + } + ctx.putImageData(imageData, 0, 0); }; -var grayscale = function() { - ctx.drawImage(img, 0, 0); - const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); - const data = imageData.data; - for (var i = 0; i < data.length; i += 4) { - var avg = (data[i] + data[i + 1] + data[i + 2]) / 3; - data[i] = avg; // red - data[i + 1] = avg; // green - data[i + 2] = avg; // blue - } - ctx.putImageData(imageData, 0, 0); +var grayscale = function () { + ctx.drawImage(img, 0, 0); + const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); + const data = imageData.data; + for (var i = 0; i < data.length; i += 4) { + var avg = (data[i] + data[i + 1] + data[i + 2]) / 3; + data[i] = avg; // red + data[i + 1] = avg; // green + data[i + 2] = avg; // blue + } + ctx.putImageData(imageData, 0, 0); }; -const inputs = document.querySelectorAll('[name=color]'); +const inputs = document.querySelectorAll("[name=color]"); for (const input of inputs) { - input.addEventListener("change", function(evt) { - switch (evt.target.value) { - case "inverted": - return invert(); - case "grayscale": - return grayscale(); - default: - return original(); - } - }); + input.addEventListener("change", function (evt) { + switch (evt.target.value) { + case "inverted": + return invert(); + case "grayscale": + return grayscale(); + default: + return original(); + } + }); } ``` @@ -273,9 +280,17 @@ for (const input of inputs) { 我们得到鼠标的位置并裁剪出距左和上 5 像素,距右和下 5 像素的图片。然后我们将这幅图复制到另一个画布然后将图片调整到我们想要的大小。在缩放画布里,我们将 10×10 像素的对原画布的裁剪调整为 200×200。 ```js -zoomctx.drawImage(canvas, - Math.abs(x - 5), Math.abs(y - 5), - 10, 10, 0, 0, 200, 200); +zoomctx.drawImage( + canvas, + Math.abs(x - 5), + Math.abs(y - 5), + 10, + 10, + 0, + 0, + 200, + 200, +); ``` 因为反锯齿默认是启用的,我们可能想要关闭它以看到清楚的像素。你可以通过切换勾选框来看到 `imageSmoothingEnabled` 属性的效果(不同浏览器需要不同前缀)。 @@ -286,48 +301,53 @@ zoomctx.drawImage(canvas,
- +
``` ```js var img = new Image(); -img.src = 'rhino.jpg'; -img.onload = function() { +img.src = "rhino.jpg"; +img.onload = function () { draw(this); }; function draw(img) { - var canvas = document.getElementById('canvas'); - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0); - img.style.display = 'none'; - var zoomctx = document.getElementById('zoom').getContext('2d'); + img.style.display = "none"; + var zoomctx = document.getElementById("zoom").getContext("2d"); - var smoothbtn = document.getElementById('smoothbtn'); - var toggleSmoothing = function(event) { + var smoothbtn = document.getElementById("smoothbtn"); + var toggleSmoothing = function (event) { zoomctx.imageSmoothingEnabled = this.checked; zoomctx.mozImageSmoothingEnabled = this.checked; zoomctx.webkitImageSmoothingEnabled = this.checked; zoomctx.msImageSmoothingEnabled = this.checked; }; - smoothbtn.addEventListener('change', toggleSmoothing); + smoothbtn.addEventListener("change", toggleSmoothing); - var zoom = function(event) { + var zoom = function (event) { var x = event.layerX; var y = event.layerY; - zoomctx.drawImage(canvas, - Math.abs(x - 5), - Math.abs(y - 5), - 10, 10, - 0, 0, - 200, 200); + zoomctx.drawImage( + canvas, + Math.abs(x - 5), + Math.abs(y - 5), + 10, + 10, + 0, + 0, + 200, + 200, + ); }; - canvas.addEventListener('mousemove', zoom); + canvas.addEventListener("mousemove", zoom); } ``` diff --git a/files/zh-cn/web/api/canvas_api/tutorial/transformations/index.md b/files/zh-cn/web/api/canvas_api/tutorial/transformations/index.md index aaf0febcbefc5e..9272cb1c812aa2 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/transformations/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/transformations/index.md @@ -38,24 +38,24 @@ Canvas 状态存储在栈中,每当`save()`方法被调用后,当前的状 ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); - ctx.fillRect(0,0,150,150); // 使用默认设置绘制一个矩形 - ctx.save(); // 保存默认状态 + ctx.fillRect(0, 0, 150, 150); // 使用默认设置绘制一个矩形 + ctx.save(); // 保存默认状态 - ctx.fillStyle = '#09F' // 在原有配置基础上对颜色做改变 - ctx.fillRect(15,15,120,120); // 使用新的设置绘制一个矩形 + ctx.fillStyle = "#09F"; // 在原有配置基础上对颜色做改变 + ctx.fillRect(15, 15, 120, 120); // 使用新的设置绘制一个矩形 - ctx.save(); // 保存当前状态 - ctx.fillStyle = '#FFF' // 再次改变颜色配置 + ctx.save(); // 保存当前状态 + ctx.fillStyle = "#FFF"; // 再次改变颜色配置 ctx.globalAlpha = 0.5; - ctx.fillRect(30,30,90,90); // 使用新的配置绘制一个矩形 + ctx.fillRect(30, 30, 90, 90); // 使用新的配置绘制一个矩形 - ctx.restore(); // 重新加载之前的颜色状态 - ctx.fillRect(45,45,60,60); // 使用上一次的配置绘制一个矩形 + ctx.restore(); // 重新加载之前的颜色状态 + ctx.fillRect(45, 45, 60, 60); // 使用上一次的配置绘制一个矩形 - ctx.restore(); // 加载默认颜色配置 - ctx.fillRect(60,60,30,30); // 使用加载的配置绘制一个矩形 + ctx.restore(); // 加载默认颜色配置 + ctx.fillRect(60, 60, 30, 30); // 使用加载的配置绘制一个矩形 } ``` @@ -86,11 +86,11 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); for (var i = 0; i < 3; i++) { for (var j = 0; j < 3; j++) { ctx.save(); - ctx.fillStyle = 'rgb(' + (51 * i) + ', ' + (255 - 51 * i) + ', 255)'; + ctx.fillStyle = "rgb(" + 51 * i + ", " + (255 - 51 * i) + ", 255)"; ctx.translate(10 + j * 50, 10 + i * 50); ctx.fillRect(0, 0, 25, 25); ctx.restore(); @@ -185,7 +185,7 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); // draw a simple rectangle, but scale it. ctx.save(); @@ -195,8 +195,8 @@ function draw() { // mirror horizontally ctx.scale(-1, 1); - ctx.font = '48px serif'; - ctx.fillText('MDN', -135, 120); + ctx.font = "48px serif"; + ctx.fillText("MDN", -135, 120); } ``` @@ -246,14 +246,14 @@ draw(); ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); - var sin = Math.sin(Math.PI/6); - var cos = Math.cos(Math.PI/6); + var sin = Math.sin(Math.PI / 6); + var cos = Math.cos(Math.PI / 6); ctx.translate(100, 100); var c = 0; - for (var i=0; i <= 12; i++) { - c = Math.floor(255 / 12 * i); + for (var i = 0; i <= 12; i++) { + c = Math.floor((255 / 12) * i); ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")"; ctx.fillRect(0, 0, 100, 10); ctx.transform(cos, sin, -sin, cos, 0, 0); diff --git a/files/zh-cn/web/api/canvas_api/tutorial/using_images/index.md b/files/zh-cn/web/api/canvas_api/tutorial/using_images/index.md index 2da6a29e82952b..b1ad5dbe316b4d 100644 --- a/files/zh-cn/web/api/canvas_api/tutorial/using_images/index.md +++ b/files/zh-cn/web/api/canvas_api/tutorial/using_images/index.md @@ -54,8 +54,8 @@ canvas 的 API 可以使用下面这些类型中的一种作为图片的源: 或者我们可以用脚本创建一个新的 {{domxref("HTMLImageElement")}} 对象。要实现这个方法,我们可以使用很方便的 `Image()` 构造函数。 ```js -var img = new Image(); // 创建一个元素 -img.src = 'myImage.png'; // 设置图片源地址 +var img = new Image(); // 创建一个元素 +img.src = "myImage.png"; // 设置图片源地址 ``` 当脚本执行后,图片开始装载。 @@ -63,11 +63,11 @@ img.src = 'myImage.png'; // 设置图片源地址 若调用 `drawImage` 时,图片没装载完,那什么都不会发生(在一些旧的浏览器中可能会抛出异常)。因此你应该用 load 事件来保证不会在加载完毕之前使用这个图片: ```js -var img = new Image(); // 创建 img 元素 -img.onload = function(){ +var img = new Image(); // 创建 img 元素 +img.onload = function () { // 执行 drawImage 语句 -} -img.src = 'myImage.png'; // 设置图片源地址 +}; +img.src = "myImage.png"; // 设置图片源地址 ``` 如果你只用到一张图片的话,这已经够了。但一旦需要不止一张图片,那就需要更加复杂的处理方法,但图片预加载策略超出本教程的范围。 @@ -77,7 +77,8 @@ img.src = 'myImage.png'; // 设置图片源地址 我们还可以通过 [data:url](http://en.wikipedia.org/wiki/Data:_URL) 方式来引用图像。Data urls 允许用一串 Base64 编码的字符串的方式来定义一个图片。 ```js -img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw=='; +img.src = + "data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw=="; ``` 其优点就是图片内容即时可用,无须再到服务器兜一圈。(还有一个优点是,可以将 CSS,JavaScript,HTML 和 图片全部封装在一起,迁移起来十分方便。)缺点就是图像没法缓存,图片大的话内嵌的 url 数据会相当的长: @@ -88,11 +89,11 @@ img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAs ```js function getMyVideo() { - var canvas = document.getElementById('canvas'); + var canvas = document.getElementById("canvas"); if (canvas.getContext) { - var ctx = canvas.getContext('2d'); + var ctx = canvas.getContext("2d"); - return document.getElementById('myvideo'); + return document.getElementById("myvideo"); } } ``` @@ -116,27 +117,27 @@ function getMyVideo() { ```html hidden - - - + + + ``` ```js - function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); - var img = new Image(); - img.onload = function(){ - ctx.drawImage(img,0,0); - ctx.beginPath(); - ctx.moveTo(30,96); - ctx.lineTo(70,66); - ctx.lineTo(103,76); - ctx.lineTo(170,15); - ctx.stroke(); - } - img.src = 'backdrop.png'; - } +function draw() { + var ctx = document.getElementById("canvas").getContext("2d"); + var img = new Image(); + img.onload = function () { + ctx.drawImage(img, 0, 0); + ctx.beginPath(); + ctx.moveTo(30, 96); + ctx.lineTo(70, 66); + ctx.lineTo(103, 76); + ctx.lineTo(170, 15); + ctx.stroke(); + }; + img.src = "backdrop.png"; +} ``` 结果看起来是这样的: @@ -160,24 +161,24 @@ function getMyVideo() { ```html hidden - - - + + + ``` ```js function draw() { - var ctx = document.getElementById('canvas').getContext('2d'); + var ctx = document.getElementById("canvas").getContext("2d"); var img = new Image(); - img.onload = function(){ - for (var i=0;i<4;i++){ - for (var j=0;j<3;j++){ - ctx.drawImage(img,j*50,i*38,50,38); + img.onload = function () { + for (var i = 0; i < 4; i++) { + for (var j = 0; j < 3; j++) { + ctx.drawImage(img, j * 50, i * 38, 50, 38); } } }; - img.src = 'rhino.jpg'; + img.src = "rhino.jpg"; } ``` @@ -206,27 +207,36 @@ function draw() { ```html - - -
- - -
- + + +
+ + +
+ ``` ```js function draw() { - var canvas = document.getElementById('canvas'); - var ctx = canvas.getContext('2d'); + var canvas = document.getElementById("canvas"); + var ctx = canvas.getContext("2d"); // Draw slice - ctx.drawImage(document.getElementById('source'), - 33,71,104,124,21,20,87,104); + ctx.drawImage( + document.getElementById("source"), + 33, + 71, + 104, + 124, + 21, + 20, + 87, + 104, + ); // Draw frame - ctx.drawImage(document.getElementById('frame'),0,0); + ctx.drawImage(document.getElementById("frame"), 0, 0); } ``` @@ -242,29 +252,29 @@ function draw() { ```html - - + +
- - - - + + + + - - - - + + + + -
- - + + + ``` ```css body { - background: 0 -100px repeat-x url(bg_gallery.png) #4F191A; + background: 0 -100px repeat-x url(bg_gallery.png) #4f191a; margin: 10px; } @@ -283,28 +293,25 @@ td { ```js function draw() { - // Loop through all images - for (i=0;i