From 6ef1fa4618e08426b874529619a66adbd3d1fcf0 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 12:07:59 +0100 Subject: unslug ja: move --- files/ja/web/api/ambient_light_events/index.html | 68 ++ .../api/audiobuffersourcenode/onended/index.html | 108 --- .../web/api/audiobuffersourcenode/stop/index.html | 120 ---- .../web/api/audiocontext/createanalyser/index.html | 154 ----- .../api/audiocontext/createbiquadfilter/index.html | 126 ---- .../web/api/audiocontext/createbuffer/index.html | 174 ----- .../api/audiocontext/createbuffersource/index.html | 143 ---- .../audiocontext/createchannelmerger/index.html | 133 ---- .../audiocontext/createchannelsplitter/index.html | 133 ---- .../api/audiocontext/createconvolver/index.html | 131 ---- .../ja/web/api/audiocontext/createdelay/index.html | 143 ---- .../createdynamicscompressor/index.html | 138 ---- .../ja/web/api/audiocontext/creategain/index.html | 128 ---- .../api/audiocontext/createoscillator/index.html | 111 ---- .../web/api/audiocontext/createpanner/index.html | 198 ------ .../api/audiocontext/createperiodicwave/index.html | 139 ---- .../audiocontext/createscriptprocessor/index.html | 69 -- .../api/audiocontext/createstereopanner/index.html | 128 ---- .../ja/web/api/audiocontext/currenttime/index.html | 112 ---- .../api/audiocontext/decodeaudiodata/index.html | 155 ----- .../ja/web/api/audiocontext/destination/index.html | 114 ---- files/ja/web/api/audiocontext/listener/index.html | 112 ---- .../audiocontext/mozaudiochanneltype/index.html | 95 --- .../web/api/audiocontext/onstatechange/index.html | 101 --- .../ja/web/api/audiocontext/samplerate/index.html | 112 ---- files/ja/web/api/audiocontext/state/index.html | 66 -- .../audioscheduledsourcenode/onended/index.html | 108 +++ .../api/audioscheduledsourcenode/stop/index.html | 120 ++++ .../api/baseaudiocontext/createanalyser/index.html | 154 +++++ .../baseaudiocontext/createbiquadfilter/index.html | 126 ++++ .../api/baseaudiocontext/createbuffer/index.html | 174 +++++ .../baseaudiocontext/createbuffersource/index.html | 143 ++++ .../createchannelmerger/index.html | 133 ++++ .../createchannelsplitter/index.html | 133 ++++ .../baseaudiocontext/createconvolver/index.html | 131 ++++ .../api/baseaudiocontext/createdelay/index.html | 143 ++++ .../createdynamicscompressor/index.html | 138 ++++ .../web/api/baseaudiocontext/creategain/index.html | 128 ++++ .../baseaudiocontext/createoscillator/index.html | 111 ++++ .../api/baseaudiocontext/createpanner/index.html | 198 ++++++ .../baseaudiocontext/createperiodicwave/index.html | 139 ++++ .../createscriptprocessor/index.html | 69 ++ .../baseaudiocontext/createstereopanner/index.html | 128 ++++ .../api/baseaudiocontext/currenttime/index.html | 112 ++++ .../baseaudiocontext/decodeaudiodata/index.html | 155 +++++ .../api/baseaudiocontext/destination/index.html | 114 ++++ .../web/api/baseaudiocontext/listener/index.html | 112 ++++ .../api/baseaudiocontext/onstatechange/index.html | 101 +++ .../web/api/baseaudiocontext/samplerate/index.html | 112 ++++ files/ja/web/api/baseaudiocontext/state/index.html | 66 ++ .../drawing_graphics_with_canvas/index.html | 213 ------ .../tutorial/advanced_animations/index.html | 380 +++++++++++ .../tutorial/applying_styles_and_colors/index.html | 725 +++++++++++++++++++++ .../tutorial/basic_animations/index.html | 711 ++++++++++++++++++++ .../api/canvas_api/tutorial/basic_usage/index.html | 152 +++++ .../canvas_api/tutorial/drawing_shapes/index.html | 577 ++++++++++++++++ .../canvas_api/tutorial/drawing_text/index.html | 174 +++++ .../web/api/canvas_api/tutorial/finale/index.html | 51 ++ .../tutorial/optimizing_canvas/index.html | 118 ++++ .../pixel_manipulation_with_canvas/index.html | 264 ++++++++ .../canvas_api/tutorial/transformations/index.html | 282 ++++++++ .../canvas_api/tutorial/using_images/index.html | 337 ++++++++++ files/ja/web/api/css_painting_api/guide/index.html | 540 +++++++++++++++ .../index.html" | 540 --------------- files/ja/web/api/cssmatrix/index.html | 94 --- files/ja/web/api/deviceacceleration/index.html | 47 -- .../api/devicemotioneventacceleration/index.html | 47 ++ files/ja/web/api/document/activeelement/index.html | 144 ---- files/ja/web/api/document/async/index.html | 45 -- .../web/api/document/elementfrompoint/index.html | 50 -- files/ja/web/api/document/getanimations/index.html | 81 --- files/ja/web/api/document/getselection/index.html | 13 - files/ja/web/api/document/inputencoding/index.html | 26 - .../web/api/document/onselectionchange/index.html | 62 -- .../api/document_object_model/preface/index.html | 52 -- .../documentorshadowroot/activeelement/index.html | 144 ++++ .../elementfrompoint/index.html | 50 ++ .../documentorshadowroot/getanimations/index.html | 81 +++ .../documentorshadowroot/nodefrompoint/index.html | 79 --- .../documentorshadowroot/nodesfrompoint/index.html | 83 --- files/ja/web/api/dommatrix/index.html | 94 +++ files/ja/web/api/element/accesskey/index.html | 23 - files/ja/web/api/element/name/index.html | 58 -- files/ja/web/api/event/button/index.html | 60 -- files/ja/web/api/event/createevent/index.html | 32 - .../gamepad_api/using_the_gamepad_api/index.html | 347 ++++++++++ .../web/api/globaleventhandlers/onreset/index.html | 57 ++ .../api/globaleventhandlers/onresize/index.html | 78 +++ .../onselectionchange/index.html | 62 ++ .../drag_operations/index.html | 350 ++++++++++ .../multiple_items/index.html | 108 +++ .../recommended_drag_types/index.html | 228 +++++++ files/ja/web/api/htmlelement/accesskey/index.html | 23 + files/ja/web/api/installtrigger/index.html | 15 + files/ja/web/api/mediarecorder_api/index.html | 187 ------ files/ja/web/api/node/baseuriobject/index.html | 33 - files/ja/web/api/node/nodeprincipal/index.html | 21 - files/ja/web/api/page_visibility_api/index.html | 272 ++++++++ files/ja/web/api/proximity_events/index.html | 84 +++ files/ja/web/api/randomsource/index.html | 113 ---- .../readablestreamdefaultcontroller/index.html | 107 --- files/ja/web/api/slotable/index.html | 50 -- files/ja/web/api/vibration_api/index.html | 101 +++ .../api/vrdevice/cancelanimationframe/index.html | 104 --- files/ja/web/api/vrdevice/capabilities/index.html | 62 -- files/ja/web/api/vrdevice/depthfar/index.html | 99 --- files/ja/web/api/vrdevice/depthnear/index.html | 99 --- files/ja/web/api/vrdevice/displayid/index.html | 58 -- .../web/api/vrdevice/geteyeparameters/index.html | 104 --- .../web/api/vrdevice/getimmediatepose/index.html | 101 --- files/ja/web/api/vrdevice/getlayers/index.html | 53 -- files/ja/web/api/vrdevice/getpose/index.html | 101 --- files/ja/web/api/vrdevice/index.html | 129 ---- files/ja/web/api/vrdevice/isconnected/index.html | 97 --- files/ja/web/api/vrdevice/ispresenting/index.html | 97 --- .../api/vrdevice/requestanimationframe/index.html | 109 ---- .../ja/web/api/vrdevice/requestpresent/index.html | 162 ----- files/ja/web/api/vrdevice/resetpose/index.html | 105 --- .../ja/web/api/vrdevice/stageparameters/index.html | 49 -- files/ja/web/api/vrdevice/submitframe/index.html | 106 --- .../api/vrdisplay/cancelanimationframe/index.html | 104 +++ files/ja/web/api/vrdisplay/capabilities/index.html | 62 ++ files/ja/web/api/vrdisplay/depthfar/index.html | 99 +++ files/ja/web/api/vrdisplay/depthnear/index.html | 99 +++ files/ja/web/api/vrdisplay/displayid/index.html | 58 ++ .../web/api/vrdisplay/geteyeparameters/index.html | 104 +++ .../web/api/vrdisplay/getimmediatepose/index.html | 101 +++ files/ja/web/api/vrdisplay/getlayers/index.html | 53 ++ files/ja/web/api/vrdisplay/getpose/index.html | 101 +++ files/ja/web/api/vrdisplay/index.html | 129 ++++ files/ja/web/api/vrdisplay/isconnected/index.html | 97 +++ files/ja/web/api/vrdisplay/ispresenting/index.html | 97 +++ .../api/vrdisplay/requestanimationframe/index.html | 109 ++++ .../ja/web/api/vrdisplay/requestpresent/index.html | 162 +++++ files/ja/web/api/vrdisplay/resetpose/index.html | 105 +++ .../web/api/vrdisplay/stageparameters/index.html | 49 ++ files/ja/web/api/vrdisplay/submitframe/index.html | 106 +++ files/ja/web/api/vrlayer/index.html | 91 --- files/ja/web/api/vrlayer/rightbounds/index.html | 68 -- files/ja/web/api/vrlayer/source/index.html | 59 -- files/ja/web/api/vrlayerinit/index.html | 91 +++ .../ja/web/api/vrlayerinit/rightbounds/index.html | 68 ++ files/ja/web/api/vrlayerinit/source/index.html | 59 ++ .../api/webgl_api/cross-domain_textures/index.html | 16 - .../websockets_api/websockets_reference/index.html | 23 - files/ja/web/api/window.opener/index.html | 33 - files/ja/web/api/window.stop/index.html | 58 -- files/ja/web/api/window/arguments/index.html | 7 - files/ja/web/api/window/escape/index.html | 34 - files/ja/web/api/window/getattention/index.html | 25 - files/ja/web/api/window/onafterprint/index.html | 55 -- files/ja/web/api/window/onappinstalled/index.html | 57 ++ files/ja/web/api/window/onclick/index.html | 45 -- files/ja/web/api/window/oninstall/index.html | 57 -- files/ja/web/api/window/onmousedown/index.html | 48 -- files/ja/web/api/window/onmouseup/index.html | 57 -- files/ja/web/api/window/onreset/index.html | 57 -- files/ja/web/api/window/onresize/index.html | 78 --- files/ja/web/api/window/opener/index.html | 33 + files/ja/web/api/window/restore/index.html | 11 - files/ja/web/api/window/stop/index.html | 58 ++ files/ja/web/api/window/unescape/index.html | 34 - files/ja/web/api/window/url/index.html | 101 --- files/ja/web/api/windowbase64/atob/index.html | 93 --- .../base64_encoding_and_decoding/index.html | 558 ---------------- files/ja/web/api/windowbase64/index.html | 116 ---- .../windoweventhandlers/onafterprint/index.html | 55 ++ .../api/windoworworkerglobalscope/atob/index.html | 93 +++ .../windoworworkerglobalscope/caches/index.html | 82 +++ .../clearinterval/index.html | 122 ++++ .../web/api/windowtimers/clearinterval/index.html | 122 ---- files/ja/web/api/windowtimers/index.html | 119 ---- .../ja/web/api/workerglobalscope/caches/index.html | 82 --- files/ja/web/api/xmldocument/async/index.html | 45 ++ files/ja/web/api/xmlserializer/index.html | 101 +++ 175 files changed, 12067 insertions(+), 9038 deletions(-) create mode 100644 files/ja/web/api/ambient_light_events/index.html delete mode 100644 files/ja/web/api/audiobuffersourcenode/onended/index.html delete mode 100644 files/ja/web/api/audiobuffersourcenode/stop/index.html delete mode 100644 files/ja/web/api/audiocontext/createanalyser/index.html delete mode 100644 files/ja/web/api/audiocontext/createbiquadfilter/index.html delete mode 100644 files/ja/web/api/audiocontext/createbuffer/index.html delete mode 100644 files/ja/web/api/audiocontext/createbuffersource/index.html delete mode 100644 files/ja/web/api/audiocontext/createchannelmerger/index.html delete mode 100644 files/ja/web/api/audiocontext/createchannelsplitter/index.html delete mode 100644 files/ja/web/api/audiocontext/createconvolver/index.html delete mode 100644 files/ja/web/api/audiocontext/createdelay/index.html delete mode 100644 files/ja/web/api/audiocontext/createdynamicscompressor/index.html delete mode 100644 files/ja/web/api/audiocontext/creategain/index.html delete mode 100644 files/ja/web/api/audiocontext/createoscillator/index.html delete mode 100644 files/ja/web/api/audiocontext/createpanner/index.html delete mode 100644 files/ja/web/api/audiocontext/createperiodicwave/index.html delete mode 100644 files/ja/web/api/audiocontext/createscriptprocessor/index.html delete mode 100644 files/ja/web/api/audiocontext/createstereopanner/index.html delete mode 100644 files/ja/web/api/audiocontext/currenttime/index.html delete mode 100644 files/ja/web/api/audiocontext/decodeaudiodata/index.html delete mode 100644 files/ja/web/api/audiocontext/destination/index.html delete mode 100644 files/ja/web/api/audiocontext/listener/index.html delete mode 100644 files/ja/web/api/audiocontext/mozaudiochanneltype/index.html delete mode 100644 files/ja/web/api/audiocontext/onstatechange/index.html delete mode 100644 files/ja/web/api/audiocontext/samplerate/index.html delete mode 100644 files/ja/web/api/audiocontext/state/index.html create mode 100644 files/ja/web/api/audioscheduledsourcenode/onended/index.html create mode 100644 files/ja/web/api/audioscheduledsourcenode/stop/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createanalyser/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createbiquadfilter/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createbuffer/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createbuffersource/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createchannelmerger/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createchannelsplitter/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createconvolver/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createdelay/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createdynamicscompressor/index.html create mode 100644 files/ja/web/api/baseaudiocontext/creategain/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createoscillator/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createpanner/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createperiodicwave/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createscriptprocessor/index.html create mode 100644 files/ja/web/api/baseaudiocontext/createstereopanner/index.html create mode 100644 files/ja/web/api/baseaudiocontext/currenttime/index.html create mode 100644 files/ja/web/api/baseaudiocontext/decodeaudiodata/index.html create mode 100644 files/ja/web/api/baseaudiocontext/destination/index.html create mode 100644 files/ja/web/api/baseaudiocontext/listener/index.html create mode 100644 files/ja/web/api/baseaudiocontext/onstatechange/index.html create mode 100644 files/ja/web/api/baseaudiocontext/samplerate/index.html create mode 100644 files/ja/web/api/baseaudiocontext/state/index.html delete mode 100644 files/ja/web/api/canvas_api/drawing_graphics_with_canvas/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/advanced_animations/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/basic_animations/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/basic_usage/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/drawing_shapes/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/drawing_text/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/finale/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/optimizing_canvas/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/transformations/index.html create mode 100644 files/ja/web/api/canvas_api/tutorial/using_images/index.html create mode 100644 files/ja/web/api/css_painting_api/guide/index.html delete mode 100644 "files/ja/web/api/css_painting_api/\343\202\254\343\202\244\343\203\211/index.html" delete mode 100644 files/ja/web/api/cssmatrix/index.html delete mode 100644 files/ja/web/api/deviceacceleration/index.html create mode 100644 files/ja/web/api/devicemotioneventacceleration/index.html delete mode 100644 files/ja/web/api/document/activeelement/index.html delete mode 100644 files/ja/web/api/document/async/index.html delete mode 100644 files/ja/web/api/document/elementfrompoint/index.html delete mode 100644 files/ja/web/api/document/getanimations/index.html delete mode 100644 files/ja/web/api/document/getselection/index.html delete mode 100644 files/ja/web/api/document/inputencoding/index.html delete mode 100644 files/ja/web/api/document/onselectionchange/index.html delete mode 100644 files/ja/web/api/document_object_model/preface/index.html create mode 100644 files/ja/web/api/documentorshadowroot/activeelement/index.html create mode 100644 files/ja/web/api/documentorshadowroot/elementfrompoint/index.html create mode 100644 files/ja/web/api/documentorshadowroot/getanimations/index.html delete mode 100644 files/ja/web/api/documentorshadowroot/nodefrompoint/index.html delete mode 100644 files/ja/web/api/documentorshadowroot/nodesfrompoint/index.html create mode 100644 files/ja/web/api/dommatrix/index.html delete mode 100644 files/ja/web/api/element/accesskey/index.html delete mode 100644 files/ja/web/api/element/name/index.html delete mode 100644 files/ja/web/api/event/button/index.html delete mode 100644 files/ja/web/api/event/createevent/index.html create mode 100644 files/ja/web/api/gamepad_api/using_the_gamepad_api/index.html create mode 100644 files/ja/web/api/globaleventhandlers/onreset/index.html create mode 100644 files/ja/web/api/globaleventhandlers/onresize/index.html create mode 100644 files/ja/web/api/globaleventhandlers/onselectionchange/index.html create mode 100644 files/ja/web/api/html_drag_and_drop_api/drag_operations/index.html create mode 100644 files/ja/web/api/html_drag_and_drop_api/multiple_items/index.html create mode 100644 files/ja/web/api/html_drag_and_drop_api/recommended_drag_types/index.html create mode 100644 files/ja/web/api/htmlelement/accesskey/index.html create mode 100644 files/ja/web/api/installtrigger/index.html delete mode 100644 files/ja/web/api/mediarecorder_api/index.html delete mode 100644 files/ja/web/api/node/baseuriobject/index.html delete mode 100644 files/ja/web/api/node/nodeprincipal/index.html create mode 100644 files/ja/web/api/page_visibility_api/index.html create mode 100644 files/ja/web/api/proximity_events/index.html delete mode 100644 files/ja/web/api/randomsource/index.html delete mode 100644 files/ja/web/api/readablestreamdefaultcontroller/readablestreamdefaultcontroller/index.html delete mode 100644 files/ja/web/api/slotable/index.html create mode 100644 files/ja/web/api/vibration_api/index.html delete mode 100644 files/ja/web/api/vrdevice/cancelanimationframe/index.html delete mode 100644 files/ja/web/api/vrdevice/capabilities/index.html delete mode 100644 files/ja/web/api/vrdevice/depthfar/index.html delete mode 100644 files/ja/web/api/vrdevice/depthnear/index.html delete mode 100644 files/ja/web/api/vrdevice/displayid/index.html delete mode 100644 files/ja/web/api/vrdevice/geteyeparameters/index.html delete mode 100644 files/ja/web/api/vrdevice/getimmediatepose/index.html delete mode 100644 files/ja/web/api/vrdevice/getlayers/index.html delete mode 100644 files/ja/web/api/vrdevice/getpose/index.html delete mode 100644 files/ja/web/api/vrdevice/index.html delete mode 100644 files/ja/web/api/vrdevice/isconnected/index.html delete mode 100644 files/ja/web/api/vrdevice/ispresenting/index.html delete mode 100644 files/ja/web/api/vrdevice/requestanimationframe/index.html delete mode 100644 files/ja/web/api/vrdevice/requestpresent/index.html delete mode 100644 files/ja/web/api/vrdevice/resetpose/index.html delete mode 100644 files/ja/web/api/vrdevice/stageparameters/index.html delete mode 100644 files/ja/web/api/vrdevice/submitframe/index.html create mode 100644 files/ja/web/api/vrdisplay/cancelanimationframe/index.html create mode 100644 files/ja/web/api/vrdisplay/capabilities/index.html create mode 100644 files/ja/web/api/vrdisplay/depthfar/index.html create mode 100644 files/ja/web/api/vrdisplay/depthnear/index.html create mode 100644 files/ja/web/api/vrdisplay/displayid/index.html create mode 100644 files/ja/web/api/vrdisplay/geteyeparameters/index.html create mode 100644 files/ja/web/api/vrdisplay/getimmediatepose/index.html create mode 100644 files/ja/web/api/vrdisplay/getlayers/index.html create mode 100644 files/ja/web/api/vrdisplay/getpose/index.html create mode 100644 files/ja/web/api/vrdisplay/index.html create mode 100644 files/ja/web/api/vrdisplay/isconnected/index.html create mode 100644 files/ja/web/api/vrdisplay/ispresenting/index.html create mode 100644 files/ja/web/api/vrdisplay/requestanimationframe/index.html create mode 100644 files/ja/web/api/vrdisplay/requestpresent/index.html create mode 100644 files/ja/web/api/vrdisplay/resetpose/index.html create mode 100644 files/ja/web/api/vrdisplay/stageparameters/index.html create mode 100644 files/ja/web/api/vrdisplay/submitframe/index.html delete mode 100644 files/ja/web/api/vrlayer/index.html delete mode 100644 files/ja/web/api/vrlayer/rightbounds/index.html delete mode 100644 files/ja/web/api/vrlayer/source/index.html create mode 100644 files/ja/web/api/vrlayerinit/index.html create mode 100644 files/ja/web/api/vrlayerinit/rightbounds/index.html create mode 100644 files/ja/web/api/vrlayerinit/source/index.html delete mode 100644 files/ja/web/api/webgl_api/cross-domain_textures/index.html delete mode 100644 files/ja/web/api/websockets_api/websockets_reference/index.html delete mode 100644 files/ja/web/api/window.opener/index.html delete mode 100644 files/ja/web/api/window.stop/index.html delete mode 100644 files/ja/web/api/window/arguments/index.html delete mode 100644 files/ja/web/api/window/escape/index.html delete mode 100644 files/ja/web/api/window/getattention/index.html delete mode 100644 files/ja/web/api/window/onafterprint/index.html create mode 100644 files/ja/web/api/window/onappinstalled/index.html delete mode 100644 files/ja/web/api/window/onclick/index.html delete mode 100644 files/ja/web/api/window/oninstall/index.html delete mode 100644 files/ja/web/api/window/onmousedown/index.html delete mode 100644 files/ja/web/api/window/onmouseup/index.html delete mode 100644 files/ja/web/api/window/onreset/index.html delete mode 100644 files/ja/web/api/window/onresize/index.html create mode 100644 files/ja/web/api/window/opener/index.html delete mode 100644 files/ja/web/api/window/restore/index.html create mode 100644 files/ja/web/api/window/stop/index.html delete mode 100644 files/ja/web/api/window/unescape/index.html delete mode 100644 files/ja/web/api/window/url/index.html delete mode 100644 files/ja/web/api/windowbase64/atob/index.html delete mode 100644 files/ja/web/api/windowbase64/base64_encoding_and_decoding/index.html delete mode 100644 files/ja/web/api/windowbase64/index.html create mode 100644 files/ja/web/api/windoweventhandlers/onafterprint/index.html create mode 100644 files/ja/web/api/windoworworkerglobalscope/atob/index.html create mode 100644 files/ja/web/api/windoworworkerglobalscope/caches/index.html create mode 100644 files/ja/web/api/windoworworkerglobalscope/clearinterval/index.html delete mode 100644 files/ja/web/api/windowtimers/clearinterval/index.html delete mode 100644 files/ja/web/api/windowtimers/index.html delete mode 100644 files/ja/web/api/workerglobalscope/caches/index.html create mode 100644 files/ja/web/api/xmldocument/async/index.html create mode 100644 files/ja/web/api/xmlserializer/index.html (limited to 'files/ja/web/api') diff --git a/files/ja/web/api/ambient_light_events/index.html b/files/ja/web/api/ambient_light_events/index.html new file mode 100644 index 0000000000..be70ad2612 --- /dev/null +++ b/files/ja/web/api/ambient_light_events/index.html @@ -0,0 +1,68 @@ +--- +title: Ambient Light Events +slug: WebAPI/Using_Light_Events +tags: + - Ambient Light +translation_of: Web/API/Ambient_Light_Events +--- +
{{DefaultAPISidebar("Ambient Light Events")}}{{SeeCompatTable}}
+ +

ambient light event は、光の強さの変化をウェブページやアプリケーションに気づかせるのに便利な手段です。これによりユーザーインターフェイスのコントラストを変えたり写真を撮るために必要な露出時間を変えたりするなど、ウェブページやアプリケーションが光量の変化に対応できるようになります。

+ +

Light Event

+ +

端末の光センサーが光量の変化を検出すると、それをブラウザーに通知します。ブラウザーがその通知を受け取ると、正確な光の強度に関する情報を提供する {{domxref("DeviceLightEvent")}} イベントを発生させます。

+ +

このイベントは {{domxref("EventTarget.addEventListener","addEventListener")}} メソッド (イベント名 {{event("devicelight")}} を使用) を使用するか、イベントハンドラーを {{domxref("window.ondevicelight")}} プロパティに接続することにより、 window オブジェクトレベルで取得できます。

+ +

イベントを取得するとイベントオブジェクトの {{domxref("DeviceLightEvent.value")}} プロパティを通して、{{interwiki("wikipedia", "ルクス")}}で表した照度にアクセスできます。

+ +

+ +
if ('ondevicelight' in window) {
+  window.addEventListener('devicelight', function(event) {
+    var body = document.querySelector('body');
+    if (event.value < 50) {
+      body.classList.add('darklight');
+      body.classList.remove('brightlight');
+    } else {
+      body.classList.add('brightlight');
+      body.classList.remove('darklight');
+    }
+  });
+} else {
+  console.log('devicelight event not supported');
+}
+
+ +

仕様書

+ + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName("AmbientLight", "", "Ambient Light Events")}}{{Spec2("AmbientLight")}}初回定義
+ +

ブラウザーの対応

+ + + +

{{Compat("api.DeviceLightEvent")}}

+ +

関連情報

+ + diff --git a/files/ja/web/api/audiobuffersourcenode/onended/index.html b/files/ja/web/api/audiobuffersourcenode/onended/index.html deleted file mode 100644 index 22f8b05ba3..0000000000 --- a/files/ja/web/api/audiobuffersourcenode/onended/index.html +++ /dev/null @@ -1,108 +0,0 @@ ---- -title: AudioBufferSourceNode.onended -slug: Web/API/AudioBufferSourceNode/onended -translation_of: Web/API/AudioScheduledSourceNode/onended -translation_of_original: Web/API/AudioBufferSourceNode/onended ---- -

{{ APIRef("AudioBufferSourceNode") }}

- -
AudioBufferSourceNodeの onended イベントハンドラーは{{event("ended_(Web_Audio)", "ended")}} イベントに関するコ−ルバック関数を格納します。これによりオーディオトラックの再生終了時に実行するコードを設定することができます。
- -
-

: onended ハンドラーは loop プロパティーがtrueに設定されている場合はオーディオが再生終了することが無いので効果がありません。このような場合にこの機能を有効にするには {{ domxref("AudioBufferSourceNode.stop()") }} を使用してください。

-
- -

構文

- -
var source = audioCtx.createBufferSource();
-source.onended = function() { ... };
-
- -

用例

- -
source.start();
-source.onended = function() {
-  console.log('Your audio has finished playing');
-}
- -

プロパティ

- -

有りません。

- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBufferSourceNode-onended', 'onended')}}{{Spec2('Web Audio API')}} 
- -

ブラウザー互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}23{{CompatNo}}15 {{property_prefix("webkit")}}
- 22 (unprefixed)
6 {{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
-
- -

関連情報

- - diff --git a/files/ja/web/api/audiobuffersourcenode/stop/index.html b/files/ja/web/api/audiobuffersourcenode/stop/index.html deleted file mode 100644 index 2163d86379..0000000000 --- a/files/ja/web/api/audiobuffersourcenode/stop/index.html +++ /dev/null @@ -1,120 +0,0 @@ ---- -title: AudioBufferSourceNode.stop() -slug: Web/API/AudioBufferSourceNode/stop -translation_of: Web/API/AudioScheduledSourceNode/stop -translation_of_original: Web/API/AudioBufferSourceNode/stop ---- -

{{ APIRef("Web Audio API") }}

- -
-

インターフェースのstop()メソッドは、オーディオバッファの再生を停止させるために使われます。

-
- -

構文

- -
var source = audioCtx.createBufferSource();
-source.stop(when);
-
- -

- -

最も単純なオーディオバッファ再生の停止方法—この場合は何もパラメータを指定する必要はありません。

- -
source.stop();
- -

しばらく後に停止させたい場合は、引数として秒数を指定します。

- -
source.stop(3);
- -
-

注: stop()の使い方の完全な例はAudioContext.decodeAudioDataを参照してください。コードをすぐに実行することや、ソースコードを閲覧することもできます。

-
- -

引数

- -
-
when
-
whenパラメータは、再生をいつ停止するかを決定します。指定の時間を経過すると、再生はすぐに停止します。このメソッドが2回以上呼ばれると、例外が発生します
-
- -

戻り値

- -

なし

- -

使用

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBufferSourceNode-stop-void-double-when', 'stop()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}23{{CompatNo}}15 {{property_prefix("webkit")}}
- 22 (unprefixed)
6 {{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createanalyser/index.html b/files/ja/web/api/audiocontext/createanalyser/index.html deleted file mode 100644 index c186d1029c..0000000000 --- a/files/ja/web/api/audiocontext/createanalyser/index.html +++ /dev/null @@ -1,154 +0,0 @@ ---- -title: AudioContext.createAnalyser() -slug: Web/API/AudioContext/createAnalyser -translation_of: Web/API/BaseAudioContext/createAnalyser ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateAnalyser()メソッドは、音声の時間と周波数を解析する{{ domxref("AnalyserNode") }}を生成します。これはデータの可視化などで使えます。

-
- -
-

注: このノードの詳しい説明は、{{domxref("AnalyserNode")}}のページを参照してください。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var analyser = audioCtx.createAnalyser();
- -

戻り値

- -

{{domxref("AnalyserNode")}}

- -

- -

次のサンプルでは、基本的なAudioContextAnalyserNodeの生成、requestAnimationFrame()による時間データの周期的な収集と「オシロスコープのように」現在の音声を出力する方法を示しています。より完全な例と情報は、Voice-change-O-maticデモ(app.jsの128–205行目)を参照してください。

- -
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-var analyser = audioCtx.createAnalyser();
-
-  ...
-
-analyser.fftSize = 2048;
-var bufferLength = analyser.fftSize;
-var dataArray = new Uint8Array(bufferLength);
-analyser.getByteTimeDomainData(dataArray);
-
-// 現在の音のオシロスコープのように描く
-
-function draw() {
-
-      drawVisual = requestAnimationFrame(draw);
-
-      analyser.getByteTimeDomainData(dataArray);
-
-      canvasCtx.fillStyle = 'rgb(200, 200, 200)';
-      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
-
-      canvasCtx.lineWidth = 2;
-      canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
-
-      canvasCtx.beginPath();
-
-      var sliceWidth = WIDTH * 1.0 / bufferLength;
-      var x = 0;
-
-      for(var i = 0; i < bufferLength; i++) {
-
-        var v = dataArray[i] / 128.0;
-        var y = v * HEIGHT/2;
-
-        if(i === 0) {
-          canvasCtx.moveTo(x, y);
-        } else {
-          canvasCtx.lineTo(x, y);
-        }
-
-        x += sliceWidth;
-      }
-
-      canvasCtx.lineTo(canvas.width, canvas.height/2);
-      canvasCtx.stroke();
-    };
-
-    draw();
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createAnalyser-AnalyserNode', 'createAnalyser()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createbiquadfilter/index.html b/files/ja/web/api/audiocontext/createbiquadfilter/index.html deleted file mode 100644 index 136557bea5..0000000000 --- a/files/ja/web/api/audiocontext/createbiquadfilter/index.html +++ /dev/null @@ -1,126 +0,0 @@ ---- -title: AudioContext.createBiquadFilter() -slug: Web/API/AudioContext/createBiquadFilter -translation_of: Web/API/BaseAudioContext/createBiquadFilter ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateBiquadFilter()メソッドはいくつかの一般的なフィルタを設定できる二次フィルターを表す{{ domxref("BiquadFilterNode") }}を生成します。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var biquadFilter = audioCtx.createBiquadFilter();
- -

戻り値

- -

{{domxref("BiquadFilterNode")}}

- -

- -

次の例はAudioContextのBiquadFilterNodeの使い方を説明しています。完全に動作する例は、voice-change-o-maticデモ(ソースコードもあります)を参照してください。

- -
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-
-// このアプリで使う2つのノードを設定する
-var analyser = audioCtx.createAnalyser();
-var distortion = audioCtx.createWaveShaper();
-var gainNode = audioCtx.createGain();
-var biquadFilter = audioCtx.createBiquadFilter();
-var convolver = audioCtx.createConvolver();
-
-// ノードを接続する
-
-source = audioCtx.createMediaStreamSource(stream);
-source.connect(analyser);
-analyser.connect(distortion);
-distortion.connect(biquadFilter);
-biquadFilter.connect(convolver);
-convolver.connect(gainNode);
-gainNode.connect(audioCtx.destination);
-
-// 二次フィルターで操作する
-
-biquadFilter.type = "lowshelf";
-biquadFilter.frequency.value = 1000;
-biquadFilter.gain.value = 25;
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createBiquadFilter-BiquadFilterNode', 'createBiquadFilter()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0 {{property_prefix("webkit")}}
- 22
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参照

- - diff --git a/files/ja/web/api/audiocontext/createbuffer/index.html b/files/ja/web/api/audiocontext/createbuffer/index.html deleted file mode 100644 index e94a5a18be..0000000000 --- a/files/ja/web/api/audiocontext/createbuffer/index.html +++ /dev/null @@ -1,174 +0,0 @@ ---- -title: AudioContext.createBuffer() -slug: Web/API/AudioContext/createBuffer -translation_of: Web/API/BaseAudioContext/createBuffer ---- -

{{ APIRef("Web Audio API") }}

- -
-

インターフェースのcreateBuffer()メソッドは、新規の空の{{ domxref("AudioBuffer") }}オブジェクトを生成します。そこにデータを書きこめば、{{ domxref("AudioBufferSourceNode") }}で再生できます。

-
- -
-

Note: createBuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createBuffer() was blocking other code execution. The asynchronous method decodeAudioData() does the same thing — takes compressed audio, say, an MP3 file, and directly gives you back an {{ domxref("AudioBuffer") }} that you can then set to play via in an {{ domxref("AudioBufferSourceNode") }}. For simple uses like playing an MP3, decodeAudioData() is what you should be using.

-
- -

構文

- -
var audioCtx = new AudioContext();
-var buffer = audioCtx.createBuffer(numOfChannels, length, sampleRate);
- -

引数

- -
-

Note: For an in-depth explanation of how audio buffers work, and what these parameters mean, read Audio buffers: frames, samples and channels from our Basic concepts guide.

-
- -
-
numOfChannels
-
integerで現されたバッファのチャンネルの数。実装は少なくとも32チャンネルに対応している
-
length
-
integerで表されたバッファのサンプルフレームの数
-
sampleRate
-
1秒あたりのサンプルフレームの数。実装は少なくとも22050から96000の範囲に対応している
-
- -

戻り値

- -

{{domxref("AudioBuffer")}}

- -

- -

まずは2つの小さな例で、引数をどのように設定するかを説明します:

- -
var audioCtx = new AudioContext();
-var buffer = audioCtx.createBuffer(2, 22050, 44100);
- -

このようにすると、ステレオ(2チャンネル)のバッファが生成され、44100Hz(極めて一般的で、多くの通常のサウンドカードはこのレートで動作します)のAudioContextで再生すると、0.5秒間(22050フレーム / 44100Hz )となります。

- -
var audioCtx = new AudioContext();
-var buffer = audioCtx.createBuffer(1, 22050, 22050);
- -

このようにすると、モノラル(1チャンネル)のバッファが生成され、44100HzのAudioContextで再生すると、自動的に44100Hzに再サンプリングされ(そして結果として44100フレームとなり)、1秒間(44100フレーム / 44100Hz)となります。

- -
-

Note: audio resampling is very similar to image resizing: say you've got a 16 x 16 image, but you want it to fill a 32x32 area: you resize (resample) it. the result has less quality (it can be blurry or edgy, depending on the resizing algorithm), but it works, and the resized image takes up less space. Resampled audio is exactly the same — you save space, but in practice you will be unable to properly reproduce high frequency content (treble sound).

-
- -

次は少し複雑なcreateBuffer()の例を見てみましょう。2秒間のバッファを生成し、ホワイトノイズを書き込み、{{ domxref("AudioBufferSourceNode") }}で再生します。コードをすぐに実行することや、ソースコードを閲覧することもできます。

- -
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-var button = document.querySelector('button');
-var pre = document.querySelector('pre');
-var myScript = document.querySelector('script');
-
-pre.innerHTML = myScript.innerHTML;
-
-// ステレオ
-var channels = 2;
-// AudioContextのサンプルレートで2秒間の空のステレオバッファを生成する
-var frameCount = audioCtx.sampleRate * 2.0;
-
-var myArrayBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);
-
-button.onclick = function() {
-  // バッファにホワイトノイズを書き込む;
-  // 単なる-1.0から1.0の間の乱数の値である
-  for (var channel = 0; channel < channels; channel++) {
-   // 実際のデータの配列を得る
-   var nowBuffering = myArrayBuffer.getChannelData(channel);
-   for (var i = 0; i < frameCount; i++) {
-     // Math.random()は[0; 1.0]である
-     // 音声は[-1.0; 1.0]である必要がある
-     nowBuffering[i] = Math.random() * 2 - 1;
-   }
-  }
-
-  // AudioBufferSourceNodeを得る
-  // これはAudioBufferを再生するときに使うAudioNodeである
-  var source = audioCtx.createBufferSource();
-  // AudioBufferSourceNodeにバッファを設定する
-  source.buffer = myArrayBuffer;
-  // AudioBufferSourceNodeを出力先に接続すると音声が聞こえるようになる
-  source.connect(audioCtx.destination);
-  // 音源の再生を始める
-  source.start();
-}
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createBuffer-AudioBuffer-unsigned-long-numberOfChannels-unsigned-long-length-float-sampleRate', 'createBuffer()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0 {{property_prefix("webkit")}}
- 22
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createbuffersource/index.html b/files/ja/web/api/audiocontext/createbuffersource/index.html deleted file mode 100644 index 24f65061c6..0000000000 --- a/files/ja/web/api/audiocontext/createbuffersource/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: AudioContext.createBufferSource() -slug: Web/API/AudioContext/createBufferSource -translation_of: Web/API/BaseAudioContext/createBufferSource ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateBufferSource()メソッドは、{{ domxref("AudioBuffer") }}オブジェクトに書き込まれた音声データを再生する{{ domxref("AudioBufferSourceNode") }}を生成します。{{ domxref("AudioBuffer") }}は{{domxref("AudioContext.createBuffer")}}を使った場合や、{{domxref("AudioContext.decodeAudioData")}}でオーディオトラックをデコードしたときに生成されます。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var source = audioCtx.createBufferSource();
- -

戻り値

- -

{{domxref("AudioBufferSourceNode")}}

- -

- -

この例では、2秒間のバッファを生成し、ホワイトノイズを書き込み、{{ domxref("AudioBufferSourceNode") }}で再生します。コメントは何をしているかを簡単に説明しています。

- -
-

注: コードの実行ソースの閲覧もできます。

-
- -
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-var button = document.querySelector('button');
-var pre = document.querySelector('pre');
-var myScript = document.querySelector('script');
-
-pre.innerHTML = myScript.innerHTML;
-
-// ステレオ
-var channels = 2;
-// AudioContextのサンプルレートで2秒間の空のステレオバッファを生成する
-var frameCount = audioCtx.sampleRate * 2.0;
-
-var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
-
-button.onclick = function() {
-  // バッファにホワイトノイズを書き込む;
-  // 単なる-1.0から1.0の間の乱数の値である
-  for (var channel = 0; channel < channels; channel++) {
-   // 実際のデータの配列を得る
-   var nowBuffering = myArrayBuffer.getChannelData(channel);
-   for (var i = 0; i < frameCount; i++) {
-     // Math.random()は[0; 1.0]である
-     // 音声は[-1.0; 1.0]である必要がある
-     nowBuffering[i] = Math.random() * 2 - 1;
-   }
-  }
-
-  // AudioBufferSourceNodeを得る
-  // これはAudioBufferを再生するときに使うAudioNodeである
-  var source = audioCtx.createBufferSource();
-  // AudioBufferSourceNodeにバッファを設定する
-  source.buffer = myArrayBuffer;
-  // AudioBufferSourceNodeを出力先に接続すると音声が聞こえるようになる
-  source.connect(audioCtx.destination);
-  // 音源の再生を始める
-  source.start();
-}
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createBufferSource-AudioBufferSourceNode', 'createBufferSource()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createchannelmerger/index.html b/files/ja/web/api/audiocontext/createchannelmerger/index.html deleted file mode 100644 index e79b116642..0000000000 --- a/files/ja/web/api/audiocontext/createchannelmerger/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: AudioContext.createChannelMerger() -slug: Web/API/AudioContext/createChannelMerger -translation_of: Web/API/BaseAudioContext/createChannelMerger ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateChannelMerger()メソッドは、複数のオーディオストリームを1つに混合する{{domxref("ChannelMergerNode")}}を生成します。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var merger = audioCtx.createChannelMerger(numberOfInputs);
- -

引数

- -
-
numberOfInputs
-
入力オーディオストリームのチャンネルの数。指定がない場合は6になる。
-
- -

戻り値

- -

{{domxref("ChannelMergerNode")}}

- -

- -

この例ではステレオトラックを分け、左右のチャンネルをそれぞれ別に処理する方法を示しています。これを使うためには、{{domxref("AudioNode.connect(AudioNode)") }}メソッドの2番目と3番目の引数を使い、接続元と接続先のチャンネルの番号を指定する必要があります。

- -
var ac = new AudioContext();
-ac.decodeAudioData(someStereoBuffer, function(data) {
- var source = ac.createBufferSource();
- source.buffer = data;
- var splitter = ac.createChannelSplitter(2);
- source.connect(splitter);
- var merger = ac.createChannelMerger(2);
-
- // 左チャンネルのボリュームのみ小さくする
- var gain = ac.createGain();
- gain.value = 0.5;
- splitter.connect(gain, 0);
-
- // splitterをmergerの2番目の入力にして戻す
- // ここではチャンネルを入れ替えることで、ステレオ音声の左右を逆にしている
- gain.connect(merger, 0, 1);
- splitter.connect(merger, 1, 0);
-
- var dest = ac.createMediaStreamDestination();
-
- // ChannelMergerNodeを使ったのでステレオのMediaStreamとなった
- // webオーディオグラフのWebRTCやMediaRecorderなどに渡す
- merger.connect(dest);
-});
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createChannelMerger-ChannelMergerNode-unsigned-long-numberOfInputs', 'createChannelMerger()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参照

- - diff --git a/files/ja/web/api/audiocontext/createchannelsplitter/index.html b/files/ja/web/api/audiocontext/createchannelsplitter/index.html deleted file mode 100644 index 07444c49d0..0000000000 --- a/files/ja/web/api/audiocontext/createchannelsplitter/index.html +++ /dev/null @@ -1,133 +0,0 @@ ---- -title: AudioContext.createChannelSplitter() -slug: Web/API/AudioContext/createChannelSplitter -translation_of: Web/API/BaseAudioContext/createChannelSplitter ---- -

{{ APIRef("Web Audio API") }}

- -
-

インターフェースのcreateChannelSplitter()メソッドは、オーディオストリームを個別に処理するためにチャンネルを分離する{{domxref("ChannelSplitterNode")}}を生成します。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var splitter = audioCtx.createChannelSplitter(numberOfOutputs);
- -

引数

- -
-
numberOfOutputs
-
入力オーディオストリームを分ける数。引数の指定がなければ6。
-
- -

Returns

- -

{{domxref("ChannelSplitterNode")}}

- -

- -

この例ではステレオトラックを分け、左右のチャンネルをそれぞれ別に処理する方法を示しています。これを使うためには、{{domxref("AudioNode.connect(AudioNode)") }}メソッドの2番目と3番目の引数を使い、接続元と接続先のチャンネルの番号を指定する必要があります。

- -
var ac = new AudioContext();
-ac.decodeAudioData(someStereoBuffer, function(data) {
- var source = ac.createBufferSource();
- source.buffer = data;
- var splitter = ac.createChannelSplitter(2);
- source.connect(splitter);
- var merger = ac.createChannelMerger(2);
-
- // 左チャンネルのボリュームのみ小さくする
- var gain = ac.createGain();
- gain.value = 0.5;
- splitter.connect(gain, 0);
-
- // splitterをmergerの2番目の入力にして戻す
- // ここではチャンネルを入れ替えることで、ステレオ音声の左右を逆にしている
- gain.connect(merger, 0, 1);
- splitter.connect(merger, 1, 0);
-
- var dest = ac.createMediaStreamDestination();
-
- // ChannelMergerNodeを使ったのでステレオのMediaStreamとなった
- // webオーディオグラフのWebRTCやMediaRecorderなどに渡す
- merger.connect(dest);
-});
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createChannelSplitter-ChannelSplitterNode-unsigned-long-numberOfOutputs', 'createChannelSplitter()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createconvolver/index.html b/files/ja/web/api/audiocontext/createconvolver/index.html deleted file mode 100644 index ae5acf59c8..0000000000 --- a/files/ja/web/api/audiocontext/createconvolver/index.html +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: AudioContext.createConvolver() -slug: Web/API/AudioContext/createConvolver -translation_of: Web/API/BaseAudioContext/createConvolver ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateConvolver()メソッドは、音声にリバーブ効果などを適用する{{ domxref("ConvolverNode") }}を生成します。詳細はspec definition of Convolutionを参照してください。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var convolver = audioCtx.createConvolver();
- -

戻り値

- -

{{domxref("ConvolverNode")}}

- -

- -

次の例は畳み込みノードを生成する基礎的なAudioContextの使い方を示しています。まず、畳み込み(インパルス応答)が適用される音声が書き込まれたAudioBufferを生成し、そしてそれに畳み込みを適用します。例ではコンサートホールの群集の短い音声を使っていて、深く音響したリバーブ効果がかかっています。

- -

例と情報の応用は、Voice-change-O-maticデモ(ソースコード)をチェックしてください。

- -
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-var convolver = audioCtx.createConvolver();
-
-  ...
-
-// XHRで畳み込みノードのための音声トラックを得る
-
-var soundSource, concertHallBuffer;
-
-ajaxRequest = new XMLHttpRequest();
-ajaxRequest.open('GET', 'concert-crowd.ogg', true);
-ajaxRequest.responseType = 'arraybuffer';
-
-ajaxRequest.onload = function() {
-  var audioData = ajaxRequest.response;
-  audioCtx.decodeAudioData(audioData, function(buffer) {
-      concertHallBuffer = buffer;
-      soundSource = audioCtx.createBufferSource();
-      soundSource.buffer = concertHallBuffer;
-    }, function(e){"Error with decoding audio data" + e.err});
-}
-
-ajaxRequest.send();
-
-  ...
-
-convolver.buffer = concertHallBuffer;
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createConvolver-ConvolverNode', 'createConvolver()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createdelay/index.html b/files/ja/web/api/audiocontext/createdelay/index.html deleted file mode 100644 index 709a8a375b..0000000000 --- a/files/ja/web/api/audiocontext/createdelay/index.html +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: AudioContext.createDelay() -slug: Web/API/AudioContext/createDelay -translation_of: Web/API/BaseAudioContext/createDelay ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateDelay()メソッドは、入力音声信号を一定時間遅らせる{{domxref("DelayNode")}}を生成します。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var synthDelay = audioCtx.createDelay(maxDelayTime);
- -

引数

- -
-
maxDelayTime
-
音声信号の最大遅れ時間の秒数。デフォルトは0
-
- -

戻り値

- -

{{domxref("DelayNode")}}

- -

- -

ループする3つの異なる簡単な例を用意しました。create-delayを見てください。(ソースコードも閲覧できます。)ただPlayボタンを押すと、ループはすぐ始まります。スライダーを右に動かしPlayボタンを押すと、待ち時間が挿入され、少し時間が過ぎるまで再生が始まりません。

- -
var AudioContext = window.AudioContext || window.webkitAudioContext;
-var audioCtx = new AudioContext();
-
-var synthDelay = audioCtx.createDelay(5.0);
-
-  ...
-
-var synthSource;
-
-playSynth.onclick = function() {
-  synthSource = audioCtx.createBufferSource();
-  synthSource.buffer = buffers[2];
-  synthSource.loop = true;
-  synthSource.start();
-  synthSource.connect(synthDelay);
-  synthDelay.connect(destination);
-  this.setAttribute('disabled', 'disabled');
-}
-
-stopSynth.onclick = function() {
-  synthSource.disconnect(synthDelay);
-  synthDelay.disconnect(destination);
-  synthSource.stop();
-  playSynth.removeAttribute('disabled');
-}
-
-...
-
-var delay1;
-rangeSynth.oninput = function() {
-delay1 = rangeSynth.value;
-synthDelay.delayTime.value = delay1;
-}
-
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createDelay-DelayNode-double-maxDelayTime', 'createDelay()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参照

- - diff --git a/files/ja/web/api/audiocontext/createdynamicscompressor/index.html b/files/ja/web/api/audiocontext/createdynamicscompressor/index.html deleted file mode 100644 index 2fa5ca43ed..0000000000 --- a/files/ja/web/api/audiocontext/createdynamicscompressor/index.html +++ /dev/null @@ -1,138 +0,0 @@ ---- -title: AudioContext.createDynamicsCompressor() -slug: Web/API/AudioContext/createDynamicsCompressor -translation_of: Web/API/BaseAudioContext/createDynamicsCompressor ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateDynamicsCompressor()メソッドは、音声信号にコンプレッサーを適用する{{domxref("DynamicsCompressorNode")}}を生成します。

-
- -

コンプレッサーは、音声信号の最大部分の音量を小さくし、最小部分の音量を大きくします。一般的に、より大きく、豊かで、高密度な音になります。これはゲームや音楽アプリケーションでたくさんの別々の音を同時に再生する場合に特に重要です。このような場合、全体の音量の操作したり、出力音声のクリッピング(ひずみ)を避けたいはずです。

- -

構文

- -
var audioCtx = new AudioContext();
-var compressor = audioCtx.createDynamicsCompressor();
- -

戻り値

- -

{{domxref("DynamicsCompressorNode")}}

- -

- -

音声トラックにコンプレッサーを追加するためにcreateDynamicsCompressor()を使う簡単なデモコードです。より完全なサンプルは、basic Compressor example (ソースコードの閲覧)を参照してください。

- -
// MediaElementAudioSourceNodeを生成する
-// そこにHTMLMediaElementを入れる
-var source = audioCtx.createMediaElementSource(myAudio);
-
-// コンプレッサーノードを生成する
-var compressor = audioCtx.createDynamicsCompressor();
-compressor.threshold.value = -50;
-compressor.knee.value = 40;
-compressor.ratio.value = 12;
-compressor.reduction.value = -20;
-compressor.attack.value = 0;
-compressor.release.value = 0.25;
-
-// AudioBufferSourceNodeを行き先(destination)につなげる
-source.connect(audioCtx.destination);
-
-button.onclick = function() {
-  var active = button.getAttribute('data-active');
-  if(active == 'false') {
-    button.setAttribute('data-active', 'true');
-    button.innerHTML = 'Remove compression';
-
-    source.disconnect(audioCtx.destination);
-    source.connect(compressor);
-    compressor.connect(audioCtx.destination);
-  } else if(active == 'true') {
-    button.setAttribute('data-active', 'false');
-    button.innerHTML = 'Add compression';
-
-    source.disconnect(compressor);
-    compressor.disconnect(audioCtx.destination);
-    source.connect(audioCtx.destination);
-  }
-}
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createDynamicsCompressor-DynamicsCompressorNode', 'createDynamicsCompressor()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/creategain/index.html b/files/ja/web/api/audiocontext/creategain/index.html deleted file mode 100644 index c536a0621c..0000000000 --- a/files/ja/web/api/audiocontext/creategain/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: AudioContext.createGain() -slug: Web/API/AudioContext/createGain -translation_of: Web/API/BaseAudioContext/createGain ---- -

{{ APIRef("Web Audio API") }}

- -
-

インターフェースのcreateGain()メソッドは、音声の全体的なボリュームを操作する{{ domxref("GainNode") }}を生成します。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var gainNode = audioCtx.createGain();
- -

戻り値

- -

{{domxref("GainNode")}}

- -

- -

次の例では{{domxref("AudioContext")}}、GainNodeを生成する基本的な使い方を示しています。生成したGainNodeは、Muteボタンを押したときにgainプロパティの値を設定することで、無音・無音解除するために使っています。完全な例と情報は、Voice-change-O-maticデモ(ソースの閲覧)をクリックしてください。

- -
<div>
-  <a class="mute">Mute button</a>
-</div>
- -
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-var gainNode = audioCtx.createGain();
-var mute = document.querySelector('.mute');
-
-source.connect(gainNode);
-gainNode.connect(audioCtx.destination);
-
-  ...
-
-mute.onclick = voiceMute;
-
-function voiceMute() {
-  if(mute.id == "") {
-    gainNode.gain.value = 0;
-    mute.id = "activated";
-    mute.innerHTML = "Unmute";
-  } else {
-    gainNode.gain.value = 1;
-    mute.id = "";
-    mute.innerHTML = "Mute";
-  }
-}
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createGain-GainNode', 'createGain()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createoscillator/index.html b/files/ja/web/api/audiocontext/createoscillator/index.html deleted file mode 100644 index e971400f5d..0000000000 --- a/files/ja/web/api/audiocontext/createoscillator/index.html +++ /dev/null @@ -1,111 +0,0 @@ ---- -title: AudioContext.createOscillator() -slug: Web/API/AudioContext/createOscillator -translation_of: Web/API/BaseAudioContext/createOscillator ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateOscillator()メソッドは、周期的な波形を発生源である{{ domxref("OscillatorNode") }}を生成します。これは基礎的な音源です。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var oscillator = audioCtx.createOscillator();
- -

戻り値

- -

{{domxref("OscillatorNode")}}

- -

- -

次の例はオシレーターノードを生成する基礎的なAudioContextの使い方を示しています。例と情報の応用は、Voice-change-O-maticデモ(ソースコード)をチェックしてください。また、{{ domxref("OscillatorNode") }}にはより詳細な情報があります。

- -
// webオーディオAPIコンテキストを生成する
-var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-
-// オシレーターノードを生成する
-var oscillator = audioCtx.createOscillator();
-
-oscillator.type = 'square';
-oscillator.frequency.value = 3000; // 値はHz(ヘルツ)
-oscillator.start();
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createOscillator-OscillatorNode', 'createOscillator')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createpanner/index.html b/files/ja/web/api/audiocontext/createpanner/index.html deleted file mode 100644 index 1b30c60a03..0000000000 --- a/files/ja/web/api/audiocontext/createpanner/index.html +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: AudioContext.createPanner() -slug: Web/API/AudioContext/createPanner -translation_of: Web/API/BaseAudioContext/createPanner ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }} の createPanner() を利用すると、新しい {{domxref("PannerNode")}} を作成できます。これは空間音響を実現するために利用されます。

- -

作成された PannerNode は、音声の聴取者の位置と向きから空間的な再生を行います。聴取者の位置と向きは、 {{domxref("AudioListener") }} オブジェクトとして表現され、{{domxref("AudioContext.listener") }} で参照できます。

-
- -

記法

- -
var audioCtx = new AudioContext();
-var panner = audioCtx.createPanner();
- -

返り値

- -

{{domxref("PannerNode")}} を返します。

- -

利用例

- -

以下の例では、createPanner() メソッドの利用方法と、 {{domxref("AudioListener")}} と{{domxref("PannerNode")}} による空間音響のコントロール方法について解説します。一般的には、聴取者と音源の 3 次元空間上での位置を決め、アプリケーションの動きに合わせてそれらを更新することになります。これを利用することで、キャラクターが世界の中を動き回るようなゲームで、近づくと聞こえ、遠ざかると聞こえなくなるステレオを実現できます。 以下の例では moveRight()moveLeft()、PositionPanner() などを利用して、位置をコントロールしています。

- -

完全な実装例は panner-node example (ソースコード) を確認してください。このデモでは 2.5 次元上の「メタルの部屋」上で、曲を再生するラジカセの位置を変更させることで変化する音声を体験できます。

- -

付記:以下の例では比較的新しい属性を利用するために、ブラウザの機能を調べています。例えば位置を設定する {{domxref("AudioListener.forwardX")}}) などです。これらが利用できる場合は利用し、そうでない場合は{{domxref("AudioListener.setOrientation()")}}) のような古いメソッドを利用しています。

- -
// set up listener and panner position information
-var WIDTH = window.innerWidth;
-var HEIGHT = window.innerHeight;
-
-var xPos = Math.floor(WIDTH/2);
-var yPos = Math.floor(HEIGHT/2);
-var zPos = 295;
-
-// define other variables
-
-var AudioContext = window.AudioContext || window.webkitAudioContext;
-var audioCtx = new AudioContext();
-
-var panner = audioCtx.createPanner();
-panner.panningModel = 'HRTF';
-panner.distanceModel = 'inverse';
-panner.refDistance = 1;
-panner.maxDistance = 10000;
-panner.rolloffFactor = 1;
-panner.coneInnerAngle = 360;
-panner.coneOuterAngle = 0;
-panner.coneOuterGain = 0;
-
-if(panner.orientationX) {
-  panner.orientationX.value = 1;
-  panner.orientationY.value = 0;
-  panner.orientationZ.value = 0;
-} else {
-  panner.setOrientation(1,0,0);
-}
-
-var listener = audioCtx.listener;
-
-if(listener.forwardX) {
-  listener.forwardX.value = 0;
-  listener.forwardY.value = 0;
-  listener.forwardZ.value = -1;
-  listener.upX.value = 0;
-  listener.upY.value = 1;
-  listener.upZ.value = 0;
-} else {
-  listener.setOrientation(0,0,-1,0,1,0);
-}
-
-var source;
-
-var play = document.querySelector('.play');
-var stop = document.querySelector('.stop');
-
-var boomBox = document.querySelector('.boom-box');
-
-var listenerData = document.querySelector('.listener-data');
-var pannerData = document.querySelector('.panner-data');
-
-leftBound = (-xPos) + 50;
-rightBound = xPos - 50;
-
-xIterator = WIDTH/150;
-
-// listener will always be in the same place for this demo
-
-if(listener.positionX) {
-  listener.positionX.value = xPos;
-  listener.positionY.value = yPos;
-  listener.positionZ.value = 300;
-} else {
-  listener.setPosition(xPos,yPos,300);
-}
-
-listenerData.innerHTML = 'Listener data: X ' + xPos + ' Y ' + yPos + ' Z ' + 300;
-
-// panner will move as the boombox graphic moves around on the screen
-function positionPanner() {
-  if(panner.positionX) {
-    panner.positionX.value = xPos;
-    panner.positionY.value = yPos;
-    panner.positionZ.value = zPos;
-  } else {
-    panner.setPosition(xPos,yPos,zPos);
-  }
-  pannerData.innerHTML = 'Panner data: X ' + xPos + ' Y ' + yPos + ' Z ' + zPos;
-}
- -
-

listener と panner に設定された位置が正しく機能するためには、それらがスクリーン上の位置を正しく反映している必要があります。そのためには少し面倒な計算が必要となりますが、すこしやれば慣れる類のものです。

-
- -

仕様

- - - - - - - - - - - - - - -
仕様状況コメント
{{SpecName('Web Audio API', '#widl-AudioContext-createPanner-PannerNode', 'createPanner()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザー互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

関連情報

- - diff --git a/files/ja/web/api/audiocontext/createperiodicwave/index.html b/files/ja/web/api/audiocontext/createperiodicwave/index.html deleted file mode 100644 index 825a1a8de5..0000000000 --- a/files/ja/web/api/audiocontext/createperiodicwave/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: AudioContext.createPeriodicWave() -slug: Web/API/AudioContext/createPeriodicWave -translation_of: Web/API/BaseAudioContext/createPeriodicWave ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreatePeriodicWave()メソッドは、周期的な波形を定義するために使われる{{domxref("PeriodicWave")}}を生成します。これは{{ domxref("OscillatorNode") }}の出力を決めるために使われます。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var wave = audioCtx.createPeriodicWave(real, imag);
- -

戻り値

- -

{{domxref("PeriodicWave")}}

- -

引数

- -
-
real
-
余弦項の配列 (伝統的なA項)
-
imag
-
正弦項の配列 (伝統的なB項)
-
- -

- -

The following example illustrates simple usage of createPeriodicWave(), to create a {{domxref("PeriodicWave")}} object containing a simple sine wave.

- -
var real = new Float32Array(2);
-var imag = new Float32Array(2);
-var ac = new AudioContext();
-var osc = ac.createOscillator();
-
-real[0] = 0;
-imag[0] = 0;
-real[1] = 1;
-imag[1] = 0;
-
-var wave = ac.createPeriodicWave(real, imag);
-
-osc.setPeriodicWave(wave);
-
-osc.connect(ac.destination);
-
-osc.start();
-osc.stop(2);
- -

This works because a sound that contains only a fundamental tone is by definition a sine wave.
-
- Here, we create a PeriodicWave with two values. The first value is the DC offset, which is the value at which the oscillator starts. 0 is good here, because we want to start the curve at the middle of the [-1.0; 1.0] range.

- -

The second and subsequent values are sine and cosine components. You can think of it as the result of a Fourier transform, where you get frequency domain values from time domain value. Here, with createPeriodicWave(), you specify the frequencies, and the browser performs a an inverse Fourier transform to get a time domain buffer for the frequency of the oscillator. Here, we only set one component at full volume (1.0) on the fundamental tone, so we get a sine wave.

- -

The coefficients of the Fourier transform should be given in ascending order (i.e. (a+bi)ei,(c+di)e2i,(f+gi)e3i\left(a+bi\right)e^{i} , \left(c+di\right)e^{2i} , \left(f+gi\right)e^{3i}   etc.) and can be positive or negative.  A simple way of manually obtaining such coefficients (though not the best) is to use a graphing calculator.

- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createPeriodicWave-PeriodicWave-Float32Array-real-Float32Array-imag', 'createPeriodicWave')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(33.0)}}
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/createscriptprocessor/index.html b/files/ja/web/api/audiocontext/createscriptprocessor/index.html deleted file mode 100644 index d3c80ae2cb..0000000000 --- a/files/ja/web/api/audiocontext/createscriptprocessor/index.html +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: AudioContext.createScriptProcessor() -slug: Web/API/AudioContext/createScriptProcessor -translation_of: Web/API/BaseAudioContext/createScriptProcessor ---- -

{{ APIRef("AudioContext") }}

-
-

{{ domxref("AudioContext") }} の createScriptProcessor() メソッドを利用することで、ダイレクトな音声処理ができる {{domxref("ScriptProcessorNode")}} オブジェクトを作成できます。

-
-
-

注意: このノードの利用方法に関しては {{domxref("ScriptProcessorNode")}} をご覧ください。

-
-

構文

-
 ScriptProcessorNode             createScriptProcessor (optional unsigned long bufferSize = 0 , optional unsigned long numberOfInputChannels = 2 , optional unsigned long numberOfOutputChannels = 2 );
-

-

createScriptProcessor()の利用例は以下の通りになります。Web Audio API が提供する機能では望む音声処理を実現できない場合に、このメソッドを利用します。これを利用することで、どの様な音声処理でも記述できます。

-
SineWave = function(context) {
-  var that = this;
-  this.x = 0; // Initial sample number
-  this.context = context;
-  this.node = context.createScriptProcessor(1024, 1, 1);
-  this.node.onaudioprocess = function(e) { that.process(e) };
-}
-
-SineWave.prototype.process = function(e) {
-  var data = e.outputBuffer.getChannelData(0);
-  for (var i = 0; i < data.length; ++i) {
-    data[i] = Math.sin(this.x++);
-  }
-}
-
-SineWave.prototype.play = function() {
-  this.node.connect(this.context.destination);
-}
-
-SineWave.prototype.pause = function() {
-  this.node.disconnect();
-}
-

引数

-
-
- bufferSize
-
- サンプルフレームを単位としたバッファのサイズです。指定する場合は、次のいずれかの値でなくてはなりません: 256, 512, 1024, 2048, 4096, 8192, 16384 。指定されない場合、もしくは 0 が指定された場合、環境における最適な値が設定されます。この値はノードが生存する限り同じ値が利用され、その値は 2 の冪上です。
-
- この値は audioprocess イベントの発生頻度と、イベントごとに渡されるサンプルフレームの大きさを決めます。小さい値を指定すると低遅延となり、大きな値を指定すると音声の破損やグリッチを避けられます。この値は自分で決めず、実装に決めさせることが遅延と品質の面から推奨されます。
-
- numberOfInputChannels
-
- 入力のチャンネル数を整数で指定します。デフォルト値は 2 で、最大 32 チャンネルまでサポートします。
-
- numberOfOutputChannels
-
- 出力するチャンネル数を整数で指定します。デフォルト値は 2 で、最大 32 チャンネルまでサポートします。
-
-
-

Important: Webkit currently (version 31) requires that a valid bufferSize be passed when calling this method.

-
-
-

注意: numberOfInputChannelsnumberOfOutputChannels の両方に 0 を指定することはできません。

-
-

返り値

-

A {{domxref("ScriptProcessorNode")}}.

-

ブラウザ互換性

-

{{page("/en-US/docs/Web/API/AudioContext","Browser_compatibility")}}

-

仕様

-

{{page("/en-US/docs/Web/API/AudioContext","Specifications")}}

-

関連情報

-

{{page("/en-US/docs/Web/API/AudioContext","See_also")}}

diff --git a/files/ja/web/api/audiocontext/createstereopanner/index.html b/files/ja/web/api/audiocontext/createstereopanner/index.html deleted file mode 100644 index c77689aa90..0000000000 --- a/files/ja/web/api/audiocontext/createstereopanner/index.html +++ /dev/null @@ -1,128 +0,0 @@ ---- -title: AudioContext.createStereoPanner() -slug: Web/API/AudioContext/createStereoPanner -translation_of: Web/API/BaseAudioContext/createStereoPanner ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcreateStereoPanner()メソッドは、音源にステレオパンニングを適用する{{ domxref("StereoPannerNode") }}を生成します。入力されたオーディオストリームは、低コストなequal-powerパンニングアルゴリズムで位置が決められます。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var panNode = audioCtx.createStereoPanner();
- -

戻り値

- -

{{domxref("StereoPannerNode")}}

- -

- -

このStereoPannerNodeサンプル(ソースコード)のHTMLには、{{htmlelement("audio")}}要素と、パン値を増減させるスライダー{{domxref("input")}}しかありません。JavaScpriptでは、{{domxref("MediaElementAudioSourceNode")}}と{{domxref("StereoPannerNode")}}を生成し、この2つをconnect()メソッドで接続しています。そして、スライダーを動かすと、oninputイベントハンドラで{{domxref("StereoPannerNode.pan")}}パラメータの値を変更し、ディスプレイのパン値を更新しています。

- -

スライダーを左から右に動かすと、音楽のスピーカーからの出力が左から右にパンされます。

- -
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
-var myAudio = document.querySelector('audio');
-
-var panControl = document.querySelector('.panning-control');
-var panValue = document.querySelector('.panning-value');
-
-pre.innerHTML = myScript.innerHTML;
-
-// MediaElementAudioSourceNodeを生成し、そこにHTMLMediaElementを入れる
-var source = audioCtx.createMediaElementSource(myAudio);
-
-// ステレオパンナーを生成する
-var panNode = audioCtx.createStereoPanner();
-
-// イベントハンドラ関数で、スライダーが動いたとき左右のパンの値を左右する
-
-panControl.oninput = function() {
-  panNode.pan.value = panControl.value;
-  panValue.innerHTML = panControl.value;
-}
-
-// AudioBufferSourceNodeをpanNodeに接続し、panNodeを行き先(destination)に接続する
-// これでこのコントロールで音楽をパンを調整することができる
-source.connect(panNode);
-panNode.connect(audioCtx.destination);
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createStereoPanner-StereoPannerNode', 'createStereoPanner()')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(37.0)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}37.02.2{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/currenttime/index.html b/files/ja/web/api/audiocontext/currenttime/index.html deleted file mode 100644 index 0d2a92b3ea..0000000000 --- a/files/ja/web/api/audiocontext/currenttime/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: AudioContext.currentTime -slug: Web/API/AudioContext/currentTime -translation_of: Web/API/BaseAudioContext/currentTime ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのcurrentTime読み取り専用プロパティは、再生、タイムラインの可視化などのスケジューリングで使用できる単純増加するハードウェア時間をdoubleの秒数で返します。0から始まります。

-
- -

構文

- -
var audioCtx = new AudioContext();
-console.log(audioCtx.currentTime);
- -

- -

double

- -

- -
-

注: 完全な実装の例は、MDN Github repopanner-nodeなどを参照してください。audioCtx.currentTimeをあなたのブラウザで使ってみてください。

-
- -
var AudioContext = window.AudioContext || window.webkitAudioContext;
-var audioCtx = new AudioContext();
-// 古いwebkit/blinkブラウザではプレフィックスが必要です
-
-...
-
-console.log(audioCtx.currentTime);
-
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-currentTime', 'currentTime')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/decodeaudiodata/index.html b/files/ja/web/api/audiocontext/decodeaudiodata/index.html deleted file mode 100644 index db9c106e52..0000000000 --- a/files/ja/web/api/audiocontext/decodeaudiodata/index.html +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: AudioContext.decodeAudioData() -slug: Web/API/AudioContext/decodeAudioData -tags: - - API - - Audio - - AudioContext - - BaseAudioContext - - Method - - Reference - - Web Audio API - - decodeAudioData -translation_of: Web/API/BaseAudioContext/decodeAudioData ---- -

{{ APIRef("Web Audio API") }}

- -

decodeAudioData() は {{ domxref("BaseAudioContext") }} のメソッドで、 {{domxref("ArrayBuffer")}} に書き込まれた音声ファイルデータを非同期にデコードするために使用されます。この場合、 ArrayBuffer は {{domxref("XMLHttpRequest")}} と {{domxref("FileReader")}} から読み込まれます。デコードされた {{domxref("AudioBuffer")}} は {{domxref("AudioContext")}} のサンプリングレートにリサンプリングされ、コールバックやプロミスに渡されます。

- -

この方法は、オーディオトラックから Web Audio API 用のオーディオソースを作成する際に推奨される方法です。この方法は、音声ファイルの断片的なデータではなく、完全なファイルデータに対してのみ動作します。

- -

構文

- -

古いコールバック構文:

- -
baseAudioContext.decodeAudioData(ArrayBuffer, successCallback, errorCallback);
- -

新しいプロミスベースの構文:

- -
Promise<decodedData> baseAudioContext.decodeAudioData(ArrayBuffer);
- -

引数

- -
-
ArrayBuffer
-
デコードする音声データが入った ArrayBuffer です。通常は{{domxref("XMLHttpRequest")}}, {{domxref("WindowOrWorkerGlobalScope.fetch()")}}, {{domxref("FileReader")}} から取得します。
-
successCallback
-
デコードが完了すると呼び出されるコールバック関数です。このコールバックの引数は1つで、 decodedData (デコードされた PCM 音声データ) を表す {{domxref("AudioBuffer")}} です。通常は、デコードされたデータを {{domxref("AudioBufferSourceNode")}} に入れて、そこから再生したり、好きなように操作したりすることができます。
-
errorCallback
-
任意のエラーコールバックで、音声データのデコードでエラーが発生すると呼び出されます。
-
- -

返値

- -

なし、または decodedData で満足する {{domxref("Promise") }} オブジェクトで.

- -

- -

ここでは最初に古いコールバックベースのシステムを、次に新しいプロミスベースの構文を取り上げます。

- -

古いコールバックベースの構文

- -

この例では、 getData() 関数は XHR を使用して音声トラックを読み込み、リクエストの responseTypearraybuffer に設定して、レスポンスとして配列バッファーを返すようにして、それを audioData 変数に格納しています。それからこのバッファーを decodeAudioData() 関数に渡します。成功したコールバックは、デコードに成功した PCM データを受け取り、 {{ domxref("AudioContext.createBufferSource()") }} で作成した {{ domxref("AudioBufferSourceNode") }} に入れ、ソースを {{domxref("AudioContext.destination") }} に接続してループするように設定します。

- -

ボタンは単に getData() を実行して、それぞれトラックの読み込みと再生、停止を行うだけです。ソースの stop() メソッドが呼ばれると、ソースは消滅します。

- -
-

注: ライブ例の実行 (またはソースの閲覧) もできます。

-
- -
// 変数の定義
-
-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');
-
-// 音声トラックの読み込みには XHR を使い、
-// decodeAudioData でデコードし、バッファーに格納する
-// そして、そのバッファーを source に設定する
-
-function getData() {
-  source = audioCtx.createBufferSource();
-  var request = new XMLHttpRequest();
-
-  request.open('GET', 'viper.ogg', true);
-
-  request.responseType = 'arraybuffer';
-
-
-  request.onload = function() {
-    var audioData = request.response;
-
-    audioCtx.decodeAudioData(audioData, function(buffer) {
-        source.buffer = buffer;
-
-        source.connect(audioCtx.destination);
-        source.loop = true;
-      },
-
-      function(e){ console.log("Error with decoding audio data" + e.err); });
-
-  }
-
-  request.send();
-}
-
-// 音声の停止と再生を行うボタン
-
-play.onclick = function() {
-  getData();
-  source.start(0);
-  play.setAttribute('disabled', 'disabled');
-}
-
-stop.onclick = function() {
-  source.stop(0);
-  play.removeAttribute('disabled');
-}
-
-
-// pre要素にスクリプトを設定する
-
-pre.innerHTML = myScript.innerHTML;
- -

新しいプロミスベースの構文

- -
ctx.decodeAudioData(audioData).then(function(decodedData) {
- // デコードしたデータをここで使う
-});
- -

仕様書

- - - - - - - - - - - - - - - - -
仕様状態備考
{{SpecName('Web Audio API', '#dom-baseaudiocontext-decodeaudiodata', 'decodeAudioData()')}}{{Spec2('Web Audio API')}}
- -

ブラウザーの互換性

- -
- - -

{{Compat("api.BaseAudioContext.decodeAudioData")}}

-
- -

関連情報

- - diff --git a/files/ja/web/api/audiocontext/destination/index.html b/files/ja/web/api/audiocontext/destination/index.html deleted file mode 100644 index f93e8682f1..0000000000 --- a/files/ja/web/api/audiocontext/destination/index.html +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: AudioContext.destination -slug: Web/API/AudioContext/destination -translation_of: Web/API/BaseAudioContext/destination ---- -

{{ APIRef("Web Audio API") }}

- -
-

インターフェースのdestinationプロパティは、コンテキストの全ての音声の最終的な行き先を表す{{ domxref("AudioDestinationNode") }} を戻します。これは、あなたのコンピュータのスピーカーのような、オーディオレンダリングデバイスと考えることができます。

-
- -

構文

- -
var audioCtx = new AudioContext();
-gainNode.connect(audioCtx.destination);
- -

- -

{{ domxref("AudioDestinationNode") }}

- -

- -
-

注: 完全な実装の例は、MDN Github repopanner-nodeなどを参照してください。

-
- -
var AudioContext = window.AudioContext || window.webkitAudioContext;
-var audioCtx = new AudioContext();
-// 古いwebkit/blinkブラウザではプレフィックスが必要です
-
-var oscillatorNode = audioCtx.createOscillator();
-var gainNode = audioCtx.createGain();
-
-oscillatorNode.connect(gainNode);
-gainNode.connect(audioCtx.destination);
-
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-destination', 'destination')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/listener/index.html b/files/ja/web/api/audiocontext/listener/index.html deleted file mode 100644 index 7b4f394727..0000000000 --- a/files/ja/web/api/audiocontext/listener/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: AudioContext.listener -slug: Web/API/AudioContext/listener -translation_of: Web/API/BaseAudioContext/listener ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのlistenerプロパティは、3次元音声を実装するために使う{{ domxref("AudioListener") }}オブジェクトを返します。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var myListener = audioCtx.listener;
- -

- -

{{ domxref("AudioListener") }}

- -

- -
-

注: 完全な実装の例は、panner-nodeを参照してください。

-
- -
var AudioContext = window.AudioContext || window.webkitAudioContext;
-var audioCtx = new AudioContext();
-// 古いwebkit/blinkブラウザではプレフィックスが必要です
-
-...
-
-var myListener = audioCtx.listener;
-
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-listener', 'listener')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/mozaudiochanneltype/index.html b/files/ja/web/api/audiocontext/mozaudiochanneltype/index.html deleted file mode 100644 index 62f6879ebe..0000000000 --- a/files/ja/web/api/audiocontext/mozaudiochanneltype/index.html +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: AudioContext.mozAudioChannelType -slug: Web/API/AudioContext/mozAudioChannelType -translation_of: Web/API/AudioContext/mozAudioChannelType ---- -

{{APIRef("Web Audio API")}} {{Non-standard_header}}

- -

{{domxref("AudioContext")}}インターフェースのmozAudioChannelType読み取り専用プロパティは、Firefox OS デバイスで、オーディオコンテキスト要素で再生される音声を再生するオーディオチャンネルを設定するために使えます。

- -

これはAudioChannels APIに定義された非標準のプロパティです。詳細はUsing the AudioChannels APIを参照してください。

- -

構文

- -
var audioCtx = new AudioContext();
-var myAudioChannelType = audioCtx.mozAudioChannelType;
-
- -

AudioContextのオーディオチャンネルタイプを設定できるのは、次のコンストラクタを使う場合のみです。

- -
var audioCtx = new AudioContext('ringer');
- -

- -

{{domxref("DOMString")}}

- -

- -

TBD

- -

仕様

- -

現在はAudioChannels APIには公式の仕様はありません。実装、WebIDLなどの詳細はhttps://wiki.mozilla.org/WebAPI/AudioChannelsを参照してください。

- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
General support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
General support{{CompatNo}}{{CompatNo}}{{CompatNo}}1.2{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/onstatechange/index.html b/files/ja/web/api/audiocontext/onstatechange/index.html deleted file mode 100644 index 5ce3ecaf26..0000000000 --- a/files/ja/web/api/audiocontext/onstatechange/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: AudioContext.onstatechange -slug: Web/API/AudioContext/onstatechange -translation_of: Web/API/BaseAudioContext/onstatechange ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのonstatechangeプロパティは、{{Event("statechange")}}イベントが発火した(これはオーディオコンテキストの状態が変わったとき発生します)とき呼ばれるイベントハンドラ関数を定義します。

-
- -

構文

- -
var audioCtx = new AudioContext();
-audioCtx.onstatechange = function() { ... };
- -

- -

次のスニペットはAudioContext states デモの一部です(すぐに実行)。{{domxref("AudioContext.onstatechange")}}ハンドラは、状態が変わるたびにコンソールにログを出力するために使われています。

- -
audioCtx.onstatechange = function() {
-  console.log(audioCtx.state);
-}
-
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-onstatechange', 'onstatechange')}}{{Spec2('Web Audio API')}} 
- -

互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(43.0)}}{{CompatGeckoDesktop(40.0)}} {{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/samplerate/index.html b/files/ja/web/api/audiocontext/samplerate/index.html deleted file mode 100644 index 8715d8ae39..0000000000 --- a/files/ja/web/api/audiocontext/samplerate/index.html +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: AudioContext.sampleRate -slug: Web/API/AudioContext/sampleRate -translation_of: Web/API/BaseAudioContext/sampleRate ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのsampleRateプロパティは、このオーディオコンテキストの全てのノードで使われるサンプルレート(1秒あたりのサンプル数)を浮動小数点で返します。

-
- -

構文

- -
var audioCtx = new AudioContext();
-var mySampleRate = audioCtx.sampleRate;
- -

- -

浮動小数点

- -

- -
-

注: 完全な実装の例は、MDN Github repopanner-nodeなどを参照してください。audioCtx.sampleRateをあなたのブラウザで使ってみてください。

-
- -
var AudioContext = window.AudioContext || window.webkitAudioContext;
-var audioCtx = new AudioContext();
-// 古いwebkit/blinkブラウザではプレフィックスが必要です
-
-...
-
-console.log(audioCtx.sampleRate);
-
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-sampleRate', 'sampleRate')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
- 22 (unprefixed)
6.0{{property_prefix("webkit")}}
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
-
- -

参考

- - diff --git a/files/ja/web/api/audiocontext/state/index.html b/files/ja/web/api/audiocontext/state/index.html deleted file mode 100644 index a19d03f9af..0000000000 --- a/files/ja/web/api/audiocontext/state/index.html +++ /dev/null @@ -1,66 +0,0 @@ ---- -title: AudioContext.state -slug: Web/API/AudioContext/state -translation_of: Web/API/BaseAudioContext/state ---- -

{{ APIRef("Web Audio API") }}

- -
-

{{ domxref("AudioContext") }}インターフェースのstate読取専用プロパティは、現在のAudioContextの状態を返します。

-
- -

構文

- -
baseAudioContext.state;
- -

- -

{{domxref("DOMString")}}。取りうる値は:

- - - -

- -

次のスニペットはAudioContext states デモの一部です(すぐに実行)。{{domxref("AudioContext.onstatechange")}}ハンドラは、状態が変わるたびにコンソールにログを出力するために使われています。

- -
audioCtx.onstatechange = function() {
-  console.log(audioCtx.state);
-}
-
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('Web Audio API', '#dom-baseaudiocontext-state', 'state')}}{{Spec2('Web Audio API')}} 
- -

ブラウザ互換性

- -
-
- - -

{{Compat("api.BaseAudioContext.state")}}

-
-
- -

参考

- - diff --git a/files/ja/web/api/audioscheduledsourcenode/onended/index.html b/files/ja/web/api/audioscheduledsourcenode/onended/index.html new file mode 100644 index 0000000000..22f8b05ba3 --- /dev/null +++ b/files/ja/web/api/audioscheduledsourcenode/onended/index.html @@ -0,0 +1,108 @@ +--- +title: AudioBufferSourceNode.onended +slug: Web/API/AudioBufferSourceNode/onended +translation_of: Web/API/AudioScheduledSourceNode/onended +translation_of_original: Web/API/AudioBufferSourceNode/onended +--- +

{{ APIRef("AudioBufferSourceNode") }}

+ +
AudioBufferSourceNodeの onended イベントハンドラーは{{event("ended_(Web_Audio)", "ended")}} イベントに関するコ−ルバック関数を格納します。これによりオーディオトラックの再生終了時に実行するコードを設定することができます。
+ +
+

: onended ハンドラーは loop プロパティーがtrueに設定されている場合はオーディオが再生終了することが無いので効果がありません。このような場合にこの機能を有効にするには {{ domxref("AudioBufferSourceNode.stop()") }} を使用してください。

+
+ +

構文

+ +
var source = audioCtx.createBufferSource();
+source.onended = function() { ... };
+
+ +

用例

+ +
source.start();
+source.onended = function() {
+  console.log('Your audio has finished playing');
+}
+ +

プロパティ

+ +

有りません。

+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBufferSourceNode-onended', 'onended')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザー互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}23{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

関連情報

+ + diff --git a/files/ja/web/api/audioscheduledsourcenode/stop/index.html b/files/ja/web/api/audioscheduledsourcenode/stop/index.html new file mode 100644 index 0000000000..2163d86379 --- /dev/null +++ b/files/ja/web/api/audioscheduledsourcenode/stop/index.html @@ -0,0 +1,120 @@ +--- +title: AudioBufferSourceNode.stop() +slug: Web/API/AudioBufferSourceNode/stop +translation_of: Web/API/AudioScheduledSourceNode/stop +translation_of_original: Web/API/AudioBufferSourceNode/stop +--- +

{{ APIRef("Web Audio API") }}

+ +
+

インターフェースのstop()メソッドは、オーディオバッファの再生を停止させるために使われます。

+
+ +

構文

+ +
var source = audioCtx.createBufferSource();
+source.stop(when);
+
+ +

+ +

最も単純なオーディオバッファ再生の停止方法—この場合は何もパラメータを指定する必要はありません。

+ +
source.stop();
+ +

しばらく後に停止させたい場合は、引数として秒数を指定します。

+ +
source.stop(3);
+ +
+

注: stop()の使い方の完全な例はAudioContext.decodeAudioDataを参照してください。コードをすぐに実行することや、ソースコードを閲覧することもできます。

+
+ +

引数

+ +
+
when
+
whenパラメータは、再生をいつ停止するかを決定します。指定の時間を経過すると、再生はすぐに停止します。このメソッドが2回以上呼ばれると、例外が発生します
+
+ +

戻り値

+ +

なし

+ +

使用

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioBufferSourceNode-stop-void-double-when', 'stop()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support14 {{property_prefix("webkit")}}23{{CompatNo}}15 {{property_prefix("webkit")}}
+ 22 (unprefixed)
6 {{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidChromeFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{CompatNo}}28 {{property_prefix("webkit")}}251.2{{CompatNo}}{{CompatNo}}6 {{property_prefix("webkit")}}
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createanalyser/index.html b/files/ja/web/api/baseaudiocontext/createanalyser/index.html new file mode 100644 index 0000000000..c186d1029c --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createanalyser/index.html @@ -0,0 +1,154 @@ +--- +title: AudioContext.createAnalyser() +slug: Web/API/AudioContext/createAnalyser +translation_of: Web/API/BaseAudioContext/createAnalyser +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateAnalyser()メソッドは、音声の時間と周波数を解析する{{ domxref("AnalyserNode") }}を生成します。これはデータの可視化などで使えます。

+
+ +
+

注: このノードの詳しい説明は、{{domxref("AnalyserNode")}}のページを参照してください。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var analyser = audioCtx.createAnalyser();
+ +

戻り値

+ +

{{domxref("AnalyserNode")}}

+ +

+ +

次のサンプルでは、基本的なAudioContextAnalyserNodeの生成、requestAnimationFrame()による時間データの周期的な収集と「オシロスコープのように」現在の音声を出力する方法を示しています。より完全な例と情報は、Voice-change-O-maticデモ(app.jsの128–205行目)を参照してください。

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var analyser = audioCtx.createAnalyser();
+
+  ...
+
+analyser.fftSize = 2048;
+var bufferLength = analyser.fftSize;
+var dataArray = new Uint8Array(bufferLength);
+analyser.getByteTimeDomainData(dataArray);
+
+// 現在の音のオシロスコープのように描く
+
+function draw() {
+
+      drawVisual = requestAnimationFrame(draw);
+
+      analyser.getByteTimeDomainData(dataArray);
+
+      canvasCtx.fillStyle = 'rgb(200, 200, 200)';
+      canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);
+
+      canvasCtx.lineWidth = 2;
+      canvasCtx.strokeStyle = 'rgb(0, 0, 0)';
+
+      canvasCtx.beginPath();
+
+      var sliceWidth = WIDTH * 1.0 / bufferLength;
+      var x = 0;
+
+      for(var i = 0; i < bufferLength; i++) {
+
+        var v = dataArray[i] / 128.0;
+        var y = v * HEIGHT/2;
+
+        if(i === 0) {
+          canvasCtx.moveTo(x, y);
+        } else {
+          canvasCtx.lineTo(x, y);
+        }
+
+        x += sliceWidth;
+      }
+
+      canvasCtx.lineTo(canvas.width, canvas.height/2);
+      canvasCtx.stroke();
+    };
+
+    draw();
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createAnalyser-AnalyserNode', 'createAnalyser()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createbiquadfilter/index.html b/files/ja/web/api/baseaudiocontext/createbiquadfilter/index.html new file mode 100644 index 0000000000..136557bea5 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createbiquadfilter/index.html @@ -0,0 +1,126 @@ +--- +title: AudioContext.createBiquadFilter() +slug: Web/API/AudioContext/createBiquadFilter +translation_of: Web/API/BaseAudioContext/createBiquadFilter +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateBiquadFilter()メソッドはいくつかの一般的なフィルタを設定できる二次フィルターを表す{{ domxref("BiquadFilterNode") }}を生成します。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var biquadFilter = audioCtx.createBiquadFilter();
+ +

戻り値

+ +

{{domxref("BiquadFilterNode")}}

+ +

+ +

次の例はAudioContextのBiquadFilterNodeの使い方を説明しています。完全に動作する例は、voice-change-o-maticデモ(ソースコードもあります)を参照してください。

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// このアプリで使う2つのノードを設定する
+var analyser = audioCtx.createAnalyser();
+var distortion = audioCtx.createWaveShaper();
+var gainNode = audioCtx.createGain();
+var biquadFilter = audioCtx.createBiquadFilter();
+var convolver = audioCtx.createConvolver();
+
+// ノードを接続する
+
+source = audioCtx.createMediaStreamSource(stream);
+source.connect(analyser);
+analyser.connect(distortion);
+distortion.connect(biquadFilter);
+biquadFilter.connect(convolver);
+convolver.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+
+// 二次フィルターで操作する
+
+biquadFilter.type = "lowshelf";
+biquadFilter.frequency.value = 1000;
+biquadFilter.gain.value = 25;
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createBiquadFilter-BiquadFilterNode', 'createBiquadFilter()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0 {{property_prefix("webkit")}}
+ 22
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参照

+ + diff --git a/files/ja/web/api/baseaudiocontext/createbuffer/index.html b/files/ja/web/api/baseaudiocontext/createbuffer/index.html new file mode 100644 index 0000000000..e94a5a18be --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createbuffer/index.html @@ -0,0 +1,174 @@ +--- +title: AudioContext.createBuffer() +slug: Web/API/AudioContext/createBuffer +translation_of: Web/API/BaseAudioContext/createBuffer +--- +

{{ APIRef("Web Audio API") }}

+ +
+

インターフェースのcreateBuffer()メソッドは、新規の空の{{ domxref("AudioBuffer") }}オブジェクトを生成します。そこにデータを書きこめば、{{ domxref("AudioBufferSourceNode") }}で再生できます。

+
+ +
+

Note: createBuffer() used to be able to take compressed data and give back decoded samples, but this ability was removed from the spec, because all the decoding was done on the main thread, therefore createBuffer() was blocking other code execution. The asynchronous method decodeAudioData() does the same thing — takes compressed audio, say, an MP3 file, and directly gives you back an {{ domxref("AudioBuffer") }} that you can then set to play via in an {{ domxref("AudioBufferSourceNode") }}. For simple uses like playing an MP3, decodeAudioData() is what you should be using.

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var buffer = audioCtx.createBuffer(numOfChannels, length, sampleRate);
+ +

引数

+ +
+

Note: For an in-depth explanation of how audio buffers work, and what these parameters mean, read Audio buffers: frames, samples and channels from our Basic concepts guide.

+
+ +
+
numOfChannels
+
integerで現されたバッファのチャンネルの数。実装は少なくとも32チャンネルに対応している
+
length
+
integerで表されたバッファのサンプルフレームの数
+
sampleRate
+
1秒あたりのサンプルフレームの数。実装は少なくとも22050から96000の範囲に対応している
+
+ +

戻り値

+ +

{{domxref("AudioBuffer")}}

+ +

+ +

まずは2つの小さな例で、引数をどのように設定するかを説明します:

+ +
var audioCtx = new AudioContext();
+var buffer = audioCtx.createBuffer(2, 22050, 44100);
+ +

このようにすると、ステレオ(2チャンネル)のバッファが生成され、44100Hz(極めて一般的で、多くの通常のサウンドカードはこのレートで動作します)のAudioContextで再生すると、0.5秒間(22050フレーム / 44100Hz )となります。

+ +
var audioCtx = new AudioContext();
+var buffer = audioCtx.createBuffer(1, 22050, 22050);
+ +

このようにすると、モノラル(1チャンネル)のバッファが生成され、44100HzのAudioContextで再生すると、自動的に44100Hzに再サンプリングされ(そして結果として44100フレームとなり)、1秒間(44100フレーム / 44100Hz)となります。

+ +
+

Note: audio resampling is very similar to image resizing: say you've got a 16 x 16 image, but you want it to fill a 32x32 area: you resize (resample) it. the result has less quality (it can be blurry or edgy, depending on the resizing algorithm), but it works, and the resized image takes up less space. Resampled audio is exactly the same — you save space, but in practice you will be unable to properly reproduce high frequency content (treble sound).

+
+ +

次は少し複雑なcreateBuffer()の例を見てみましょう。2秒間のバッファを生成し、ホワイトノイズを書き込み、{{ domxref("AudioBufferSourceNode") }}で再生します。コードをすぐに実行することや、ソースコードを閲覧することもできます。

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var button = document.querySelector('button');
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+
+pre.innerHTML = myScript.innerHTML;
+
+// ステレオ
+var channels = 2;
+// AudioContextのサンプルレートで2秒間の空のステレオバッファを生成する
+var frameCount = audioCtx.sampleRate * 2.0;
+
+var myArrayBuffer = audioCtx.createBuffer(channels, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // バッファにホワイトノイズを書き込む;
+  // 単なる-1.0から1.0の間の乱数の値である
+  for (var channel = 0; channel < channels; channel++) {
+   // 実際のデータの配列を得る
+   var nowBuffering = myArrayBuffer.getChannelData(channel);
+   for (var i = 0; i < frameCount; i++) {
+     // Math.random()は[0; 1.0]である
+     // 音声は[-1.0; 1.0]である必要がある
+     nowBuffering[i] = Math.random() * 2 - 1;
+   }
+  }
+
+  // AudioBufferSourceNodeを得る
+  // これはAudioBufferを再生するときに使うAudioNodeである
+  var source = audioCtx.createBufferSource();
+  // AudioBufferSourceNodeにバッファを設定する
+  source.buffer = myArrayBuffer;
+  // AudioBufferSourceNodeを出力先に接続すると音声が聞こえるようになる
+  source.connect(audioCtx.destination);
+  // 音源の再生を始める
+  source.start();
+}
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createBuffer-AudioBuffer-unsigned-long-numberOfChannels-unsigned-long-length-float-sampleRate', 'createBuffer()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0 {{property_prefix("webkit")}}
+ 22
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createbuffersource/index.html b/files/ja/web/api/baseaudiocontext/createbuffersource/index.html new file mode 100644 index 0000000000..24f65061c6 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createbuffersource/index.html @@ -0,0 +1,143 @@ +--- +title: AudioContext.createBufferSource() +slug: Web/API/AudioContext/createBufferSource +translation_of: Web/API/BaseAudioContext/createBufferSource +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateBufferSource()メソッドは、{{ domxref("AudioBuffer") }}オブジェクトに書き込まれた音声データを再生する{{ domxref("AudioBufferSourceNode") }}を生成します。{{ domxref("AudioBuffer") }}は{{domxref("AudioContext.createBuffer")}}を使った場合や、{{domxref("AudioContext.decodeAudioData")}}でオーディオトラックをデコードしたときに生成されます。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var source = audioCtx.createBufferSource();
+ +

戻り値

+ +

{{domxref("AudioBufferSourceNode")}}

+ +

+ +

この例では、2秒間のバッファを生成し、ホワイトノイズを書き込み、{{ domxref("AudioBufferSourceNode") }}で再生します。コメントは何をしているかを簡単に説明しています。

+ +
+

注: コードの実行ソースの閲覧もできます。

+
+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var button = document.querySelector('button');
+var pre = document.querySelector('pre');
+var myScript = document.querySelector('script');
+
+pre.innerHTML = myScript.innerHTML;
+
+// ステレオ
+var channels = 2;
+// AudioContextのサンプルレートで2秒間の空のステレオバッファを生成する
+var frameCount = audioCtx.sampleRate * 2.0;
+
+var myArrayBuffer = audioCtx.createBuffer(2, frameCount, audioCtx.sampleRate);
+
+button.onclick = function() {
+  // バッファにホワイトノイズを書き込む;
+  // 単なる-1.0から1.0の間の乱数の値である
+  for (var channel = 0; channel < channels; channel++) {
+   // 実際のデータの配列を得る
+   var nowBuffering = myArrayBuffer.getChannelData(channel);
+   for (var i = 0; i < frameCount; i++) {
+     // Math.random()は[0; 1.0]である
+     // 音声は[-1.0; 1.0]である必要がある
+     nowBuffering[i] = Math.random() * 2 - 1;
+   }
+  }
+
+  // AudioBufferSourceNodeを得る
+  // これはAudioBufferを再生するときに使うAudioNodeである
+  var source = audioCtx.createBufferSource();
+  // AudioBufferSourceNodeにバッファを設定する
+  source.buffer = myArrayBuffer;
+  // AudioBufferSourceNodeを出力先に接続すると音声が聞こえるようになる
+  source.connect(audioCtx.destination);
+  // 音源の再生を始める
+  source.start();
+}
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createBufferSource-AudioBufferSourceNode', 'createBufferSource()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createchannelmerger/index.html b/files/ja/web/api/baseaudiocontext/createchannelmerger/index.html new file mode 100644 index 0000000000..e79b116642 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createchannelmerger/index.html @@ -0,0 +1,133 @@ +--- +title: AudioContext.createChannelMerger() +slug: Web/API/AudioContext/createChannelMerger +translation_of: Web/API/BaseAudioContext/createChannelMerger +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateChannelMerger()メソッドは、複数のオーディオストリームを1つに混合する{{domxref("ChannelMergerNode")}}を生成します。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var merger = audioCtx.createChannelMerger(numberOfInputs);
+ +

引数

+ +
+
numberOfInputs
+
入力オーディオストリームのチャンネルの数。指定がない場合は6になる。
+
+ +

戻り値

+ +

{{domxref("ChannelMergerNode")}}

+ +

+ +

この例ではステレオトラックを分け、左右のチャンネルをそれぞれ別に処理する方法を示しています。これを使うためには、{{domxref("AudioNode.connect(AudioNode)") }}メソッドの2番目と3番目の引数を使い、接続元と接続先のチャンネルの番号を指定する必要があります。

+ +
var ac = new AudioContext();
+ac.decodeAudioData(someStereoBuffer, function(data) {
+ var source = ac.createBufferSource();
+ source.buffer = data;
+ var splitter = ac.createChannelSplitter(2);
+ source.connect(splitter);
+ var merger = ac.createChannelMerger(2);
+
+ // 左チャンネルのボリュームのみ小さくする
+ var gain = ac.createGain();
+ gain.value = 0.5;
+ splitter.connect(gain, 0);
+
+ // splitterをmergerの2番目の入力にして戻す
+ // ここではチャンネルを入れ替えることで、ステレオ音声の左右を逆にしている
+ gain.connect(merger, 0, 1);
+ splitter.connect(merger, 1, 0);
+
+ var dest = ac.createMediaStreamDestination();
+
+ // ChannelMergerNodeを使ったのでステレオのMediaStreamとなった
+ // webオーディオグラフのWebRTCやMediaRecorderなどに渡す
+ merger.connect(dest);
+});
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createChannelMerger-ChannelMergerNode-unsigned-long-numberOfInputs', 'createChannelMerger()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参照

+ + diff --git a/files/ja/web/api/baseaudiocontext/createchannelsplitter/index.html b/files/ja/web/api/baseaudiocontext/createchannelsplitter/index.html new file mode 100644 index 0000000000..07444c49d0 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createchannelsplitter/index.html @@ -0,0 +1,133 @@ +--- +title: AudioContext.createChannelSplitter() +slug: Web/API/AudioContext/createChannelSplitter +translation_of: Web/API/BaseAudioContext/createChannelSplitter +--- +

{{ APIRef("Web Audio API") }}

+ +
+

インターフェースのcreateChannelSplitter()メソッドは、オーディオストリームを個別に処理するためにチャンネルを分離する{{domxref("ChannelSplitterNode")}}を生成します。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var splitter = audioCtx.createChannelSplitter(numberOfOutputs);
+ +

引数

+ +
+
numberOfOutputs
+
入力オーディオストリームを分ける数。引数の指定がなければ6。
+
+ +

Returns

+ +

{{domxref("ChannelSplitterNode")}}

+ +

+ +

この例ではステレオトラックを分け、左右のチャンネルをそれぞれ別に処理する方法を示しています。これを使うためには、{{domxref("AudioNode.connect(AudioNode)") }}メソッドの2番目と3番目の引数を使い、接続元と接続先のチャンネルの番号を指定する必要があります。

+ +
var ac = new AudioContext();
+ac.decodeAudioData(someStereoBuffer, function(data) {
+ var source = ac.createBufferSource();
+ source.buffer = data;
+ var splitter = ac.createChannelSplitter(2);
+ source.connect(splitter);
+ var merger = ac.createChannelMerger(2);
+
+ // 左チャンネルのボリュームのみ小さくする
+ var gain = ac.createGain();
+ gain.value = 0.5;
+ splitter.connect(gain, 0);
+
+ // splitterをmergerの2番目の入力にして戻す
+ // ここではチャンネルを入れ替えることで、ステレオ音声の左右を逆にしている
+ gain.connect(merger, 0, 1);
+ splitter.connect(merger, 1, 0);
+
+ var dest = ac.createMediaStreamDestination();
+
+ // ChannelMergerNodeを使ったのでステレオのMediaStreamとなった
+ // webオーディオグラフのWebRTCやMediaRecorderなどに渡す
+ merger.connect(dest);
+});
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createChannelSplitter-ChannelSplitterNode-unsigned-long-numberOfOutputs', 'createChannelSplitter()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createconvolver/index.html b/files/ja/web/api/baseaudiocontext/createconvolver/index.html new file mode 100644 index 0000000000..ae5acf59c8 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createconvolver/index.html @@ -0,0 +1,131 @@ +--- +title: AudioContext.createConvolver() +slug: Web/API/AudioContext/createConvolver +translation_of: Web/API/BaseAudioContext/createConvolver +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateConvolver()メソッドは、音声にリバーブ効果などを適用する{{ domxref("ConvolverNode") }}を生成します。詳細はspec definition of Convolutionを参照してください。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var convolver = audioCtx.createConvolver();
+ +

戻り値

+ +

{{domxref("ConvolverNode")}}

+ +

+ +

次の例は畳み込みノードを生成する基礎的なAudioContextの使い方を示しています。まず、畳み込み(インパルス応答)が適用される音声が書き込まれたAudioBufferを生成し、そしてそれに畳み込みを適用します。例ではコンサートホールの群集の短い音声を使っていて、深く音響したリバーブ効果がかかっています。

+ +

例と情報の応用は、Voice-change-O-maticデモ(ソースコード)をチェックしてください。

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var convolver = audioCtx.createConvolver();
+
+  ...
+
+// XHRで畳み込みノードのための音声トラックを得る
+
+var soundSource, concertHallBuffer;
+
+ajaxRequest = new XMLHttpRequest();
+ajaxRequest.open('GET', 'concert-crowd.ogg', true);
+ajaxRequest.responseType = 'arraybuffer';
+
+ajaxRequest.onload = function() {
+  var audioData = ajaxRequest.response;
+  audioCtx.decodeAudioData(audioData, function(buffer) {
+      concertHallBuffer = buffer;
+      soundSource = audioCtx.createBufferSource();
+      soundSource.buffer = concertHallBuffer;
+    }, function(e){"Error with decoding audio data" + e.err});
+}
+
+ajaxRequest.send();
+
+  ...
+
+convolver.buffer = concertHallBuffer;
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createConvolver-ConvolverNode', 'createConvolver()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createdelay/index.html b/files/ja/web/api/baseaudiocontext/createdelay/index.html new file mode 100644 index 0000000000..709a8a375b --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createdelay/index.html @@ -0,0 +1,143 @@ +--- +title: AudioContext.createDelay() +slug: Web/API/AudioContext/createDelay +translation_of: Web/API/BaseAudioContext/createDelay +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateDelay()メソッドは、入力音声信号を一定時間遅らせる{{domxref("DelayNode")}}を生成します。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var synthDelay = audioCtx.createDelay(maxDelayTime);
+ +

引数

+ +
+
maxDelayTime
+
音声信号の最大遅れ時間の秒数。デフォルトは0
+
+ +

戻り値

+ +

{{domxref("DelayNode")}}

+ +

+ +

ループする3つの異なる簡単な例を用意しました。create-delayを見てください。(ソースコードも閲覧できます。)ただPlayボタンを押すと、ループはすぐ始まります。スライダーを右に動かしPlayボタンを押すと、待ち時間が挿入され、少し時間が過ぎるまで再生が始まりません。

+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var synthDelay = audioCtx.createDelay(5.0);
+
+  ...
+
+var synthSource;
+
+playSynth.onclick = function() {
+  synthSource = audioCtx.createBufferSource();
+  synthSource.buffer = buffers[2];
+  synthSource.loop = true;
+  synthSource.start();
+  synthSource.connect(synthDelay);
+  synthDelay.connect(destination);
+  this.setAttribute('disabled', 'disabled');
+}
+
+stopSynth.onclick = function() {
+  synthSource.disconnect(synthDelay);
+  synthDelay.disconnect(destination);
+  synthSource.stop();
+  playSynth.removeAttribute('disabled');
+}
+
+...
+
+var delay1;
+rangeSynth.oninput = function() {
+delay1 = rangeSynth.value;
+synthDelay.delayTime.value = delay1;
+}
+
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createDelay-DelayNode-double-maxDelayTime', 'createDelay()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参照

+ + diff --git a/files/ja/web/api/baseaudiocontext/createdynamicscompressor/index.html b/files/ja/web/api/baseaudiocontext/createdynamicscompressor/index.html new file mode 100644 index 0000000000..2fa5ca43ed --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createdynamicscompressor/index.html @@ -0,0 +1,138 @@ +--- +title: AudioContext.createDynamicsCompressor() +slug: Web/API/AudioContext/createDynamicsCompressor +translation_of: Web/API/BaseAudioContext/createDynamicsCompressor +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateDynamicsCompressor()メソッドは、音声信号にコンプレッサーを適用する{{domxref("DynamicsCompressorNode")}}を生成します。

+
+ +

コンプレッサーは、音声信号の最大部分の音量を小さくし、最小部分の音量を大きくします。一般的に、より大きく、豊かで、高密度な音になります。これはゲームや音楽アプリケーションでたくさんの別々の音を同時に再生する場合に特に重要です。このような場合、全体の音量の操作したり、出力音声のクリッピング(ひずみ)を避けたいはずです。

+ +

構文

+ +
var audioCtx = new AudioContext();
+var compressor = audioCtx.createDynamicsCompressor();
+ +

戻り値

+ +

{{domxref("DynamicsCompressorNode")}}

+ +

+ +

音声トラックにコンプレッサーを追加するためにcreateDynamicsCompressor()を使う簡単なデモコードです。より完全なサンプルは、basic Compressor example (ソースコードの閲覧)を参照してください。

+ +
// MediaElementAudioSourceNodeを生成する
+// そこにHTMLMediaElementを入れる
+var source = audioCtx.createMediaElementSource(myAudio);
+
+// コンプレッサーノードを生成する
+var compressor = audioCtx.createDynamicsCompressor();
+compressor.threshold.value = -50;
+compressor.knee.value = 40;
+compressor.ratio.value = 12;
+compressor.reduction.value = -20;
+compressor.attack.value = 0;
+compressor.release.value = 0.25;
+
+// AudioBufferSourceNodeを行き先(destination)につなげる
+source.connect(audioCtx.destination);
+
+button.onclick = function() {
+  var active = button.getAttribute('data-active');
+  if(active == 'false') {
+    button.setAttribute('data-active', 'true');
+    button.innerHTML = 'Remove compression';
+
+    source.disconnect(audioCtx.destination);
+    source.connect(compressor);
+    compressor.connect(audioCtx.destination);
+  } else if(active == 'true') {
+    button.setAttribute('data-active', 'false');
+    button.innerHTML = 'Add compression';
+
+    source.disconnect(compressor);
+    compressor.disconnect(audioCtx.destination);
+    source.connect(audioCtx.destination);
+  }
+}
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createDynamicsCompressor-DynamicsCompressorNode', 'createDynamicsCompressor()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/creategain/index.html b/files/ja/web/api/baseaudiocontext/creategain/index.html new file mode 100644 index 0000000000..c536a0621c --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/creategain/index.html @@ -0,0 +1,128 @@ +--- +title: AudioContext.createGain() +slug: Web/API/AudioContext/createGain +translation_of: Web/API/BaseAudioContext/createGain +--- +

{{ APIRef("Web Audio API") }}

+ +
+

インターフェースのcreateGain()メソッドは、音声の全体的なボリュームを操作する{{ domxref("GainNode") }}を生成します。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var gainNode = audioCtx.createGain();
+ +

戻り値

+ +

{{domxref("GainNode")}}

+ +

+ +

次の例では{{domxref("AudioContext")}}、GainNodeを生成する基本的な使い方を示しています。生成したGainNodeは、Muteボタンを押したときにgainプロパティの値を設定することで、無音・無音解除するために使っています。完全な例と情報は、Voice-change-O-maticデモ(ソースの閲覧)をクリックしてください。

+ +
<div>
+  <a class="mute">Mute button</a>
+</div>
+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var gainNode = audioCtx.createGain();
+var mute = document.querySelector('.mute');
+
+source.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+
+  ...
+
+mute.onclick = voiceMute;
+
+function voiceMute() {
+  if(mute.id == "") {
+    gainNode.gain.value = 0;
+    mute.id = "activated";
+    mute.innerHTML = "Unmute";
+  } else {
+    gainNode.gain.value = 1;
+    mute.id = "";
+    mute.innerHTML = "Mute";
+  }
+}
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createGain-GainNode', 'createGain()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createoscillator/index.html b/files/ja/web/api/baseaudiocontext/createoscillator/index.html new file mode 100644 index 0000000000..e971400f5d --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createoscillator/index.html @@ -0,0 +1,111 @@ +--- +title: AudioContext.createOscillator() +slug: Web/API/AudioContext/createOscillator +translation_of: Web/API/BaseAudioContext/createOscillator +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateOscillator()メソッドは、周期的な波形を発生源である{{ domxref("OscillatorNode") }}を生成します。これは基礎的な音源です。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var oscillator = audioCtx.createOscillator();
+ +

戻り値

+ +

{{domxref("OscillatorNode")}}

+ +

+ +

次の例はオシレーターノードを生成する基礎的なAudioContextの使い方を示しています。例と情報の応用は、Voice-change-O-maticデモ(ソースコード)をチェックしてください。また、{{ domxref("OscillatorNode") }}にはより詳細な情報があります。

+ +
// webオーディオAPIコンテキストを生成する
+var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+
+// オシレーターノードを生成する
+var oscillator = audioCtx.createOscillator();
+
+oscillator.type = 'square';
+oscillator.frequency.value = 3000; // 値はHz(ヘルツ)
+oscillator.start();
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createOscillator-OscillatorNode', 'createOscillator')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createpanner/index.html b/files/ja/web/api/baseaudiocontext/createpanner/index.html new file mode 100644 index 0000000000..1b30c60a03 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createpanner/index.html @@ -0,0 +1,198 @@ +--- +title: AudioContext.createPanner() +slug: Web/API/AudioContext/createPanner +translation_of: Web/API/BaseAudioContext/createPanner +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }} の createPanner() を利用すると、新しい {{domxref("PannerNode")}} を作成できます。これは空間音響を実現するために利用されます。

+ +

作成された PannerNode は、音声の聴取者の位置と向きから空間的な再生を行います。聴取者の位置と向きは、 {{domxref("AudioListener") }} オブジェクトとして表現され、{{domxref("AudioContext.listener") }} で参照できます。

+
+ +

記法

+ +
var audioCtx = new AudioContext();
+var panner = audioCtx.createPanner();
+ +

返り値

+ +

{{domxref("PannerNode")}} を返します。

+ +

利用例

+ +

以下の例では、createPanner() メソッドの利用方法と、 {{domxref("AudioListener")}} と{{domxref("PannerNode")}} による空間音響のコントロール方法について解説します。一般的には、聴取者と音源の 3 次元空間上での位置を決め、アプリケーションの動きに合わせてそれらを更新することになります。これを利用することで、キャラクターが世界の中を動き回るようなゲームで、近づくと聞こえ、遠ざかると聞こえなくなるステレオを実現できます。 以下の例では moveRight()moveLeft()、PositionPanner() などを利用して、位置をコントロールしています。

+ +

完全な実装例は panner-node example (ソースコード) を確認してください。このデモでは 2.5 次元上の「メタルの部屋」上で、曲を再生するラジカセの位置を変更させることで変化する音声を体験できます。

+ +

付記:以下の例では比較的新しい属性を利用するために、ブラウザの機能を調べています。例えば位置を設定する {{domxref("AudioListener.forwardX")}}) などです。これらが利用できる場合は利用し、そうでない場合は{{domxref("AudioListener.setOrientation()")}}) のような古いメソッドを利用しています。

+ +
// set up listener and panner position information
+var WIDTH = window.innerWidth;
+var HEIGHT = window.innerHeight;
+
+var xPos = Math.floor(WIDTH/2);
+var yPos = Math.floor(HEIGHT/2);
+var zPos = 295;
+
+// define other variables
+
+var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+
+var panner = audioCtx.createPanner();
+panner.panningModel = 'HRTF';
+panner.distanceModel = 'inverse';
+panner.refDistance = 1;
+panner.maxDistance = 10000;
+panner.rolloffFactor = 1;
+panner.coneInnerAngle = 360;
+panner.coneOuterAngle = 0;
+panner.coneOuterGain = 0;
+
+if(panner.orientationX) {
+  panner.orientationX.value = 1;
+  panner.orientationY.value = 0;
+  panner.orientationZ.value = 0;
+} else {
+  panner.setOrientation(1,0,0);
+}
+
+var listener = audioCtx.listener;
+
+if(listener.forwardX) {
+  listener.forwardX.value = 0;
+  listener.forwardY.value = 0;
+  listener.forwardZ.value = -1;
+  listener.upX.value = 0;
+  listener.upY.value = 1;
+  listener.upZ.value = 0;
+} else {
+  listener.setOrientation(0,0,-1,0,1,0);
+}
+
+var source;
+
+var play = document.querySelector('.play');
+var stop = document.querySelector('.stop');
+
+var boomBox = document.querySelector('.boom-box');
+
+var listenerData = document.querySelector('.listener-data');
+var pannerData = document.querySelector('.panner-data');
+
+leftBound = (-xPos) + 50;
+rightBound = xPos - 50;
+
+xIterator = WIDTH/150;
+
+// listener will always be in the same place for this demo
+
+if(listener.positionX) {
+  listener.positionX.value = xPos;
+  listener.positionY.value = yPos;
+  listener.positionZ.value = 300;
+} else {
+  listener.setPosition(xPos,yPos,300);
+}
+
+listenerData.innerHTML = 'Listener data: X ' + xPos + ' Y ' + yPos + ' Z ' + 300;
+
+// panner will move as the boombox graphic moves around on the screen
+function positionPanner() {
+  if(panner.positionX) {
+    panner.positionX.value = xPos;
+    panner.positionY.value = yPos;
+    panner.positionZ.value = zPos;
+  } else {
+    panner.setPosition(xPos,yPos,zPos);
+  }
+  pannerData.innerHTML = 'Panner data: X ' + xPos + ' Y ' + yPos + ' Z ' + zPos;
+}
+ +
+

listener と panner に設定された位置が正しく機能するためには、それらがスクリーン上の位置を正しく反映している必要があります。そのためには少し面倒な計算が必要となりますが、すこしやれば慣れる類のものです。

+
+ +

仕様

+ + + + + + + + + + + + + + +
仕様状況コメント
{{SpecName('Web Audio API', '#widl-AudioContext-createPanner-PannerNode', 'createPanner()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザー互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidEdgeFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

関連情報

+ + diff --git a/files/ja/web/api/baseaudiocontext/createperiodicwave/index.html b/files/ja/web/api/baseaudiocontext/createperiodicwave/index.html new file mode 100644 index 0000000000..825a1a8de5 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createperiodicwave/index.html @@ -0,0 +1,139 @@ +--- +title: AudioContext.createPeriodicWave() +slug: Web/API/AudioContext/createPeriodicWave +translation_of: Web/API/BaseAudioContext/createPeriodicWave +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreatePeriodicWave()メソッドは、周期的な波形を定義するために使われる{{domxref("PeriodicWave")}}を生成します。これは{{ domxref("OscillatorNode") }}の出力を決めるために使われます。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var wave = audioCtx.createPeriodicWave(real, imag);
+ +

戻り値

+ +

{{domxref("PeriodicWave")}}

+ +

引数

+ +
+
real
+
余弦項の配列 (伝統的なA項)
+
imag
+
正弦項の配列 (伝統的なB項)
+
+ +

+ +

The following example illustrates simple usage of createPeriodicWave(), to create a {{domxref("PeriodicWave")}} object containing a simple sine wave.

+ +
var real = new Float32Array(2);
+var imag = new Float32Array(2);
+var ac = new AudioContext();
+var osc = ac.createOscillator();
+
+real[0] = 0;
+imag[0] = 0;
+real[1] = 1;
+imag[1] = 0;
+
+var wave = ac.createPeriodicWave(real, imag);
+
+osc.setPeriodicWave(wave);
+
+osc.connect(ac.destination);
+
+osc.start();
+osc.stop(2);
+ +

This works because a sound that contains only a fundamental tone is by definition a sine wave.
+
+ Here, we create a PeriodicWave with two values. The first value is the DC offset, which is the value at which the oscillator starts. 0 is good here, because we want to start the curve at the middle of the [-1.0; 1.0] range.

+ +

The second and subsequent values are sine and cosine components. You can think of it as the result of a Fourier transform, where you get frequency domain values from time domain value. Here, with createPeriodicWave(), you specify the frequencies, and the browser performs a an inverse Fourier transform to get a time domain buffer for the frequency of the oscillator. Here, we only set one component at full volume (1.0) on the fundamental tone, so we get a sine wave.

+ +

The coefficients of the Fourier transform should be given in ascending order (i.e. (a+bi)ei,(c+di)e2i,(f+gi)e3i\left(a+bi\right)e^{i} , \left(c+di\right)e^{2i} , \left(f+gi\right)e^{3i}   etc.) and can be positive or negative.  A simple way of manually obtaining such coefficients (though not the best) is to use a graphing calculator.

+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createPeriodicWave-PeriodicWave-Float32Array-real-Float32Array-imag', 'createPeriodicWave')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatVersionUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(33.0)}}
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/createscriptprocessor/index.html b/files/ja/web/api/baseaudiocontext/createscriptprocessor/index.html new file mode 100644 index 0000000000..d3c80ae2cb --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createscriptprocessor/index.html @@ -0,0 +1,69 @@ +--- +title: AudioContext.createScriptProcessor() +slug: Web/API/AudioContext/createScriptProcessor +translation_of: Web/API/BaseAudioContext/createScriptProcessor +--- +

{{ APIRef("AudioContext") }}

+
+

{{ domxref("AudioContext") }} の createScriptProcessor() メソッドを利用することで、ダイレクトな音声処理ができる {{domxref("ScriptProcessorNode")}} オブジェクトを作成できます。

+
+
+

注意: このノードの利用方法に関しては {{domxref("ScriptProcessorNode")}} をご覧ください。

+
+

構文

+
 ScriptProcessorNode             createScriptProcessor (optional unsigned long bufferSize = 0 , optional unsigned long numberOfInputChannels = 2 , optional unsigned long numberOfOutputChannels = 2 );
+

+

createScriptProcessor()の利用例は以下の通りになります。Web Audio API が提供する機能では望む音声処理を実現できない場合に、このメソッドを利用します。これを利用することで、どの様な音声処理でも記述できます。

+
SineWave = function(context) {
+  var that = this;
+  this.x = 0; // Initial sample number
+  this.context = context;
+  this.node = context.createScriptProcessor(1024, 1, 1);
+  this.node.onaudioprocess = function(e) { that.process(e) };
+}
+
+SineWave.prototype.process = function(e) {
+  var data = e.outputBuffer.getChannelData(0);
+  for (var i = 0; i < data.length; ++i) {
+    data[i] = Math.sin(this.x++);
+  }
+}
+
+SineWave.prototype.play = function() {
+  this.node.connect(this.context.destination);
+}
+
+SineWave.prototype.pause = function() {
+  this.node.disconnect();
+}
+

引数

+
+
+ bufferSize
+
+ サンプルフレームを単位としたバッファのサイズです。指定する場合は、次のいずれかの値でなくてはなりません: 256, 512, 1024, 2048, 4096, 8192, 16384 。指定されない場合、もしくは 0 が指定された場合、環境における最適な値が設定されます。この値はノードが生存する限り同じ値が利用され、その値は 2 の冪上です。
+
+ この値は audioprocess イベントの発生頻度と、イベントごとに渡されるサンプルフレームの大きさを決めます。小さい値を指定すると低遅延となり、大きな値を指定すると音声の破損やグリッチを避けられます。この値は自分で決めず、実装に決めさせることが遅延と品質の面から推奨されます。
+
+ numberOfInputChannels
+
+ 入力のチャンネル数を整数で指定します。デフォルト値は 2 で、最大 32 チャンネルまでサポートします。
+
+ numberOfOutputChannels
+
+ 出力するチャンネル数を整数で指定します。デフォルト値は 2 で、最大 32 チャンネルまでサポートします。
+
+
+

Important: Webkit currently (version 31) requires that a valid bufferSize be passed when calling this method.

+
+
+

注意: numberOfInputChannelsnumberOfOutputChannels の両方に 0 を指定することはできません。

+
+

返り値

+

A {{domxref("ScriptProcessorNode")}}.

+

ブラウザ互換性

+

{{page("/en-US/docs/Web/API/AudioContext","Browser_compatibility")}}

+

仕様

+

{{page("/en-US/docs/Web/API/AudioContext","Specifications")}}

+

関連情報

+

{{page("/en-US/docs/Web/API/AudioContext","See_also")}}

diff --git a/files/ja/web/api/baseaudiocontext/createstereopanner/index.html b/files/ja/web/api/baseaudiocontext/createstereopanner/index.html new file mode 100644 index 0000000000..c77689aa90 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/createstereopanner/index.html @@ -0,0 +1,128 @@ +--- +title: AudioContext.createStereoPanner() +slug: Web/API/AudioContext/createStereoPanner +translation_of: Web/API/BaseAudioContext/createStereoPanner +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcreateStereoPanner()メソッドは、音源にステレオパンニングを適用する{{ domxref("StereoPannerNode") }}を生成します。入力されたオーディオストリームは、低コストなequal-powerパンニングアルゴリズムで位置が決められます。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var panNode = audioCtx.createStereoPanner();
+ +

戻り値

+ +

{{domxref("StereoPannerNode")}}

+ +

+ +

このStereoPannerNodeサンプル(ソースコード)のHTMLには、{{htmlelement("audio")}}要素と、パン値を増減させるスライダー{{domxref("input")}}しかありません。JavaScpriptでは、{{domxref("MediaElementAudioSourceNode")}}と{{domxref("StereoPannerNode")}}を生成し、この2つをconnect()メソッドで接続しています。そして、スライダーを動かすと、oninputイベントハンドラで{{domxref("StereoPannerNode.pan")}}パラメータの値を変更し、ディスプレイのパン値を更新しています。

+ +

スライダーを左から右に動かすと、音楽のスピーカーからの出力が左から右にパンされます。

+ +
var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+var myAudio = document.querySelector('audio');
+
+var panControl = document.querySelector('.panning-control');
+var panValue = document.querySelector('.panning-value');
+
+pre.innerHTML = myScript.innerHTML;
+
+// MediaElementAudioSourceNodeを生成し、そこにHTMLMediaElementを入れる
+var source = audioCtx.createMediaElementSource(myAudio);
+
+// ステレオパンナーを生成する
+var panNode = audioCtx.createStereoPanner();
+
+// イベントハンドラ関数で、スライダーが動いたとき左右のパンの値を左右する
+
+panControl.oninput = function() {
+  panNode.pan.value = panControl.value;
+  panValue.innerHTML = panControl.value;
+}
+
+// AudioBufferSourceNodeをpanNodeに接続し、panNodeを行き先(destination)に接続する
+// これでこのコントロールで音楽をパンを調整することができる
+source.connect(panNode);
+panNode.connect(audioCtx.destination);
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-createStereoPanner-StereoPannerNode', 'createStereoPanner()')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(42.0)}}{{CompatGeckoDesktop(37.0)}} {{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}37.02.2{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/currenttime/index.html b/files/ja/web/api/baseaudiocontext/currenttime/index.html new file mode 100644 index 0000000000..0d2a92b3ea --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/currenttime/index.html @@ -0,0 +1,112 @@ +--- +title: AudioContext.currentTime +slug: Web/API/AudioContext/currentTime +translation_of: Web/API/BaseAudioContext/currentTime +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのcurrentTime読み取り専用プロパティは、再生、タイムラインの可視化などのスケジューリングで使用できる単純増加するハードウェア時間をdoubleの秒数で返します。0から始まります。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+console.log(audioCtx.currentTime);
+ +

+ +

double

+ +

+ +
+

注: 完全な実装の例は、MDN Github repopanner-nodeなどを参照してください。audioCtx.currentTimeをあなたのブラウザで使ってみてください。

+
+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+// 古いwebkit/blinkブラウザではプレフィックスが必要です
+
+...
+
+console.log(audioCtx.currentTime);
+
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-currentTime', 'currentTime')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/decodeaudiodata/index.html b/files/ja/web/api/baseaudiocontext/decodeaudiodata/index.html new file mode 100644 index 0000000000..db9c106e52 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/decodeaudiodata/index.html @@ -0,0 +1,155 @@ +--- +title: AudioContext.decodeAudioData() +slug: Web/API/AudioContext/decodeAudioData +tags: + - API + - Audio + - AudioContext + - BaseAudioContext + - Method + - Reference + - Web Audio API + - decodeAudioData +translation_of: Web/API/BaseAudioContext/decodeAudioData +--- +

{{ APIRef("Web Audio API") }}

+ +

decodeAudioData() は {{ domxref("BaseAudioContext") }} のメソッドで、 {{domxref("ArrayBuffer")}} に書き込まれた音声ファイルデータを非同期にデコードするために使用されます。この場合、 ArrayBuffer は {{domxref("XMLHttpRequest")}} と {{domxref("FileReader")}} から読み込まれます。デコードされた {{domxref("AudioBuffer")}} は {{domxref("AudioContext")}} のサンプリングレートにリサンプリングされ、コールバックやプロミスに渡されます。

+ +

この方法は、オーディオトラックから Web Audio API 用のオーディオソースを作成する際に推奨される方法です。この方法は、音声ファイルの断片的なデータではなく、完全なファイルデータに対してのみ動作します。

+ +

構文

+ +

古いコールバック構文:

+ +
baseAudioContext.decodeAudioData(ArrayBuffer, successCallback, errorCallback);
+ +

新しいプロミスベースの構文:

+ +
Promise<decodedData> baseAudioContext.decodeAudioData(ArrayBuffer);
+ +

引数

+ +
+
ArrayBuffer
+
デコードする音声データが入った ArrayBuffer です。通常は{{domxref("XMLHttpRequest")}}, {{domxref("WindowOrWorkerGlobalScope.fetch()")}}, {{domxref("FileReader")}} から取得します。
+
successCallback
+
デコードが完了すると呼び出されるコールバック関数です。このコールバックの引数は1つで、 decodedData (デコードされた PCM 音声データ) を表す {{domxref("AudioBuffer")}} です。通常は、デコードされたデータを {{domxref("AudioBufferSourceNode")}} に入れて、そこから再生したり、好きなように操作したりすることができます。
+
errorCallback
+
任意のエラーコールバックで、音声データのデコードでエラーが発生すると呼び出されます。
+
+ +

返値

+ +

なし、または decodedData で満足する {{domxref("Promise") }} オブジェクトで.

+ +

+ +

ここでは最初に古いコールバックベースのシステムを、次に新しいプロミスベースの構文を取り上げます。

+ +

古いコールバックベースの構文

+ +

この例では、 getData() 関数は XHR を使用して音声トラックを読み込み、リクエストの responseTypearraybuffer に設定して、レスポンスとして配列バッファーを返すようにして、それを audioData 変数に格納しています。それからこのバッファーを decodeAudioData() 関数に渡します。成功したコールバックは、デコードに成功した PCM データを受け取り、 {{ domxref("AudioContext.createBufferSource()") }} で作成した {{ domxref("AudioBufferSourceNode") }} に入れ、ソースを {{domxref("AudioContext.destination") }} に接続してループするように設定します。

+ +

ボタンは単に getData() を実行して、それぞれトラックの読み込みと再生、停止を行うだけです。ソースの stop() メソッドが呼ばれると、ソースは消滅します。

+ +
+

注: ライブ例の実行 (またはソースの閲覧) もできます。

+
+ +
// 変数の定義
+
+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');
+
+// 音声トラックの読み込みには XHR を使い、
+// decodeAudioData でデコードし、バッファーに格納する
+// そして、そのバッファーを source に設定する
+
+function getData() {
+  source = audioCtx.createBufferSource();
+  var request = new XMLHttpRequest();
+
+  request.open('GET', 'viper.ogg', true);
+
+  request.responseType = 'arraybuffer';
+
+
+  request.onload = function() {
+    var audioData = request.response;
+
+    audioCtx.decodeAudioData(audioData, function(buffer) {
+        source.buffer = buffer;
+
+        source.connect(audioCtx.destination);
+        source.loop = true;
+      },
+
+      function(e){ console.log("Error with decoding audio data" + e.err); });
+
+  }
+
+  request.send();
+}
+
+// 音声の停止と再生を行うボタン
+
+play.onclick = function() {
+  getData();
+  source.start(0);
+  play.setAttribute('disabled', 'disabled');
+}
+
+stop.onclick = function() {
+  source.stop(0);
+  play.removeAttribute('disabled');
+}
+
+
+// pre要素にスクリプトを設定する
+
+pre.innerHTML = myScript.innerHTML;
+ +

新しいプロミスベースの構文

+ +
ctx.decodeAudioData(audioData).then(function(decodedData) {
+ // デコードしたデータをここで使う
+});
+ +

仕様書

+ + + + + + + + + + + + + + + + +
仕様状態備考
{{SpecName('Web Audio API', '#dom-baseaudiocontext-decodeaudiodata', 'decodeAudioData()')}}{{Spec2('Web Audio API')}}
+ +

ブラウザーの互換性

+ +
+ + +

{{Compat("api.BaseAudioContext.decodeAudioData")}}

+
+ +

関連情報

+ + diff --git a/files/ja/web/api/baseaudiocontext/destination/index.html b/files/ja/web/api/baseaudiocontext/destination/index.html new file mode 100644 index 0000000000..f93e8682f1 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/destination/index.html @@ -0,0 +1,114 @@ +--- +title: AudioContext.destination +slug: Web/API/AudioContext/destination +translation_of: Web/API/BaseAudioContext/destination +--- +

{{ APIRef("Web Audio API") }}

+ +
+

インターフェースのdestinationプロパティは、コンテキストの全ての音声の最終的な行き先を表す{{ domxref("AudioDestinationNode") }} を戻します。これは、あなたのコンピュータのスピーカーのような、オーディオレンダリングデバイスと考えることができます。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+gainNode.connect(audioCtx.destination);
+ +

+ +

{{ domxref("AudioDestinationNode") }}

+ +

+ +
+

注: 完全な実装の例は、MDN Github repopanner-nodeなどを参照してください。

+
+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+// 古いwebkit/blinkブラウザではプレフィックスが必要です
+
+var oscillatorNode = audioCtx.createOscillator();
+var gainNode = audioCtx.createGain();
+
+oscillatorNode.connect(gainNode);
+gainNode.connect(audioCtx.destination);
+
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-destination', 'destination')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/listener/index.html b/files/ja/web/api/baseaudiocontext/listener/index.html new file mode 100644 index 0000000000..7b4f394727 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/listener/index.html @@ -0,0 +1,112 @@ +--- +title: AudioContext.listener +slug: Web/API/AudioContext/listener +translation_of: Web/API/BaseAudioContext/listener +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのlistenerプロパティは、3次元音声を実装するために使う{{ domxref("AudioListener") }}オブジェクトを返します。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var myListener = audioCtx.listener;
+ +

+ +

{{ domxref("AudioListener") }}

+ +

+ +
+

注: 完全な実装の例は、panner-nodeを参照してください。

+
+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+// 古いwebkit/blinkブラウザではプレフィックスが必要です
+
+...
+
+var myListener = audioCtx.listener;
+
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-listener', 'listener')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/onstatechange/index.html b/files/ja/web/api/baseaudiocontext/onstatechange/index.html new file mode 100644 index 0000000000..5ce3ecaf26 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/onstatechange/index.html @@ -0,0 +1,101 @@ +--- +title: AudioContext.onstatechange +slug: Web/API/AudioContext/onstatechange +translation_of: Web/API/BaseAudioContext/onstatechange +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのonstatechangeプロパティは、{{Event("statechange")}}イベントが発火した(これはオーディオコンテキストの状態が変わったとき発生します)とき呼ばれるイベントハンドラ関数を定義します。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+audioCtx.onstatechange = function() { ... };
+ +

+ +

次のスニペットはAudioContext states デモの一部です(すぐに実行)。{{domxref("AudioContext.onstatechange")}}ハンドラは、状態が変わるたびにコンソールにログを出力するために使われています。

+ +
audioCtx.onstatechange = function() {
+  console.log(audioCtx.state);
+}
+
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-onstatechange', 'onstatechange')}}{{Spec2('Web Audio API')}} 
+ +

互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(43.0)}}{{CompatGeckoDesktop(40.0)}} {{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/samplerate/index.html b/files/ja/web/api/baseaudiocontext/samplerate/index.html new file mode 100644 index 0000000000..8715d8ae39 --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/samplerate/index.html @@ -0,0 +1,112 @@ +--- +title: AudioContext.sampleRate +slug: Web/API/AudioContext/sampleRate +translation_of: Web/API/BaseAudioContext/sampleRate +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのsampleRateプロパティは、このオーディオコンテキストの全てのノードで使われるサンプルレート(1秒あたりのサンプル数)を浮動小数点で返します。

+
+ +

構文

+ +
var audioCtx = new AudioContext();
+var mySampleRate = audioCtx.sampleRate;
+ +

+ +

浮動小数点

+ +

+ +
+

注: 完全な実装の例は、MDN Github repopanner-nodeなどを参照してください。audioCtx.sampleRateをあなたのブラウザで使ってみてください。

+
+ +
var AudioContext = window.AudioContext || window.webkitAudioContext;
+var audioCtx = new AudioContext();
+// 古いwebkit/blinkブラウザではプレフィックスが必要です
+
+...
+
+console.log(audioCtx.sampleRate);
+
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#widl-AudioContext-sampleRate', 'sampleRate')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome(10.0)}}{{property_prefix("webkit")}}{{CompatGeckoDesktop(25.0)}} {{CompatNo}}15.0{{property_prefix("webkit")}}
+ 22 (unprefixed)
6.0{{property_prefix("webkit")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari MobileChrome for Android
Basic support{{CompatUnknown}}26.01.2{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}33.0
+
+ +

参考

+ + diff --git a/files/ja/web/api/baseaudiocontext/state/index.html b/files/ja/web/api/baseaudiocontext/state/index.html new file mode 100644 index 0000000000..a19d03f9af --- /dev/null +++ b/files/ja/web/api/baseaudiocontext/state/index.html @@ -0,0 +1,66 @@ +--- +title: AudioContext.state +slug: Web/API/AudioContext/state +translation_of: Web/API/BaseAudioContext/state +--- +

{{ APIRef("Web Audio API") }}

+ +
+

{{ domxref("AudioContext") }}インターフェースのstate読取専用プロパティは、現在のAudioContextの状態を返します。

+
+ +

構文

+ +
baseAudioContext.state;
+ +

+ +

{{domxref("DOMString")}}。取りうる値は:

+ + + +

+ +

次のスニペットはAudioContext states デモの一部です(すぐに実行)。{{domxref("AudioContext.onstatechange")}}ハンドラは、状態が変わるたびにコンソールにログを出力するために使われています。

+ +
audioCtx.onstatechange = function() {
+  console.log(audioCtx.state);
+}
+
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Web Audio API', '#dom-baseaudiocontext-state', 'state')}}{{Spec2('Web Audio API')}} 
+ +

ブラウザ互換性

+ +
+
+ + +

{{Compat("api.BaseAudioContext.state")}}

+
+
+ +

参考

+ + diff --git a/files/ja/web/api/canvas_api/drawing_graphics_with_canvas/index.html b/files/ja/web/api/canvas_api/drawing_graphics_with_canvas/index.html deleted file mode 100644 index be09a119f7..0000000000 --- a/files/ja/web/api/canvas_api/drawing_graphics_with_canvas/index.html +++ /dev/null @@ -1,213 +0,0 @@ ---- -title: canvas に絵を描く -slug: Web/API/Canvas_API/Drawing_graphics_with_canvas -tags: - - HTML - - HTML5 - - 'HTML:Canvas' -translation_of: Web/API/Canvas_API/Tutorial -translation_of_original: Web/API/Canvas_API/Drawing_graphics_with_canvas ---- -
-

このページには、一部古い内容が含まれています。

-
- -

イントロダクション

- -

Firefox 1.5 より、 Firefox はプログラム可能な画像のための新しい HTML 要素を含みます。<canvas>WHATWG の canvas の仕様を基にしています。WhatWG canvas 仕様自体は Safari で実装された Apple の <canvas> を基にしています。クライアント上でグラフ、UI 要素、および他のカスタムグラフィックスの描画に使用することができます。

- -

<canvas> は 1 つ以上の描画コンテクスト を公開した固定サイズの描画表面を作ります。現在は 2 次元描画コンテクストのみが実装されています。 3D グラフィックスの描画には、 WebGL レンダリングコンテクストを用いると良いでしょう。

- -

2 次元描画コンテクスト

- -

初歩的な例

- -

始めに、2 つの交差した長方形を描く簡単な例を見てみましょう。片方の長方形は透明度を持っています。

- -
function draw() {
-  var myCanvas = document.getElementById('canvas');
-  var ctx = myCanvas.getContext('2d');
-
-  ctx.fillStyle = "rgb(200,0,0)";
-  ctx.fillRect (10, 10, 55, 50);
-
-  ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
-  ctx.fillRect (30, 30, 55, 50);
-}
-
- - - -
{{EmbedLiveSample('A_Simple_Example','150','150','/@api/deki/files/602/=Canvas_ex1.png')}}
- -

draw 関数は、まず canvas 要素を取得し、次にその canvas 要素 の 2 次元レンダリングコンテクストを取得しています。 ctx オブジェクトは canvas に実際に描画するのに使うことができます。例では CSS color 仕様による 2 つの異なる色を fillStyle プロパティで設定し、fillRect メソッドにより 2 つの長方形を単純に塗りつぶしています。 2 つ目の fillStyle は色と一緒に透明度を定義するために rgba() を使っています。

- -

fillRect() は矩形状の塗りつぶし、strokeRect() は矩形状の輪郭線の描画、 clearRect() はコンテクストの指定部分の消去に用います。より複雑な形を描画するにはパスを用います。

- -

パスの利用

- -

beginPath メソッドは新しいパスの作成を開始します。そして moveTolineToarcToarc などのメソッドはパスにセグメントを加えるのに使われます。パスは closePath メソッドによって閉じることが可能です。パスの作成後、fillstroke を使って canvas コンテクストにパスを描画します。

- -
function draw() {
-  var myCanvas = document.getElementById('canvas');
-  var ctx = myCanvas.getContext('2d');
-
-  ctx.fillStyle = "red";
-
-  ctx.beginPath();
-  ctx.moveTo(30, 30);
-  ctx.lineTo(150, 150);
-
-  // was: ctx.quadraticCurveTo(60, 70, 70, 150); これは間違い
-
-  ctx.bezierCurveTo(60, 70, 60, 70, 70, 150); // <- これが正しい書式 ->
-
-  ctx.lineTo(30, 30);
-
-  ctx.fill();
-}
- - - -
{{EmbedLiveSample('Using_Paths','190','190','/@api/deki/files/603/=Canvas_ex2.png')}}
- -

fill()stroke() を呼ぶと現在のパスが使われます。 もう一度塗りつぶしか輪郭線を描くにはパスを再作成しなくてはなりません。

- -

レンダリングコンテクストの状態

- -

fillStylestrokeStylelineWidthlineJoin のようなコンテクストの属性は、現在のレンダリングコンテクストの状態の一部です。 コンテクストは現在の状態を状態スタックに格納したり取り出したりするために save()restore() という 2 つのメソッドを提供してます。

- -

より複雑な例

- -

パス、状態、変換行列を用いた少し複雑な例を紹介します。 translate()scale()rotate() のコンテクストメソッドは全て現在の行列を変換します。 全ての描画された点は最初にこの行列により変換されます。

- -
function drawBowtie(ctx, fillStyle) {
-
-  ctx.fillStyle = "rgba(200,200,200,0.3)";
-  ctx.fillRect(-30, -30, 60, 60);
-
-  ctx.fillStyle = fillStyle;
-  ctx.globalAlpha = 1.0;
-  ctx.beginPath();
-  ctx.moveTo(25, 25);
-  ctx.lineTo(-25, -25);
-  ctx.lineTo(25, -25);
-  ctx.lineTo(-25, 25);
-  ctx.closePath();
-  ctx.fill();
-}
-
-function dot(ctx) {
-  ctx.save();
-  ctx.fillStyle = "black";
-  ctx.fillRect(-2, -2, 4, 4);
-  ctx.restore();
-}
-
-function draw() {
-  var ctx = document.getElementById('canvas').getContext('2d');
-
-  // 以後の全て変換はこの変換から相対的であることに注意
-  ctx.translate(45, 45);
-
-  ctx.save();
-  //ctx.translate(0, 0); // 不要
-  drawBowtie(ctx, "red");
-  dot(ctx);
-  ctx.restore();
-
-  ctx.save();
-  ctx.translate(85, 0);
-  ctx.rotate(45 * Math.PI / 180);
-  drawBowtie(ctx, "green");
-  dot(ctx);
-  ctx.restore();
-
-  ctx.save();
-  ctx.translate(0, 85);
-  ctx.rotate(135 * Math.PI / 180);
-  drawBowtie(ctx, "blue");
-  dot(ctx);
-  ctx.restore();
-
-  ctx.save();
-  ctx.translate(85, 85);
-  ctx.rotate(90 * Math.PI / 180);
-  drawBowtie(ctx, "yellow");
-  dot(ctx);
-  ctx.restore();
-}
-
- - - -
{{EmbedLiveSample('A_More_Complicated_Example','215','215','/@api/deki/files/604/=Canvas_ex3.png')}}
- -

drawBotie 関数及び dot 関数を定義し、 draw 関数内で 4 回使用しています。 それぞれを呼び出す前に、translate() 及び rotate() を現在の変換行列を用意するために用いています。その変換行列は順番に点と蝶ネクタイを配置します。 dot 関数は (0, 0) を中心に小さな黒い正方形を描画します。 dot は変換行列によって移動されます。 drawBowtie は第 1 引数に指定した塗りつぶしスタイルを使い、単純な蝶ネクタイのパスを描画します。

- -

行列の操作は累積されるので、save() 及び restore() はそれぞれが設定した元の canvas の状態に復帰するために使われます。 注目すべきは、回転が常に現在の基点の周りで起こるということです。 従って translate() rotate() translate() の連続は translate() translate() rotate() の連続実行とは異なった結果を生みます。

- -

Apple の <canvas> との互換性

- -

<canvas> は Apple の実装とその他の実装で互換性があります。 しかし、いくつかの注意すべき問題があります。

- -

必須の </canvas> タグ このセクションの内容には古い情報が含まれます

- -

Apple の Safari の実装においては、<canvas><img> とほぼ同じような方法で実装された要素で、終了タグを持っていません。 しかしながら、<canvas> がウェブで広く普及するために、 代替内容のための何らかの方法を提供しなければなりません。 したがって、Mozilla の実装では、 終了タグが必須となっています。

- -

代替内容が必要無い場合、単純に <canvas id="foo" ...></canvas> とすれば、Safari は終了タグを無視し、 Safari と Mozilla の両方で完全に互換性を持つでしょう。

- -

もし代替内容が望まれるならば、(canvas だけが描画されるべき) Safari から代替内容を隠すために、そして(代替内容が表示されるべき) IE から canvas 自体を隠すためにいくつかの CSS のトリックを使わなければなりません。

- -

現在は canvas 要素の内容には代替コンテンツを配置するように仕様書で定められています。

- -

その他の機能

- -

canvas への Web コンテンツの描画

- -
この機能は Chrome 特権コードの実行時のみに存在します。通常の HTML ページでは許可されていません。理由についてはソースをお読みください
- -

Mozilla の canvas は {{domxref("CanvasRenderingContext2D", "drawWindow()", "drawWindow()")}} メソッドで拡張できます。このメソッドは DOM window の中身のスナップショットを canvas に描画します。以下に例を示します。

- -
ctx.drawWindow(window, 0, 0, 100, 200, "rgb(255,255,255)");
-
- -

上記の例では、現在のウィンドウの、左上から (0, 0, 100, 200) 座標にある四角形の中身を、黒色背景の canvas に描き込みます。 遅くなりますが、 "rgba(255, 255, 255, 0)" と色を指定すれば、透過背景の上に中身を描画することになります。

- -

このメソッドにより、隠し IFRAME に任意の内容 (たとえば、CSS でスタイル付けされた HTML テキストや SVG) を入れて、その内容を canvas に描画することも可能です。その場合、現在の変形にしたがって、拡大縮小・回転が行われます。

- -

Ted Mielczarek の tab preview 拡張では、 Web ページのサムネイルを提供するために chrome の中でこのテクニックを使われています。ソースコードを参照してみてください。

- -
注記: Using canvas.drawWindow() while handling a document's onload event doesn't work. In Firefox 3.5 or later, you can do this in a handler for the MozAfterPaint event to successfully draw HTML content into a canvas on page load.
- -

関連情報

- - diff --git a/files/ja/web/api/canvas_api/tutorial/advanced_animations/index.html b/files/ja/web/api/canvas_api/tutorial/advanced_animations/index.html new file mode 100644 index 0000000000..d8cf43a362 --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/advanced_animations/index.html @@ -0,0 +1,380 @@ +--- +title: 高度なアニメーション +slug: Web/Guide/HTML/Canvas_tutorial/Advanced_animations +tags: + - Canvas + - Graphics + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Advanced_animations +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_animations", "Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas")}}
+ +
+

前の章では、いくつかの基本的なアニメーションを作成して、物の動かし方を学びました。このパートでは、 運動そのものをより詳細に見て、 アニメーションをより高度にするための物理を追加していきましょう。

+
+ +

ボールを描く

+ +

アニメーションの勉強のために、ボールを使おうと思うので、最初にボールを canvas 上に描きましょう。次のコードは私たちの準備をしてくれるでしょう。

+ +
<canvas id="canvas" width="600" height="300"></canvas>
+
+ +

普通は、まず描画コンテキストが必要になります。 ボールを描くため、 プロパティと canvas にボールを描くための draw() メソッドを持つ ball オブジェクトを作りましょう。

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+var ball = {
+  x: 100,
+  y: 100,
+  radius: 25,
+  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();
+ +

ここでは特別なことはなく、ball は本当に単純な円で、{{domxref("CanvasRenderingContext2D.arc()", "arc()")}} メソッドの助けを借りて描かれています。

+ +

速度の追加

+ +

ボールが手に入りましたので、このチュートリアルの前の章で習ったように、基本的なアニメーションを加えていきましょう。また {{domxref("window.requestAnimationFrame()")}} がアニメーションの制御を手助けしてくれます。The ball gets moving by adding a velocity vector to the position. For each frame, we also {{domxref("CanvasRenderingContext2D.clearRect", "clear", "", 1)}} the canvas to remove old circles from prior frames.

+ +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+
+var ball = {
+  x: 100,
+  y: 100,
+  vx: 5,
+  vy: 2,
+  radius: 25,
+  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);
+  ball.draw();
+  ball.x += ball.vx;
+  ball.y += ball.vy;
+  raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mouseover', function(e){
+  raf = window.requestAnimationFrame(draw);
+});
+
+canvas.addEventListener("mouseout",function(e){
+  window.cancelAnimationFrame(raf);
+});
+
+ball.draw();
+
+ +

境界線

+ +

Without any boundary collision testing our ball runs out of the canvas quickly. We need to check if the x and y position of the ball is out of the canvas dimensions and invert the direction of the velocity vectors. To do so, we add the following checks to the draw method:

+ +
if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
+  ball.vy = -ball.vy;
+}
+if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
+  ball.vx = -ball.vx;
+}
+ +

最初のデモ

+ +

これまでで、実際にどのように動くか見てみましょう。canvas にマウスを移動させて、アニメーションを開始してます。

+ + + +

{{EmbedLiveSample("First_demo", "610", "310")}}

+ +

加速

+ +

動きをよりリアルにするために、このような速度で再生できます。たとえば:

+ +
ball.vy *= .99;
+ball.vy += .25;
+ +

This slows down the vertical velocity each frame, so that the ball will just bounce on the floor in the end.

+ + + +

{{EmbedLiveSample("Second_demo", "610", "310")}}

+ +

後引きの効果

+ +

Until now we have made use of the {{domxref("CanvasRenderingContext2D.clearRect", "clearRect")}} method when clearing prior frames. If you replace this method with a semi-transparent {{domxref("CanvasRenderingContext2D.fillRect", "fillRect")}}, you can easily create a trailing effect.

+ +
ctx.fillStyle = 'rgba(255,255,255,0.3)';
+ctx.fillRect(0,0,canvas.width,canvas.height);
+ + + +

{{EmbedLiveSample("Third_demo", "610", "310")}}

+ +

マウスコントロールの追加

+ +

ボールに対するちょっとした制御をするために、たとえば mousemove イベントを使用してボールをマウスの動きに従わせる。といったことができます。click イベントでボールを開放して、またバウンドさせる。といったことも可能です。

+ + + +
var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+var raf;
+var running = false;
+
+var ball = {
+  x: 100,
+  y: 100,
+  vx: 5,
+  vy: 1,
+  radius: 25,
+  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);
+}
+
+function draw() {
+  clear();
+  ball.draw();
+  ball.x += ball.vx;
+  ball.y += ball.vy;
+
+  if (ball.y + ball.vy > canvas.height || ball.y + ball.vy < 0) {
+    ball.vy = -ball.vy;
+  }
+  if (ball.x + ball.vx > canvas.width || ball.x + ball.vx < 0) {
+    ball.vx = -ball.vx;
+  }
+
+  raf = window.requestAnimationFrame(draw);
+}
+
+canvas.addEventListener('mousemove', function(e){
+  if (!running) {
+    clear();
+    ball.x = e.clientX;
+    ball.y = e.clientY;
+    ball.draw();
+  }
+});
+
+canvas.addEventListener("click",function(e){
+  if (!running) {
+    raf = window.requestAnimationFrame(draw);
+    running = true;
+  }
+});
+
+canvas.addEventListener("mouseout",function(e){
+  window.cancelAnimationFrame(raf);
+  running = false;
+});
+
+ball.draw();
+
+ +

マウスを使ってボールを動かして、クリックで開放してください。

+ +

{{EmbedLiveSample("Adding_mouse_control", "610", "310")}}

+ +

ブロック崩し

+ +

This short chapter only explains some techniques to create more advanced animations. There are many more! How about adding a paddle, some bricks, and turn this demo into a Breakout game? Checkout our Game development area for more gaming related articles.

+ +

関連項目

+ + + +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_animations", "Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas")}}

diff --git a/files/ja/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html b/files/ja/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html new file mode 100644 index 0000000000..c23a5e1ce1 --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/applying_styles_and_colors/index.html @@ -0,0 +1,725 @@ +--- +title: スタイルと色を適用する +slug: Web/Guide/HTML/Canvas_tutorial/Applying_styles_and_colors +translation_of: Web/API/Canvas_API/Tutorial/Applying_styles_and_colors +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}
+ +
+

canvas に図形を描く」の章ではデフォルトの線と塗りのスタイルのみを使いました。ここではより魅力的に描くために使うことのできるcanvasのオプションについて見ていきます。具体的には、色、線のスタイル、グラデーション、パターンや影を追加する方法について学びます。

+
+ +

+ +

これまでは描画コンテキストの方法についてのみ見てきました。色を図形に適用するために、"fillStyle"と"strokeStyle"という2つの重要なプロパティを利用することができます。

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle = color")}}
+
図形の塗りつぶしのスタイルを記述する
+
{{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle = color")}}
+
図形のアウトラインのスタイルを記述する。
+
+ +

colorの部分にはCSSでの{{cssxref("<color>")}}表現やグラデーションオブジェクトまたはパターンオブジェクトが入ります。グラデーションオブジェクトとパターンオブジェクトについては後ほど学ぶことにします。 デフォルトでは、輪郭線・塗りつぶしの色は黒に設定されています。 (CSS色では#000000)

+ +
+

注記: strokeStyleおよびfillStyleプロパティを設定すると、その設定した値がデフォルトとなって、それ以降に描かれる図形の線や塗りはその色で行なわれるようになります。それぞれの図形をそれぞれ別の色で描きたい場合は、シェイプを描くごとにstrokeStyleおよびfillStyleプロパティを設定する必要があります。

+
+ +

入力できる有効な文字列は、CSS {{cssxref("<color>")}}表現の値である必要があります。 下記の例では同じ色について説明しています。

+ +
// これらは全てfillStyleにオレンジ色を代入します
+
+ctx.fillStyle = "orange";
+ctx.fillStyle = "#FFA500";
+ctx.fillStyle = "rgb(255,165,0)";
+ctx.fillStyle = "rgba(255,165,0,1)";
+
+ +

プロパティ fillStyle の例

+ +

この例では二重のforループを使って正方形からなるグリッドを作ってみたい。そしてその正方形の一つひとつは違った色になるようにしたい。結果は下のスクリーンショットのようになるだろう。かなり面白い画像ができているだろう。それぞれのブロックで別々な色を表現するために、2つの変数i,jを用いている。変数iは赤成分を、変数jは緑成分を変化させている。青成分は固定されている。By modifying the channels, you can generate all kinds of palettes. By increasing the steps, you can achieve something that looks like the color palettes Photoshop uses.

+ +
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);
+    }
+  }
+}
+ + + +

結果は以下のようになる:

+ +

{{EmbedLiveSample("A_fillStyle_example", 160, 160, "https://mdn.mozillademos.org/files/5417/Canvas_fillstyle.png")}}

+ +

プロパティ strokeStyle の例

+ +

This example is similar to the one above, but uses the strokeStyle property to change the colors of the shapes' outlines. We use the arc() method to draw circles instead of squares.

+ +
  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();
+      }
+    }
+  }
+
+ + + +

The result looks like this:

+ +

{{EmbedLiveSample("A_strokeStyle_example", "180", "180", "https://mdn.mozillademos.org/files/253/Canvas_strokestyle.png")}}

+ +

透明度のコントロール

+ +

canvasに不透明な形状を描画するだけでなく、半透明の形状を描画することもできます。 これは、globalAlphaプロパティを設定するか、輪郭線や塗りつぶしのスタイルに半透明の色を割り当てることによって行われます。

+ +
+
{{domxref("CanvasRenderingContext2D.globalAlpha", "globalAlpha = transparencyValue")}}
+
代入された透明度の値を、代入後にcanvasに描画されるすべての図形に適用します。値は0.0(完全に透明)から1.0(完全に不透明)の間でなければなりません。デフォルトでは1.0(完全に不透明)が設定されています。
+
+ +

globalAlphaプロパティは、同様の透明度でcanvasにいくつもの図形を描画する場合に役に立ちますが、それ以外の場合は、色を設定するときにそれぞれの図形に透明度を設定する方が一般的に便利です。

+ +

strokeStyleプロパティとfillStyleプロパティはCSSのrgba表現を利用できるため、次のような表記を使用して透明な色を割り当てることもできます。

+ +
// 輪郭線と塗りつぶしの色に透明色を割り当てる
+
+ctx.strokeStyle = "rgba(255,0,0,0.5)";
+ctx.fillStyle = "rgba(255,0,0,0.5)";
+
+ +

rgba()関数はrgb()関数によく似ていますが、1つ引数が増加します。最後の引数には、この色の透明度の値を設定します。有効な値の範囲は、0.0(完全に透明)から1.0(完全に不透明)です。

+ +

プロパティ globalAlpha の例

+ +

In this example, we'll draw a background of four different colored squares. On top of these, we'll draw a set of semi-transparent circles. The globalAlpha property is set at 0.2 which will be used for all shapes from that point on. Every step in the for loop draws a set of circles with an increasing radius. The final result is a radial gradient. By overlaying ever more circles on top of each other, we effectively reduce the transparency of the circles that have already been drawn. By increasing the step count and in effect drawing more circles, the background would completely disappear from the center of the image.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  // draw background
+  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';
+
+  // set transparency value
+  ctx.globalAlpha = 0.2;
+
+  // Draw semi transparent circles
+  for (i=0;i<7;i++){
+    ctx.beginPath();
+    ctx.arc(75,75,10+10*i,0,Math.PI*2,true);
+    ctx.fill();
+  }
+}
+ + + +

{{EmbedLiveSample("A_globalAlpha_example", "180", "180", "https://mdn.mozillademos.org/files/232/Canvas_globalalpha.png")}}

+ +

An example using rgba()

+ +

In this second example, we do something similar to the one above, but instead of drawing circles on top of each other, I've drawn small rectangles with increasing opacity. Using rgba() gives you a little more control and flexibility because we can set the fill and stroke style individually.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // Draw background
+  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);
+
+  // Draw semi transparent rectangles
+  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);
+    }
+  }
+}
+ + + +

{{EmbedLiveSample("An_example_using_rgba()", "180", "180", "https://mdn.mozillademos.org/files/246/Canvas_rgba.png")}}

+ +

Line styles

+ +

There are several properties which allow us to style lines.

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth", "lineWidth = value")}}
+
Sets the width of lines drawn in the future.
+
{{domxref("CanvasRenderingContext2D.lineCap", "lineCap = type")}}
+
Sets the appearance of the ends of lines.
+
{{domxref("CanvasRenderingContext2D.lineJoin", "lineJoin = type")}}
+
Sets the appearance of the "corners" where lines meet.
+
{{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit = value")}}
+
Establishes a limit on the miter when two lines join at a sharp angle, to let you control how thick the junction becomes.
+
{{domxref("CanvasRenderingContext2D.getLineDash", "getLineDash()")}}
+
Returns the current line dash pattern array containing an even number of non-negative numbers.
+
{{domxref("CanvasRenderingContext2D.setLineDash", "setLineDash(segments)")}}
+
Sets the current line dash pattern.
+
{{domxref("CanvasRenderingContext2D.lineDashOffset", "lineDashOffset = value")}}
+
Specifies where to start a dash array on a line.
+
+ +

You'll get a better understanding of what these do by looking at the examples below.

+ +

A lineWidth example

+ +

This property sets the current line thickness. Values must be positive numbers. By default this value is set to 1.0 units.

+ +

The line width is the thickness of the stroke centered on the given path. In other words, the area that's drawn extends to half the line width on either side of the path. Because canvas coordinates do not directly reference pixels, special care must be taken to obtain crisp horizontal and vertical lines.

+ +

In the example below, 10 straight lines are drawn with increasing line widths. The line on the far left is 1.0 units wide. However, the leftmost and all other odd-integer-width thickness lines do not appear crisp, because of the path's positioning.

+ +
function draw() {
+  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.stroke();
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_lineWidth_example", "180", "180", "https://mdn.mozillademos.org/files/239/Canvas_linewidth.png")}}

+ +

Obtaining crisp lines requires understanding how paths are stroked. In the images below, the grid represents the canvas coordinate grid. The squares between gridlines are actual on-screen pixels. In the first grid image below, a rectangle from (2,1) to (5,5) is filled. The entire area between them (light red) falls on pixel boundaries, so the resulting filled rectangle will have crisp edges.

+ +

+ +

If you consider a path from (3,1) to (3,5) with a line thickness of 1.0, you end up with the situation in the second image. The actual area to be filled (dark blue) only extends halfway into the pixels on either side of the path. An approximation of this has to be rendered, which means that those pixels being only partially shaded, and results in the entire area (the light blue and dark blue) being filled in with a color only half as dark as the actual stroke color. This is what happens with the 1.0 width line in the previous example code.

+ +

To fix this, you have to be very precise in your path creation. Knowing that a 1.0 width line will extend half a unit to either side of the path, creating the path from (3.5,1) to (3.5,5) results in the situation in the third image—the 1.0 line width ends up completely and precisely filling a single pixel vertical line.

+ +
+

Note: Be aware that in our vertical line example, the Y position still referenced an integer gridline position—if it hadn't, we would see pixels with half coverage at the endpoints (but note also that this behavior depends on the current lineCap style whose default value is butt; you may want to compute consistent strokes with half-pixel coordinates for odd-width lines, by setting the lineCap style to square, so that the outer border of the stroke around the endpoint will be automatically extended to cover the whole pixel exactly).

+ +

Note also that only start and final endpoints of a path are affected: if a path is closed with closePath(), there's no start and final endpoint; instead, all endpoints in the path are connected to their attached previous and next segment using the current setting of the lineJoin style, whose default value is miter, with the effect of automatically extending the outer borders of the connected segments to their intersection point, so that the rendered stroke will exactly cover full pixels centered at each endpoint if those connected segments are horizontal and/or vertical). See the next two sections for demonstrations of these additional line styles.

+
+ +

For even-width lines, each half ends up being an integer amount of pixels, so you want a path that is between pixels (that is, (3,1) to (3,5)), instead of down the middle of pixels.

+ +

While slightly painful when initially working with scalable 2D graphics, paying attention to the pixel grid and the position of paths ensures that your drawings will look correct regardless of scaling or any other transformations involved. A 1.0-width vertical line drawn at the correct position will become a crisp 2-pixel line when scaled up by 2, and will appear at the correct position.

+ +

A lineCap example

+ +

The lineCap property determines how the end points of every line are drawn. There are three possible values for this property and those are: butt, round and square. By default this property is set to butt.

+ +

+ +
+
butt
+
The ends of lines are squared off at the endpoints.
+
round
+
The ends of lines are rounded.
+
square
+
The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness.
+
+ +

In this example, we'll draw three lines, each with a different value for the lineCap property. I also added two guides to see the exact differences between the three. Each of these lines starts and ends exactly on these guides.

+ +

The line on the left uses the default butt option. You'll notice that it's drawn completely flush with the guides. The second is set to use the round option. This adds a semicircle to the end that has a radius half the width of the line. The line on the right uses the square option. This adds a box with an equal width and half the height of the line thickness.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var lineCap = ['butt','round','square'];
+
+  // Draw guides
+  ctx.strokeStyle = '#09f';
+  ctx.beginPath();
+  ctx.moveTo(10,10);
+  ctx.lineTo(140,10);
+  ctx.moveTo(10,140);
+  ctx.lineTo(140,140);
+  ctx.stroke();
+
+  // Draw lines
+  ctx.strokeStyle = 'black';
+  for (var i=0;i<lineCap.length;i++){
+    ctx.lineWidth = 15;
+    ctx.lineCap = lineCap[i];
+    ctx.beginPath();
+    ctx.moveTo(25+i*50,10);
+    ctx.lineTo(25+i*50,140);
+    ctx.stroke();
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_lineCap_example", "180", "180", "https://mdn.mozillademos.org/files/236/Canvas_linecap.png")}}

+ +

A lineJoin example

+ +

The lineJoin property determines how two connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together (degenerate segments with zero lengths, whose specified endpoints and control points are exactly at the same position, are skipped).

+ +

There are three possible values for this property: round, bevel and miter. By default this property is set to miter. Note that the lineJoin setting has no effect if the two connected segments have the same direction, because no joining area will be added in this case.

+ +

+ +
+
round
+
Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is equal to half the line width.
+
bevel
+
Fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment.
+
miter
+
Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is effected by the miterLimit property which is explained below.
+
+ +

The example below draws three different paths, demonstrating each of these three lineJoin property settings; the output is shown above.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var lineJoin = ['round','bevel','miter'];
+  ctx.lineWidth = 10;
+  for (var i=0;i<lineJoin.length;i++){
+    ctx.lineJoin = lineJoin[i];
+    ctx.beginPath();
+    ctx.moveTo(-5,5+i*40);
+    ctx.lineTo(35,45+i*40);
+    ctx.lineTo(75,5+i*40);
+    ctx.lineTo(115,45+i*40);
+    ctx.lineTo(155,5+i*40);
+    ctx.stroke();
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_lineJoin_example", "180", "180", "https://mdn.mozillademos.org/files/237/Canvas_linejoin.png")}}

+ +

A demo of the miterLimit property

+ +

As you've seen in the previous example, when joining two lines with the miter option, the outside edges of the two joining lines are extended up to the point where they meet. For lines which are at large angles with each other, this point is not far from the inside connection point. However, as the angles between each line decreases, the distance (miter length) between these points increases exponentially.

+ +

The miterLimit property determines how far the outside connection point can be placed from the inside connection point. If two lines exceed this value, a bevel join gets drawn instead. Note that the maximum miter length is the product of the line width measured in the current coordinate system, by the value of this miterLimit property (whose default value is 10.0 in the HTML {{HTMLElement("canvas")}}), so the miterLimit can be set independently from the current display scale or any affine transforms of paths: it only influences the effectively rendered shape of line edges.

+ +

More exactly, the miter limit is the maximum allowed ratio of the extension length (in the HTML canvas, it is measured between the outside corner of the joined edges of the line and the common endpoint of connecting segments specified in the path) to half the line width. It can equivalently be defined as the maximum allowed ratio of the distance between the inside and outside points of jonction of edges, to the total line width. It is then equal to the cosecant of half the minimum inner angle of connecting segments below which no miter join will be rendered, but only a bevel join:

+ + + +

Here's a little demo in which you can set miterLimit dynamically and see how this effects the shapes on the canvas. The blue lines show where the start and endpoints for each of the lines in the zig-zag pattern are.

+ +

If you specify a miterLimit value below 4.2 in this demo, none of the visible corners will join with a miter extension, but only with a small bevel near the blue lines; with a miterLimit above 10, most corners in this demo should join with a miter far away from the blue lines, and whose height is decreasing between corners from left to right because they connect with growing angles; with intermediate values, the corners on the left side will only join with a bevel near the blue lines, and the corners on the right side with a miter extension (also with a decreasing height).

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // Clear canvas
+  ctx.clearRect(0,0,150,150);
+
+  // Draw guides
+  ctx.strokeStyle = '#09f';
+  ctx.lineWidth   = 2;
+  ctx.strokeRect(-5,50,160,50);
+
+  // Set line styles
+  ctx.strokeStyle = '#000';
+  ctx.lineWidth = 10;
+
+  // check input
+  if (document.getElementById('miterLimit').value.match(/\d+(\.\d+)?/)) {
+    ctx.miterLimit = parseFloat(document.getElementById('miterLimit').value);
+  } else {
+    alert('Value must be a positive number');
+  }
+
+  // Draw lines
+  ctx.beginPath();
+  ctx.moveTo(0,100);
+  for (i=0;i<24;i++){
+    var dy = i%2==0 ? 25 : -25 ;
+    ctx.lineTo(Math.pow(i,1.5)*2,75+dy);
+  }
+  ctx.stroke();
+  return false;
+}
+
+ + + +

{{EmbedLiveSample("A_demo_of_the_miterLimit_property", "400", "180", "https://mdn.mozillademos.org/files/240/Canvas_miterlimit.png")}}

+ +

Using line dashes

+ +

The setLineDash method and the lineDashOffset property specify the dash pattern for lines. The setLineDash method accepts a list of numbers that specifies distances to alternately draw a line and a gap and the lineDashOffset property sets an offset where to start the pattern.

+ +

In this example we are creating a marching ants effect. It is an animation technique often found in selection tools of computer graphics programs. It helps the user to distinguish the selection border from the image background by animating the border. In a later part of this tutorial, you can learn how to do this and other basic animations.

+ + + +
var ctx = document.getElementById('canvas').getContext('2d');
+var offset = 0;
+
+function draw() {
+  ctx.clearRect(0,0, canvas.width, canvas.height);
+  ctx.setLineDash([4, 2]);
+  ctx.lineDashOffset = -offset;
+  ctx.strokeRect(10,10, 100, 100);
+}
+
+function march() {
+  offset++;
+  if (offset > 16) {
+    offset = 0;
+  }
+  draw();
+  setTimeout(march, 20);
+}
+
+march();
+ +

{{EmbedLiveSample("Using_line_dashes", "120", "120", "https://mdn.mozillademos.org/files/9853/marching-ants.png")}}

+ +

Gradients

+ +

Just like any normal drawing program, we can fill and stroke shapes using linear and radial gradients. We create a {{domxref("CanvasGradient")}} object by using one of the following methods. We can then assign this object to the fillStyle or strokeStyle properties.

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient", "createLinearGradient(x1, y1, x2, y2)")}}
+
Creates a linear gradient object with a starting point of (x1, y1) and an end point of (x2, y2).
+
{{domxref("CanvasRenderingContext2D.createRadialGradient", "createRadialGradient(x1, y1, r1, x2, y2, r2)")}}
+
Creates a radial gradient. The parameters represent two circles, one with its center at (x1, y1) and a radius of r1, and the other with its center at (x2, y2) with a radius of r2.
+
+ +

For example:

+ +
var lineargradient = ctx.createLinearGradient(0, 0, 150, 150);
+var radialgradient = ctx.createRadialGradient(75, 75, 0, 75, 75, 100);
+
+ +

Once we've created a CanvasGradient object we can assign colors to it by using the addColorStop() method.

+ +
+
{{domxref("CanvasGradient.addColorStop", "gradient.addColorStop(position, color)")}}
+
Creates a new color stop on the gradient object. The position is a number between 0.0 and 1.0 and defines the relative position of the color in the gradient, and the color argument must be a string representing a CSS {{cssxref("<color>")}}, indicating the color the gradient should reach at that offset into the transition.
+
+ +

You can add as many color stops to a gradient as you need. Below is a very simple linear gradient from white to black.

+ +
var lineargradient = ctx.createLinearGradient(0,0,150,150);
+lineargradient.addColorStop(0, 'white');
+lineargradient.addColorStop(1, 'black');
+
+ +

A createLinearGradient example

+ +

In this example, we'll create two different gradients. As you can see here, both the strokeStyle and fillStyle properties can accept a canvasGradient object as valid input.

+ +
function draw() {
+  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 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);
+
+}
+
+ + + +

The first is a background gradient. As you can see, we assigned two colors at the same position. You do this to make very sharp color transitions—in this case from white to green. Normally, it doesn't matter in what order you define the color stops, but in this special case, it does significantly. If you keep the assignments in the order you want them to appear, this won't be a problem.

+ +

In the second gradient, we didn't assign the starting color (at position 0.0) since it wasn't strictly necessary, because it will automatically assume the color of the next color stop. Therefore, assigning the black color at position 0.5 automatically makes the gradient, from the start to this stop, black.

+ +

{{EmbedLiveSample("A_createLinearGradient_example", "180", "180", "https://mdn.mozillademos.org/files/235/Canvas_lineargradient.png")}}

+ +

A createRadialGradient example

+ +

In this example, we'll define four different radial gradients. Because we have control over the start and closing points of the gradient, we can achieve more complex effects than we would normally have in the "classic" radial gradients we see in, for instance, Photoshop (that is, a gradient with a single center point where the gradient expands outward in a circular shape).

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // Create gradients
+  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)');
+
+  // draw shapes
+  ctx.fillStyle = radgrad4;
+  ctx.fillRect(0,0,150,150);
+  ctx.fillStyle = radgrad3;
+  ctx.fillRect(0,0,150,150);
+  ctx.fillStyle = radgrad2;
+  ctx.fillRect(0,0,150,150);
+  ctx.fillStyle = radgrad;
+  ctx.fillRect(0,0,150,150);
+}
+
+ + + +

In this case, we've offset the starting point slightly from the end point to achieve a spherical 3D effect. It's best to try to avoid letting the inside and outside circles overlap because this results in strange effects which are hard to predict.

+ +

The last color stop in each of the four gradients uses a fully transparent color. If you want to have a nice transition from this to the previous color stop, both colors should be equal. This isn't very obvious from the code because it uses two different CSS color methods as a demonstration, but in the first gradient #019F62 = rgba(1,159,98,1).

+ +

{{EmbedLiveSample("A_createRadialGradient_example", "180", "180", "https://mdn.mozillademos.org/files/244/Canvas_radialgradient.png")}}

+ +

Patterns

+ +

In one of the examples on the previous page, we used a series of loops to create a pattern of images. There is, however, a much simpler method: the createPattern() method.

+ +
+
{{domxref("CanvasRenderingContext2D.createPattern", "createPattern(image, type)")}}
+
Creates and returns a new canvas pattern object. image is a {{domxref("CanvasImageSource")}} (that is, an {{domxref("HTMLImageElement")}}, another canvas, a {{HTMLElement("video")}} element, or the like. type is a string indicating how to use the image.
+
+ +

The type specifies how to use the image in order to create the pattern, and must be one of the following string values:

+ +
+
repeat
+
Tiles the image in both vertical and horizontal directions.
+
repeat-x
+
Tiles the image horizontally but not vertically.
+
repeat-y
+
Tiles the image vertically but not horizontally.
+
no-repeat
+
Doesn't tile the image. It's used only once.
+
+ +

We use this method to create a {{domxref("CanvasPattern")}} object which is very similar to the gradient methods we've seen above. Once we've created a pattern, we can assign it to the fillStyle or strokeStyle properties. For example:

+ +
var img = new Image();
+img.src = 'someimage.png';
+var ptrn = ctx.createPattern(img,'repeat');
+
+ +
+

Note: Like with the drawImage() method, you must make sure the image you use is loaded before calling this method or the pattern may be drawn incorrectly.

+
+ +

A createPattern example

+ +

In this last example, we'll create a pattern to assign to the fillStyle property. The only thing worth noting is the use of the image's onload handler. This is to make sure the image is loaded before it is assigned to the pattern.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // create new image object to use as pattern
+  var img = new Image();
+  img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
+  img.onload = function(){
+
+    // create pattern
+    var ptrn = ctx.createPattern(img,'repeat');
+    ctx.fillStyle = ptrn;
+    ctx.fillRect(0,0,150,150);
+
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_createPattern_example", "180", "180", "https://mdn.mozillademos.org/files/222/Canvas_createpattern.png")}}

+ +

Shadows

+ +

Using shadows involves just four properties:

+ +
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX = float")}}
+
Indicates the horizontal distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY = float")}}
+
Indicates the vertical distance the shadow should extend from the object. This value isn't affected by the transformation matrix. The default is 0.
+
{{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur = float")}}
+
Indicates the size of the blurring effect; this value doesn't correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.
+
{{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor = color")}}
+
A standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.
+
+ +

The properties shadowOffsetX and shadowOffsetY indicate how far the shadow should extend from the object in the X and Y directions; these values aren't affected by the current transformation matrix. Use negative values to cause the shadow to extend up or to the left, and positive values to cause the shadow to extend down or to the right. These are both 0 by default.

+ +

The shadowBlur property indicates the size of the blurring effect; this value doesn't correspond to a number of pixels and is not affected by the current transformation matrix. The default value is 0.

+ +

The shadowColor property is a standard CSS color value indicating the color of the shadow effect; by default, it is fully-transparent black.

+ +
+

Note: Shadows are only drawn for source-over compositing operations.

+
+ +

A shadowed text example

+ +

This example draws a text string with a shadowing effect.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.shadowOffsetX = 2;
+  ctx.shadowOffsetY = 2;
+  ctx.shadowBlur = 2;
+  ctx.shadowColor = "rgba(0, 0, 0, 0.5)";
+
+  ctx.font = "20px Times New Roman";
+  ctx.fillStyle = "Black";
+  ctx.fillText("Sample String", 5, 30);
+}
+
+ + + +

{{EmbedLiveSample("A_shadowed_text_example", "180", "100", "https://mdn.mozillademos.org/files/2505/shadowed-string.png")}}

+ +

We will look at the font property and fillText method in the next chapter about drawing text.

+ +

Canvas fill rules

+ +

When using fill (or {{domxref("CanvasRenderingContext2D.clip", "clip")}} and {{domxref("CanvasRenderingContext2D.isPointInPath", "isPointinPath")}}) you can optionally provide a fill rule algorithm by which to determine if a point is inside or outside a path and thus if it gets filled or not. This is useful when a path intersects itself or is nested.
+
+ Two values are possible:

+ + + +

In this example we are using the evenodd rule.

+ +
function draw() {
+  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.fill("evenodd");
+}
+ + + +

{{EmbedLiveSample("Canvas_fill_rules", "110", "110", "https://mdn.mozillademos.org/files/9855/fill-rule.png")}}

+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_shapes", "Web/API/Canvas_API/Tutorial/Drawing_text")}}

diff --git a/files/ja/web/api/canvas_api/tutorial/basic_animations/index.html b/files/ja/web/api/canvas_api/tutorial/basic_animations/index.html new file mode 100644 index 0000000000..1690518a7d --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/basic_animations/index.html @@ -0,0 +1,711 @@ +--- +title: Basic animations +slug: Web/Guide/HTML/Canvas_tutorial/Basic_animations +tags: + - Canvas + - Graphics + - HTML + - HTML5 + - Intermediate + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Basic_animations +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Compositing", "Web/API/Canvas_API/Tutorial/Advanced_animations")}}
+ +
+

私たちが {{HTMLElement("canvas")}} 要素の操作に JavaScript を使うのは、とても簡単にインタラクティブなアニメーションを作成できるからです!本章では、いくつかの基本的なアニメーションで、その概要をつかんでいきます。

+
+ +

おそらく最大の制約は、キャンバスに図形を一度描画すると、その状態が維持されることです。アニメーションさせる場合にも、移動する部分と以前に描いた部分をすべて再描画する必要があります。複雑なフレームの再描画には時間がかかり、パフォーマンスは、実行しているコンピューターの速度に大きく依存します。

+ +

基本的なアニメーションの手順

+ +

フレームを描画させる手順は、このようになります。

+ +
    +
  1. キャンバスをクリアする
    + 描画する図形がキャンバス全体 (たとえば、背景画像) に収まらない限り、以前に描画した図形をすべてクリアする必要があります。それを行う最も簡単な方法は、{{domxref("CanvasRenderingContext2D.clearRect", "clearRect()")}} メソッドを使うことです。
  2. +
  3. キャンバスの状態を保存する
    + キャンバスの状態に影響を与える設定(スタイル、変形など)を変更していて、フレームを描画するたびに元の状態を使用したい場合は、その状態を保存する必要があります。
  4. +
  5. アニメ―ションさせる図形を描画する
    + 実際に、フレームの描画を行います。
  6. +
  7. キャンバスの状態を復元する
    + 状態を保存した場合は、新しいフレームを描画する前に状態を復元します。
  8. +
+ +

アニメーションの制御

+ +

図形は、canvas のメソッドを直接使用するか、カスタム関数を呼び出すことによって描画されます。通常は、スクリプトの実行が終了したときにのみ、これらの結果がキャンバスに表示されます。たとえば、for ループ内からアニメーションを実行することはできません。

+ +

つまり、一定の期間ごとに描画関数を実行する方法が必要です。このようなアニメーションを制御するには、2 つの方法があります。

+ +

スケジュールの更新

+ +

まず、{{domxref("window.setInterval()")}}、{{domxref("window.setTimeout()")}} があります。それから、{{domxref("window.requestAnimationFrame()")}} 関数があります。これらは、特定の関数を一定時間で呼び出すために使用できます。

+ +
+
{{domxref("WindowTimers.setInterval", "setInterval(function, delay)")}}
+
function で指定した関数を delay ミリ秒ごとに繰り返し実行します。
+
{{domxref("WindowTimers.setTimeout", "setTimeout(function, delay)")}}
+
function で指定した関数を delay ミリ秒後に実行します。
+
{{domxref("Window.requestAnimationFrame()", "requestAnimationFrame(callback)")}}
+
アニメーションを実行することをブラウザーに通知し、次の再描画の前にアニメーションを更新するため、ブラウザーが指定の関数を呼び出すように要求します。
+
+ +

ユーザーの操作が必要ない場合は、提供されたコードを繰り返し実行する setInterval() 関数を使用できます。ゲームを作成したい場合、キーボードまたはマウスのイベントを使用してアニメーションを制御するため setTimeout() を使用できます。{{domxref( "EventListener")}}を設定することで、ユーザーの操作を取得し、アニメーション関数を実行します。

+ +
+

以下の例では、{{domxref("window.requestAnimationFrame()")}} メソッドを使用してアニメーションを制御します。requestAnimationFrame メソッドは、フレームを描画する準備ができた時にシステムがアニメーションフレームを呼び出すことで、よりスムーズで効率的な方法でアニメーションを提供します。通常、コールバック回数は 1 秒あたり 60 回となり、バックグラウンドタブで実行している場合は、レートが低くなることがあります。特にゲームのアニメーションループの詳細については、ゲーム開発ビデオゲームの解剖学を参照してください。

+
+ +

アニメーションする太陽系

+ +

この例は、太陽系の小さなモデルをアニメーションさせます。

+ +
var sun = new Image();
+var moon = new Image();
+var earth = new Image();
+function init(){
+  sun.src = 'https://mdn.mozillademos.org/files/1456/Canvas_sun.png';
+  moon.src = 'https://mdn.mozillademos.org/files/1443/Canvas_moon.png';
+  earth.src = 'https://mdn.mozillademos.org/files/1429/Canvas_earth.png';
+  window.requestAnimationFrame(draw);
+}
+
+function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  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.save();
+  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);
+
+  // 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.restore();
+
+  ctx.restore();
+
+  ctx.beginPath();
+  ctx.arc(150,150,105,0,Math.PI*2,false); // Earth orbit
+  ctx.stroke();
+
+  ctx.drawImage(sun,0,0,300,300);
+
+  window.requestAnimationFrame(draw);
+}
+
+init();
+
+ + + +

{{EmbedLiveSample("An_animated_solar_system", "310", "310", "https://mdn.mozillademos.org/files/202/Canvas_animation1.png")}}

+ +

アニメ―ションする時計

+ +

この例は、アニメーションする時計で現在時間を表示します。

+ +
function clock(){
+  var now = new Date();
+  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.strokeStyle = "black";
+  ctx.fillStyle = "white";
+  ctx.lineWidth = 8;
+  ctx.lineCap = "round";
+
+  // Hour marks
+  ctx.save();
+  for (var i=0;i<12;i++){
+    ctx.beginPath();
+    ctx.rotate(Math.PI/6);
+    ctx.moveTo(100,0);
+    ctx.lineTo(120,0);
+    ctx.stroke();
+  }
+  ctx.restore();
+
+  // Minute marks
+  ctx.save();
+  ctx.lineWidth = 5;
+  for (i=0;i<60;i++){
+    if (i%5!=0) {
+      ctx.beginPath();
+      ctx.moveTo(117,0);
+      ctx.lineTo(120,0);
+      ctx.stroke();
+    }
+    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;
+
+  ctx.fillStyle = "black";
+
+  // write Hours
+  ctx.save();
+  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.stroke();
+  ctx.restore();
+
+  // write Minutes
+  ctx.save();
+  ctx.rotate( (Math.PI/30)*min + (Math.PI/1800)*sec )
+  ctx.lineWidth = 10;
+  ctx.beginPath();
+  ctx.moveTo(-28,0);
+  ctx.lineTo(112,0);
+  ctx.stroke();
+  ctx.restore();
+
+  // Write seconds
+  ctx.save();
+  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.stroke();
+  ctx.beginPath();
+  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.stroke();
+  ctx.fillStyle = "rgba(0,0,0,0)";
+  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.stroke();
+
+  ctx.restore();
+
+  window.requestAnimationFrame(clock);
+}
+
+window.requestAnimationFrame(clock);
+ + + +

{{EmbedLiveSample("An_animated_clock", "180", "180", "https://mdn.mozillademos.org/files/203/Canvas_animation2.png")}}

+ +

ループする風景

+ +

この例は、左から右へ風景写真をスクロールさせます。Wikipedia からヨセミテ国立公園の画像を使いましたが、キャンバスよりも大きな任意の画像を使用できます。

+ +
var img = new Image();
+
+// User Variables - customize these to change the image being scrolled, its
+// direction, and the speed.
+
+img.src = 'https://mdn.mozillademos.org/files/4553/Capitan_Meadows,_Yosemite_National_Park.jpg';
+var CanvasXSize = 800;
+var CanvasYSize = 200;
+var speed = 30; // lower is faster
+var scale = 1.05;
+var y = -4.5; // vertical offset
+
+// Main program
+
+var dx = 0.75;
+var imgW;
+var imgH;
+var x = 0;
+var clearX;
+var clearY;
+var ctx;
+
+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;
+    }
+
+    // get canvas context
+    ctx = document.getElementById('canvas').getContext('2d');
+
+    // set refresh rate
+    return setInterval(draw, speed);
+}
+
+function draw() {
+    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);
+        }
+    }
+
+    // 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);
+        }
+    }
+    // draw image
+    ctx.drawImage(img, x, y,imgW, imgH);
+    // amount to move
+    x += dx;
+}
+
+ +

以下は、画像をスクロールする {{HTMLElement("canvas")}} です。ここで指定する幅と高さは、JavaScript コードの CanvasXZSize および CanvasYSize 変数の値と一致する必要があることに注意してください。

+ +
<canvas id="canvas" width="800" height="200"></canvas>
+ +

{{EmbedLiveSample("A_looping_panorama", "830", "230")}}

+ +

マウス追跡アニメーション

+ +
<!DOCTYPE html>
+<html lang="en">
+    <head>
+        <meta charset="UTF-8">
+        <meta name="viewport" content="width=device-width, initial-scale=1.0">
+        <meta http-equiv="X-UA-Compatible" content="ie=edge">
+        <title>Document</title>
+        <script>
+            var cn;
+            //= document.getElementById('cw');
+            var c;
+            var u = 10;
+            const m = {
+                x: innerWidth / 2,
+                y: innerHeight / 2
+            };
+            window.onmousemove = function(e) {
+                m.x = e.clientX;
+                m.y = e.clientY;
+
+            }
+            function gc() {
+                var s = "0123456789ABCDEF";
+                var c = "#";
+                for (var i = 0; i < 6; i++) {
+                    c += s[Math.ceil(Math.random() * 15)]
+                }
+                return c
+            }
+            var a = [];
+            window.onload = function myfunction() {
+                cn = document.getElementById('cw');
+                c = cn.getContext('2d');
+
+                for (var i = 0; i < 10; i++) {
+                    var r = 30;
+                    var x = Math.random() * (innerWidth - 2 * r) + r;
+                    var y = Math.random() * (innerHeight - 2 * r) + r;
+                    var t = new ob(innerWidth / 2,innerHeight / 2,5,"red",Math.random() * 200 + 20,2);
+                    a.push(t);
+                }
+                //cn.style.backgroundColor = "#700bc8";
+
+                c.lineWidth = "2";
+                c.globalAlpha = 0.5;
+                resize();
+                anim()
+            }
+            window.onresize = function() {
+
+                resize();
+
+            }
+            function resize() {
+                cn.height = innerHeight;
+                cn.width = innerWidth;
+                for (var i = 0; i < 101; i++) {
+                    var r = 30;
+                    var x = Math.random() * (innerWidth - 2 * r) + r;
+                    var y = Math.random() * (innerHeight - 2 * r) + r;
+                    a[i] = new ob(innerWidth / 2,innerHeight / 2,4,gc(),Math.random() * 200 + 20,0.02);
+
+                }
+                //  a[0] = new ob(innerWidth / 2, innerHeight / 2, 40, "red", 0.05, 0.05);
+                //a[0].dr();
+            }
+            function ob(x, y, r, cc, o, s) {
+                this.x = x;
+                this.y = y;
+                this.r = r;
+                this.cc = cc;
+                this.theta = Math.random() * Math.PI * 2;
+                this.s = s;
+                this.o = o;
+                this.t = Math.random() * 150;
+
+                this.o = o;
+                this.dr = function() {
+                    const ls = {
+                        x: this.x,
+                        y: this.y
+                    };
+                    this.theta += this.s;
+                    this.x = m.x + Math.cos(this.theta) * this.t;
+                    this.y = m.y + Math.sin(this.theta) * this.t;
+                    c.beginPath();
+                    c.lineWidth = this.r;
+                    c.strokeStyle = this.cc;
+                    c.moveTo(ls.x, ls.y);
+                    c.lineTo(this.x, this.y);
+                    c.stroke();
+                    c.closePath();
+
+                }
+            }
+            function anim() {
+                requestAnimationFrame(anim);
+                c.fillStyle = "rgba(0,0,0,0.05)";
+                c.fillRect(0, 0, cn.width, cn.height);
+                a.forEach(function(e, i) {
+                    e.dr();
+                });
+
+            }
+        </script>
+        <style>
+            #cw {
+                position: fixed;
+                z-index: -1;
+            }
+
+            body {
+                margin: 0;
+                padding: 0;
+                background-color: rgba(0,0,0,0.05);
+            }
+        </style>
+    </head>
+    <body>
+        <canvas id="cw"></canvas>
+    </body>
+</html>
+
+ +
表示例
+ + + + + + + +
+

beyblade

+
+ +

スネークゲーム

+ +
<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width,initial-scale=1">
+    <meta http-equiv="X-UA-Compatible" content="ie=edge">
+    <title>Nokia 1100:snake..Member berries</title>
+</head>
+
+<body>
+    <div class="keypress hide">
+        <div class="up" onclick="emit(38)">&#8593;</div>
+        <div class="right" onclick="emit(39)">&#8594;</div>
+        <div class="left" onclick="emit(37)">&#8592;</div>
+        <div class="down" onclick="emit(40)">&#8595;</div>
+    </div>
+    <div class="banner" id="selector">
+        <div>
+            Time :<span id="time">0</span>
+        </div>
+        <div>LousyGames ©</div>
+        <div>
+            Score :<span id="score">0</span>
+        </div>
+        <div class="touch off" onclick="touch(this)">touch</div>
+    </div>
+    <canvas id="main"></canvas>
+</body>
+<style>
+    body {
+        margin: 0;
+        overflow: hidden;
+        background: #000
+    }
+
+    .banner {
+        text-align: center;
+        color: #fff;
+        background: #3f51b5;
+        line-height: 29px;
+        position: fixed;
+        left: 0;
+        top: 0;
+        right: 0;
+        font-family: monospace;
+        height: 30px;
+        opacity: .4;
+        display: flex;
+        transition: .5s
+    }
+
+    .banner:hover {
+        opacity: 1
+    }
+
+    div#selector>div {
+        flex-basis: 30%
+    }
+
+    @keyframes diss {
+        from {
+            opacity: 1
+        }
+
+        to {
+            opacity: 0
+        }
+    }
+
+    .keypress>div {
+        border: dashed 3px #fff;
+        height: 48%;
+        width: 48%;
+        display: flex;
+        align-content: center;
+        justify-content: center;
+        align-self: center;
+        align-items: center;
+        font-size: -webkit-xxx-large;
+        font-weight: 900;
+        color: #fff;
+        transition: .5s;
+        opacity: .1;
+        border-radius: 7px
+    }
+
+    .keypress {
+        position: fixed;
+        width: 100vw;
+        height: 100vh;
+        top: 0;
+        left: 0;
+        display: flex;
+        flex-wrap: wrap;
+        justify-content: space-around;
+        opacity: 1;
+        user-select: none
+    }
+
+    .keypress>div:hover {
+        opacity: 1
+    }
+
+    .touch {
+        background: #8bc34a
+    }
+
+    .off {
+        background: #f44336
+    }
+
+    .hide {
+        opacity: 0
+    }
+</style>
+</html>
+ +

Javascript

+ +
function tmz() {
+        var e = new Date(t),
+            i = new Date,
+            n = Math.abs(i.getMinutes() - e.getMinutes()),
+            o = Math.abs(i.getSeconds() - e.getSeconds());
+        return n + " : " + o
+    }
+
+    function coll(t, e) {
+        return t.x < e.x + e.w && t.x + t.w > e.x && t.y < e.y + e.h && t.h + t.y > e.y
+    }
+
+    function snake() {
+        this.w = 15, this.h = 15, this.dx = 1, this.dy = 1, this.xf = 1, this.yf = 1, this.sn = [];
+        for (var t = {
+            x: w / 2,
+            y: h / 2
+        }, e = 0; e < 5; e++) this.sn.push(Object.assign({}, t)), t.x += this.w;
+        this.draw = function () {
+            var t = d && d.search("Arrow") > -1,
+                e = -1;
+            if (t) {
+                var i = {
+                    ...this.sn[0]
+                };
+                if ("ArrowUp" == d && (i.y -= this.h), "ArrowDown" == d && (i.y += this.h), "ArrowLeft" == d && (i.x -= this.w), "ArrowRight" == d && (i.x += this.w), i.x >= w ? i.x = 0 : i.x < 0 && (i.x = w - this.w), i.y > h ? i.y = 0 : i.y < 0 && (i.y = h), e = fa.findIndex(t => coll({
+                    ...this.sn[0],
+                    h: this.h,
+                    w: this.w
+                }, t)), this.sn.unshift(i), -1 != e) return console.log(e), fa[e].renew(), void (document.getElementById("score").innerText = Number(document.getElementById("score").innerText) + 1);
+                this.sn.pop(), console.log(6)
+            }
+            this.sn.forEach((t, e, i) => {
+                if (0 == e || i.length - 1 == e) {
+                    var n = c.createLinearGradient(t.x, t.y, t.x + this.w, t.y + this.h);
+                    i.length - 1 == e ? (n.addColorStop(0, "black"), n.addColorStop(1, "#8BC34A")) : (n.addColorStop(0, "#8BC34A"), n.addColorStop(1, "white")), c.fillStyle = n
+                } else c.fillStyle = "#8BC34A";
+                c.fillRect(t.x, t.y, this.w, this.h), c.strokeStyle = "#E91E63", c.font = "30px serif", c.strokeStyle = "#9E9E9E", i.length - 1 != e && 0 != e && c.strokeRect(t.x, t.y, this.w, this.h), 0 == e && (c.beginPath(), c.fillStyle = "#F44336", c.arc(t.x + 10, t.y + 2, 5, 360, 0), c.fill()), c.arc(t.x + 10, t.y + 2, 5, 360, 0), c.fill(), c.beginPath()
+            })
+        }
+    }
+
+    function gc() {
+        for (var t = "0123456789ABCDEF", e = "#", i = 0; i < 6; i++) e += t[Math.ceil(15 * Math.random())];
+        return e
+    }
+
+    function food() {
+        this.x = 0, this.y = 0, this.b = 10, this.w = this.b, this.h = this.b, this.color = gc(), this.renew = function () {
+            this.x = Math.floor(Math.random() * (w - 200) + 10), this.y = Math.floor(Math.random() * (h - 200) + 30), this.color = gc()
+        }, this.renew(), this.put = (() => {
+            c.fillStyle = this.color, c.arc(this.x, this.y, this.b - 5, 0, 2 * Math.PI), c.fill(), c.beginPath(), c.arc(this.x, this.y, this.b - 5, 0, Math.PI), c.strokeStyle = "green", c.lineWidth = 10, c.stroke(), c.beginPath(), c.lineWidth = 1
+        })
+    }
+
+    function init() {
+        cc.height = h, cc.width = w, c.fillRect(0, 0, w, innerHeight);
+        for (var t = 0; t < 10; t++) fa.push(new food);
+        s = new snake(w / 2, h / 2, 400, 4, 4), anima()
+    }
+
+    function anima() {
+        c.fillStyle = "rgba(0,0,0,0.11)", c.fillRect(0, 0, cc.width, cc.height), fa.forEach(t => t.put()), s.draw(), document.getElementById("time").innerText = tmz(), setTimeout(() => {
+            requestAnimationFrame(anima)
+        }, fw)
+    }
+
+    function emit(t) {
+        key.keydown(t)
+    }
+
+    function touch(t) {
+        t.classList.toggle("off"), document.getElementsByClassName("keypress")[0].classList.toggle("hide")
+    }
+    var t = new Date + "",
+        d = void 0,
+        cc = document.getElementsByTagName("canvas")[0],
+        c = cc.getContext("2d");
+    key = {}, key.keydown = function (t) {
+        var e = document.createEvent("KeyboardEvent");
+        Object.defineProperty(e, "keyCode", {
+            get: function () {
+                return this.keyCodeVal
+            }
+        }), Object.defineProperty(e, "key", {
+            get: function () {
+                return 37 == this.keyCodeVal ? "ArrowLeft" : 38 == this.keyCodeVal ? "ArrowUp" : 39 == this.keyCodeVal ? "ArrowRight" : "ArrowDown"
+            }
+        }), Object.defineProperty(e, "which", {
+            get: function () {
+                return this.keyCodeVal
+            }
+        }), e.initKeyboardEvent ? e.initKeyboardEvent("keydown", !0, !0, document.defaultView, !1, !1, !1, !1, t, t) : e.initKeyEvent("keydown", !0, !0, document.defaultView, !1, !1, !1, !1, t, 0), e.keyCodeVal = t, e.keyCode !== t && alert("keyCode mismatch " + e.keyCode + "(" + e.which + ")"), document.dispatchEvent(e)
+    };
+    var o, s, h = innerHeight,
+        w = innerWidth,
+        fw = 60,
+        fa = [];
+    window.onkeydown = function (t) {
+        var e = t.key;
+        (e.search("Arrow") > -1 || "1" == e) && (d = t.key), "i" != e && "I" != e || (console.log("inc"), fw -= 10), "d" != e && "D" != e || (console.log("dec"), fw += 10)
+    }, init();
+
+ +
表示例
+ + + + + + + +
+

Snake game

+
+ +

その他のサンプル

+ +
+
A basic ray-caster
+
キーボードを使ってアニメーションをどのように制御するか説明した良いサンプルです。
+
Advanced animations
+
高度なアニメーション技術と物の動きについて見ていきます。
+
+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Compositing", "Web/API/Canvas_API/Tutorial/Advanced_animations")}}

diff --git a/files/ja/web/api/canvas_api/tutorial/basic_usage/index.html b/files/ja/web/api/canvas_api/tutorial/basic_usage/index.html new file mode 100644 index 0000000000..c9bc6c17f4 --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/basic_usage/index.html @@ -0,0 +1,152 @@ +--- +title: Basic usage of canvas +slug: Web/Guide/HTML/Canvas_tutorial/Basic_usage +translation_of: Web/API/Canvas_API/Tutorial/Basic_usage +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial", "Web/API/Canvas_API/Tutorial/Drawing_shapes")}}
+ +
+

まずチュートリアルの最初として {{HTMLElement("canvas")}} {{Glossary("HTML")}} 要素を説明します。このページを読めば、canvas 要素に 2D の画像を描けるようになります。

+
+ +

<canvas> 要素

+ +
<canvas id="tutorial" width="150" height="150"></canvas>
+
+ +

{{HTMLElement("canvas")}} は {{HTMLElement("img")}} と似ています。src 属性と alt 属性がない点が明確に異なりますが、{{htmlattrxref("width", "canvas")}} と {{htmlattrxref("height", "canvas")}} の属性がある点などは共通しています。 これらの属性は必ず指定しなければならないものではありません。このほかに様々な {{Glossary("DOM")}} 属性を利用できます。 widthheight 属性が指定されなかった場合、canvas は幅 300 ピクセル、高さ 150 ピクセルの要素として初期化されます。画面上の大きさは {{Glossary("CSS")}} によって変更できますが、その場合 canvas に描画される画像は CSS の指定に合わせて拡大 / 縮小されます。この際、元の画像のアスペクト比は考慮されないため、指定の仕方によっては画像が歪んで表示されます。

+ +
+

付記: 画像が歪んでいると感じた時は、<canvas> widthheight 属性の値を設定して、CSS によるサイズの変更をしないようにしましょう。

+
+ +

id 属性は 全ての要素が持つ属性<canvas> に固有なものではありません。これを利用することで、ユニークな ID を要素に持たせられます。ID を持たせることで、JavaScript の中から、その要素を探すのが簡単になります。

+ +

<canvas> 要素は通常の画像と同じようにレイアウトされます。({{cssxref("margin")}} や {{cssxref("border")}}、 {{cssxref("background")}} といったルールも利用可能ですが、これらは実際に描画される画像には影響を与えません。スタイルが何も設定されていない場合、canvas は最初透明なものとして描画されます。スタイルとレイアウトに関しては専用のページを設けています。詳細は、そちらをご覧ください。

+ +
+

代替コンテンツ

+ +

<canvas> 要素は対応していないブラウザ、例えば Internet Explorer 9 以前、で表示するための代替コンテンツを定義できます。これは {{HTMLElement("img")}} というよりは、むしろ {{HTMLElement("video")}} や {{HTMLElement("audio")}}、{{HTMLElement("picture")}} 要素に似ています。

+ +

代替コンテンツの定義方法はシンプルで、<canvas> 要素の内部に代わりに表示するコンテンツを記述します。対応していないブラウザは <canvas> を無視するため、その内部のコンテンツが表示されるというわけです。

+ +

次の例では JavaScript によって canvas に対して、代替テキストが設定されています:

+ +
<canvas id="stockGraph" width="150" height="150">
+  現在の株価: $3.15 +0.15
+</canvas>
+
+<canvas id="clock" width="150" height="150">
+  <img src="images/clock.png" width="150" height="150" alt=""/>
+</canvas>
+
+ +

使用するブラウザを変更するよう利用者に伝えることは、利用者のために全くなりません。どのような代替テキスト / コンテンツを設定するのが適切かは make the canvas more accessible をご覧ください。

+ +

</canvas>:閉じタグが必須です

+ +

代替コンテンツを内部に持つ関係上、{{HTMLElement("img")}} 要素と異なって {{HTMLElement("canvas")}} 要素は閉じタグ (</canvas>) が必須となっています。タグを閉じなかった場合は、残りのページ全てが代替コンテンツとして処理され、その結果としてそれらが表示されなくなります。

+ +

代替コンテンツが必要でない場合は、単に <canvas id="foo" ...></canvas> と書けば対応するブラウザで動作します。

+ +

描画コンテキスト

+ +

{{HTMLElement("canvas")}} は固定された大きさの描画可能領域を作成できます。この領域は、1 つ以上の描画コンテキストとして表現され、そのコンテキストを通じて描画領域を操作します。このチュートリアルでは、2 次元グラフィックスを描画するためのコンテキストについてのみ解説しますが、これ以外の描画コンテキストも存在します。その典型例が WebGL です。これは OpenGL ES に基づいた 3 次元グラフィックスを扱える描画コンテキストです。

+ +

初期状態での canvas には何も描画されていません。ここに描画を行うには、まず JavaScript で描画コンテキストを取得する必要があります。 {{HTMLElement("canvas")}} 要素の {{domxref("HTMLCanvasElement.getContext", "getContext()")}} を呼ぶことで、描画コンテキストは取得できます。呼び出す際の引数によって、取得されるコンテキストの種類が変わります。"2d" を指定することで、2 次元のグラフィックスを扱える描画コンテキストが取得できます。これで取得されたコンテキストの詳細は {{domxref("CanvasRenderingContext2D")}} をご覧ください。

+ +
var canvas = document.getElementById('tutorial');
+var ctx = canvas.getContext('2d');
+
+ +

最初の行では {{domxref("document.getElementById()")}} メソッドを呼んで、DOM 中から {{HTMLElement("canvas")}} 要素をあらわすノードを探しています。2 行目では見つけた要素の getContext() メソッドを呼んで、描画コンテキストを取得しています。

+ +
+

対応しているかどうかの確認

+ +

{{HTMLElement("canvas")}} 要素に対応していないブラウザでは、代替コンテンツが表示されます。JavaScript からは getContext() メソッドの有無を調査することで、ブラウザが対応しているかどうかを確認できます。確認するためのコードは以下のようになります:

+ +
var canvas = document.getElementById('tutorial');
+
+if (canvas.getContext){
+  var ctx = canvas.getContext('2d');
+  // drawing code here
+} else {
+  // canvas-unsupported code here
+}
+
+
+
+ +

サンプルコード

+ +

以上の点をまとめたサンプルコードは以下のようになります。このサンプルコードは、後の説明でも利用します。

+ +
+

付記:スクリプトを HTML に埋め込むのは、よいやり方ではありません。この例では分かりやすさのために、仕方なく埋め込んでいます。

+
+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <meta charset="utf-8"/>
+    <title>Canvas tutorial</title>
+    <script type="text/javascript">
+      function draw(){
+        var canvas = document.getElementById('tutorial');
+        if (canvas.getContext){
+          var ctx = canvas.getContext('2d');
+        }
+      }
+    </script>
+    <style type="text/css">
+      canvas { border: 1px solid black; }
+    </style>
+  </head>
+  <body onload="draw();">
+    <canvas id="tutorial" width="150" height="150"></canvas>
+  </body>
+</html>
+
+ +

スクリプト中の draw() 関数はページのロード完了時に一度だけ呼び出されます。これは、document の {{event("load")}} イベントを利用しているためです。他の関数同様 {{domxref("WindowTimers.setTimeout", "window.setTimeout()")}} や {{domxref("WindowTimers.setInterval", "window.setInterval()")}}、他のイベントハンドラから呼び出すことができますが、今の所ページがロードされた時にのみ呼び出されます。

+ +

このサンプルコードでは何も描画されない領域が表示されます。実際の動作は次で確認できます:

+ +

{{EmbedLiveSample("サンプルコード", 160, 160)}}

+ +

単純な描画

+ +

手始めに単純な例を見てみましょう。次の例では重なり合う 2 つの四角形が描画されます。そのうちの 1 つは透明度が設定されており、下の色が透けて見えます。この例がどのように動作しているかは、次のページで解説します。

+ +
<!DOCTYPE html>
+<html>
+ <head>
+  <meta charset="utf-8"/>
+  <script type="application/javascript">
+    function draw() {
+      var canvas = document.getElementById("canvas");
+      if (canvas.getContext) {
+        var ctx = canvas.getContext("2d");
+
+        ctx.fillStyle = "rgb(200,0,0)";
+        ctx.fillRect (10, 10, 50, 50);
+
+        ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
+        ctx.fillRect (30, 30, 50, 50);
+      }
+    }
+  </script>
+ </head>
+ <body onload="draw();">
+   <canvas id="canvas" width="150" height="150"></canvas>
+ </body>
+</html>
+
+ +

この例は次のように動作します:

+ +

{{EmbedLiveSample("単純な描画", 160, 160, "https://mdn.mozillademos.org/files/228/canvas_ex1.png")}}

+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial", "Web/API/Canvas_API/Tutorial/Drawing_shapes")}}

diff --git a/files/ja/web/api/canvas_api/tutorial/drawing_shapes/index.html b/files/ja/web/api/canvas_api/tutorial/drawing_shapes/index.html new file mode 100644 index 0000000000..99e2c55b69 --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/drawing_shapes/index.html @@ -0,0 +1,577 @@ +--- +title: canvas に図形を描く +slug: Web/Guide/HTML/Canvas_tutorial/Drawing_shapes +tags: + - Canvas + - Graphics + - HTML + - HTML Canvas + - HTML5 + - Intermediate + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Drawing_shapes +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_usage", "Web/API/Canvas_API/Tutorial/Applying_styles_and_colors")}}
+ +
+

canvas の環境をセットアップしましたので、canvas に描画する方法を詳しく見ていくことができます。この記事を読み終わると矩形、三角形、線、円弧、曲線を描く方法を学び、基本的な図形について理解できます。canvas にオブジェクトを描く際はパスを扱うことが不可欠ですので、その方法を見ていきます。

+
+ +

グリッド

+ +

+ +

描き始める前に、canvas のグリッドもしくは 座標空間 について話す必要があります。前のページの HTML テンプレートは幅 150 ピクセル、高さ 150 ピクセルの canvas 要素を持っていました。右の図に、この画像とデフォルトのグリッドを重ねて描きました。普通 グリッド上の 1 単位は canvas 上の 1 ピクセルに相当します。このグリッドの原点は左上の角 ( 座標 (0,0) ) に位置します。全ての要素がこの原点から相対的に配置されます。よって青い正方形の左上の場所は左から x ピクセル、上から y ピクセル (座標 (x,y) ) に来ます。このチュートリアルの後半で原点を他の位置へずらす方法、グリッドを回転したり、伸縮したりする方法を見ることになります。今はデフォルトで我慢しましょう。

+ +

矩形を描く

+ +

{{Glossary("SVG")}} とは異なり、{{HTMLElement("canvas")}} は 2 つの原始図形「矩形」「パス(複数の点が線によって結ばれている)」のみをサポートしています。他の全ての図形は 1 つ以上のパスを組み合わせて作らなくてはなりません。幸いなことに、パスを描く一連の関数があり、とても複雑な図形を作ることができます。

+ +

最初に矩形を見ていきましょう。canvas に矩形を描く 3 つの関数があります:

+ +
+
{{domxref("CanvasRenderingContext2D.fillRect", "fillRect(x, y, width, height)")}}
+
塗りつぶされた矩形を描きます。
+
{{domxref("CanvasRenderingContext2D.strokeRect", "strokeRect(x, y, width, height)")}}
+
矩形の輪郭を描きます。
+
{{domxref("CanvasRenderingContext2D.clearRect", "clearRect(x, y, width, height)")}}
+
指定された領域を消去し、完全な透明にします。
+
+ +

3 つの関数は同じパラメータをとります。xy は矩形の左上の角の canvas 上での位置 (原点から相対的) を指定します。widthheight は矩形のサイズを指定します。

+ +

下は、前のページの draw() 関数ですが、この 3 つの関数を追加しました。

+ +

矩形の例

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    ctx.fillRect(25, 25, 100, 100);
+    ctx.clearRect(45, 45, 60, 60);
+    ctx.strokeRect(50, 50, 50, 50);
+  }
+}
+ +

結果は以下のように見えるはずです。

+ +
{{EmbedLiveSample("Rectangular_shape_example", 160, 160, "https://mdn.mozillademos.org/files/245/Canvas_rect.png")}}
+ +

fillRect() 関数は 100x100 ピクセルの大きな黒色正方形を描きます。clearRect() 関数は中心から 60x60 ピクセルの正方形を取り除き、最後に strokeRect() が消去された正方形の中に 50x50 ピクセルの矩形の輪郭を描きます。

+ +

後のページで clearRect() の代わりのメソッドを 2 つ見て、描く図形の色と輪郭のスタイルを変更する方法を見ます。

+ +

次の節でみるパス関数と異なり、全ての 3 つの矩形関数は直ちに canvas に描きます。

+ +

パスを描く

+ +

パスについて見ていきましょう。パスは点のリストであり、それらは曲線かそうでない形状、およびさまざまな幅や色を設定可能な線分で結ばれます。パスやサブパスは、閉じることができます。パスを使って図形を描くには、 いくつかの余分な作業が必要です。

+ +
    +
  1. 始めに、パスを作成します。
  2. +
  3. 次に、パスへ描画するために描画コマンドを使用します。
  4. +
  5. パスが作成されたら、描画するための stroke または fill を実行できます。
  6. +
+ +

これらのステップで使用する関数を以下に示します:

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}}
+
新しいパスを作成します。パスを作成すると以降の描画コマンドは、そのパスを構築するために直接作用します。
+
パスのメソッド
+
オブジェクトのためにさまざまなパスを設定するメソッド群です。
+
{{domxref("CanvasRenderingContext2D.closePath", "closePath()")}}
+
直線をパスに追加し、現在のサブパスの開始地点につなぎます。
+
{{domxref("CanvasRenderingContext2D.stroke", "stroke()")}}
+
輪郭をなぞる方式で、図形を描きます。
+
{{domxref("CanvasRenderingContext2D.fill", "fill()")}}
+
パスの内部エリアを塗りつぶして、単色の図形を描きます。
+
+ +

パスを作る最初の作業は beginPath() メソッドを呼び出すことです。内部では、パスは図形を一緒に作るサブパス (線、円弧など) のリストとして保存されます。このメソッドが呼び出される毎に、リストはリセットされ新しい図形を始めることができます。

+ +
注記: beginPath() を呼び出した直後や canvas を新規作成した直後など、現在のパスが空であるときに最初にパスを構築するコマンドは、実際は何であるかにかかわらず常に moveTo() として扱われます。このためパスをリセットした後はほぼ必ず、開始位置を明示することが必要になるでしょう。
+ +

2 番目の作業は描かれる実際のパスを定義するメソッドを呼び出すことです。まもなくみることになります。

+ +

3 番目は任意の作業ですが、closePath() メソッドを呼び出すことです。このメソッドは現在の点から始点に向けて直線を描くことで図形を閉じようとします。もし図形がすでに閉じられているかリストに点がひとつしかない場合はこの関数は何もしません。

+ +
注記: fill() メソッドが呼ばれるときは開いている図形は自動的に閉じられ、closePath() メソッドを使う必要はありません。これは、stroke() を呼び出すときはあてはまりません
+ +

三角形の描画

+ +

単純な図形 (三角形) を描くコードはこのようになります。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    ctx.beginPath();
+    ctx.moveTo(75, 50);
+    ctx.lineTo(100, 75);
+    ctx.lineTo(100, 25);
+    ctx.fill();
+  }
+}
+ +

表示結果は以下の様になります。

+ +
{{EmbedLiveSample("Drawing_a_triangle", 110, 110, "https://mdn.mozillademos.org/files/9847/triangle.png")}}
+ +

ペンの移動

+ +

とても役に立つ関数である moveTo() は、自身は何も描画しませんが、上述のパスリストの一部になります。 1 枚の紙の上の 1 つの場所からペンか鉛筆を持ち上げてそれを次の場所に置くと考えるとよいでしょう。

+ +
+
{{domxref("CanvasRenderingContext2D.moveTo", "moveTo(x, y)")}}
+
xy で指定した座標に、ペンを移動します。
+
+ +

canvas が初期化されるか beginPath() メソッドが呼ばれたとき、ほとんどの場合 moveTo() メソッドを始点を他の場所に置くために使います。moveTo() メソッドを繋がっていないパスを描くために使うこともできます。下のスマイリーを見てください。

+ +

これをあなた自身で試すには、以下のコードを使うことができます。さきほど見た draw() 関数に貼り付けるだけです。

+ + + +
function draw() {
+  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.moveTo(65, 65);
+    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.stroke();
+  }
+}
+ +

表示結果は以下の様になります。

+ +

{{EmbedLiveSample("Moving_the_pen", 160, 160, "https://mdn.mozillademos.org/files/252/Canvas_smiley.png")}}

+ +

繋がっている線を見るには moveTo() メソッドを取り除いてください。

+ +
注記: arc() 関数とそのパラメータの解説は {{anch("Arcs","円弧")}} の節をご覧下さい。
+ +

+ +

直線を描くには lineTo() メソッドを使います。

+ +
+
{{domxref("CanvasRenderingContext2D.lineTo", "lineTo(x, y)")}}
+
現在の描画位置から xy で指定した位置に、線を描きます。
+
+ +

このメソッドは 2 つの引数 xy を取ります。それらは線の終点の座標です。始点は前回のパスに依存します。前回のパスの終点が始点になる、など。始点は moveTo() メソッドを使って変更することもできます。

+ +

次の例では 2 つの三角形が描かれています。 1 つは塗られ、もう 1 つは輪郭線が描かれています。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext){
+    var ctx = canvas.getContext('2d');
+
+    // Filled triangle
+    ctx.beginPath();
+    ctx.moveTo(25, 25);
+    ctx.lineTo(105, 25);
+    ctx.lineTo(25, 105);
+    ctx.fill();
+
+    // Stroked triangle
+    ctx.beginPath();
+    ctx.moveTo(125, 125);
+    ctx.lineTo(125, 45);
+    ctx.lineTo(45, 125);
+    ctx.closePath();
+    ctx.stroke();
+  }
+}
+
+ +

最初に新しい図形のパスを始めるために beginPath() メソッドが呼ばれています。次に 始点を望む位置に移動するために moveTo() メソッドが呼ばれています。三角形の 両側の辺を作る 2 つの線が描かれています。

+ +
{{EmbedLiveSample("Lines", 160, 160, "https://mdn.mozillademos.org/files/238/Canvas_lineTo.png")}}
+ +
+ +

あなたは塗られた三角形と輪郭線の描かれたものとの違いに気がつくでしょう。上で述べたように、これはパスが塗られる( fill される) と図形は自動的に閉じられ、stroke されるときはそうでないからです。輪郭の描かれた三角形で closePath() を行わないと 2 つの線しか描かれず、三角形は完成しません。

+ +

円弧

+ +

円弧や円を描くために arc() または arcTo() メソッドを使います。

+ +
+
{{domxref("CanvasRenderingContext2D.arc", "arc(x, y, radius, startAngle, endAngle, anticlockwise)")}}
+
(x, y) を中心の位置、radius を半径、startAngle を開始角度、endAngle を終了角度、anticlockwise を方向 (デフォルトは時計回り) とする円弧を描きます。
+
{{domxref("CanvasRenderingContext2D.arcTo", "arcTo(x1, y1, x2, y2, radius)")}}
+
指定した制御点と半径によって円弧を描き、その前の描画位置と直線で接続します。
+
+ +

arc メソッドを詳しく見ていきましょう。このメソッドは 6 つのパラメーターをとります。xy は、円弧を描く円の中心座標です。radius はそのまま、半径です。startAngleendAngle パラメーターは円弧の始まりと終わりをラジアンで定義します。始まりと終わりの角度は x 軸から計算します。anticlockwise パラメーターは true の時には円弧を反時計回りに、それ以外は時計回りの方向に描くブーリアン値です。

+ +
+

注記: arc 関数の角度は度ではなく、ラジアンで計算されます。度からラジアンに変換するには以下の JavaScript 式を使うことができます : radians = (Math.PI/180)*degrees

+
+ +

以下の例は上で見てきた例よりすこし複雑です。全て異なる角度と塗り方で 12 の異なる円弧を描きます。

+ +

2 つの for ループは円弧の行と列のループです。全ての円弧毎に beginPath() を使って新しいパスを始めます。コードの中で、次に何が行われているか読みやすくするために全てのパラメーターを変数として書きましたが、いつもこのようにする必要はありません。

+ +

xy 座標は充分明確です。radiusstartAngle は固定です。endAngle は最初の列が 180 度 (半円) から始まって、最後の列で完全な円を作るように 90 度ずつ増加します。

+ +

clockwise パラメーターの文は最初と 3 番目の列では時計回りの円弧として 2 番目と 4 番目の列では反時計回りの円弧という結果になります。最後に、if 文は上半分は輪郭を描画された円弧を、下半分は塗られた円弧を作ります。

+ +
+

注記: この例では、ほかの例より若干大きなサイズである 150 x 200 ピクセルの canvas が必要です。

+
+ + + +
function draw() {
+  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++) {
+        ctx.beginPath();
+        var x = 25 + j * 50; // x 座標
+        var y = 25 + i * 50; // y 座標
+        var radius = 20; // 円弧の半径
+        var startAngle = 0; // 円孤の始点
+        var endAngle = Math.PI + (Math.PI * j) / 2; // 円孤の終点
+        var anticlockwise = i % 2 !== 0; // 時計回りまたは反時計回り
+
+        ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
+
+        if (i > 1){
+          ctx.fill();
+        } else {
+          ctx.stroke();
+        }
+      }
+    }
+  }
+}
+
+ +
{{EmbedLiveSample("Arcs", 160, 210, "https://mdn.mozillademos.org/files/204/Canvas_arc.png")}}
+ +

ベジェと二次曲線

+ +

次に見ていく種類のパスはベジェ曲線です。三次および二次の種類が利用可能です。通常複雑な自然の図形を描くのに使われます。

+ +
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo", "quadraticCurveTo(cp1x, cp1y, x, y)")}}
+
現在のペンの位置から x および y で指定した終端へ、cp1x および cp1y で指定した制御点を使用して二次ベジェ曲線を描きます。
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo", "bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)")}}
+
現在のペンの位置から x および y で指定した終端へ、(cp1x, cp1y) および (cp2x, cp2y) で指定した制御点を使用して三次ベジェ曲線を描きます。
+
+ +

これらの違いは右の画像を使うことで説明することができます。二次ベジェ曲線は始点と終点 (青い点) と 1 つの制御点 (赤い点) を持つのに対して、三次ベジェ曲線は 2 つの制御点を持ちます。

+ +

それらのメソッドの両方の xy パラメータは終点の座標です。cp1xcp1y は最初の制御点、cp2xcp2y は 2 番目の制御点の座標です。

+ +

Adobe Illustrator のようなベクタードローイングソフトとは違い、何をやっているのかの直接の視覚的フィードバックが得られないので、二次および三次ベジェ曲線を使うことはとても挑戦的です。このことは複雑な図形を描くことをとても難しくします。以下の例で、いくつかの単純で基本的な図形を描きます、しかしもしあなたに時間と特に忍耐があればはるかに複雑な図形を作ることができます。

+ +

これらの例で非常に難しいものは何もありません。 どちらの場合も、最終的に描かれた一連の曲線が完全な図形となるのを見ることになります。

+ +

二次ベジェ曲線

+ +

この例では、吹き出しをレンダリングするために複数の二次ベジェ曲線を使用しています。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    // 二次曲線の例
+    ctx.beginPath();
+    ctx.moveTo(75, 25);
+    ctx.quadraticCurveTo(25, 25, 25, 62.5);
+    ctx.quadraticCurveTo(25, 100, 50, 100);
+    ctx.quadraticCurveTo(50, 120, 30, 125);
+    ctx.quadraticCurveTo(60, 120, 65, 100);
+    ctx.quadraticCurveTo(125, 100, 125, 62.5);
+    ctx.quadraticCurveTo(125, 25, 75, 25);
+    ctx.stroke();
+  }
+}
+
+ +
{{EmbedLiveSample("Quadratic_Bezier_curves", 160, 160, "https://mdn.mozillademos.org/files/243/Canvas_quadratic.png")}}
+ +

三次ベジェ曲線

+ +

この例では、三次ベジェ曲線を使ってハートを描画します。

+ + + +
function draw() {
+  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);
+    ctx.bezierCurveTo(20, 25, 20, 62.5, 20, 62.5);
+    ctx.bezierCurveTo(20, 80, 40, 102, 75, 120);
+    ctx.bezierCurveTo(110, 102, 130, 80, 130, 62.5);
+    ctx.bezierCurveTo(130, 62.5, 130, 25, 100, 25);
+    ctx.bezierCurveTo(85, 25, 75, 37, 75, 40);
+    ctx.fill();
+  }
+}
+
+ +
{{EmbedLiveSample("Cubic_Bezier_curves", 160, 160, "https://mdn.mozillademos.org/files/207/Canvas_bezier.png")}}
+ +

矩形

+ +

canvas に直接矩形を描く例 ({{anch("Drawing rectangles","矩形を描く")}}) で見た 3 つのメソッドのほかに、開いているパスリストに矩形を追加する rect() メソッドがあります。

+ +
+
{{domxref("CanvasRenderingContext2D.rect", "rect(x, y, width, height)")}}
+
(x, y) で指定した位置を左上の角にして、width および height で指定した幅および高さの矩形を描きます。
+
+ +

このメソッドが実行される前に、パラメーターに (x,y) を持った moveTo() メソッドが自動的に呼ばれます。すなわち、始点が標準の位置に置かれます。

+ +

組み合わせ

+ +

このページの全ての例で図形につき一種類のパス関数のみを使ってきました。しかし、図形を作るのに使用できるパスの種類の制限は一切ありません。そこで、この最後の例では非常に有名なゲームのキャラクタを作るために全てのパス関数を組み合わせてみましょう。

+ + + +
function draw() {
+  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);
+    roundedRect(ctx, 53, 53, 49, 33, 10);
+    roundedRect(ctx, 53, 119, 49, 16, 6);
+    roundedRect(ctx, 135, 53, 49, 33, 10);
+    roundedRect(ctx, 135, 119, 25, 49, 10);
+
+    ctx.beginPath();
+    ctx.arc(37, 37, 13, Math.PI / 7, -Math.PI / 7, false);
+    ctx.lineTo(31, 37);
+    ctx.fill();
+
+    for (var i = 0;i < 8;i++) {
+      ctx.fillRect(51 + i * 16, 35, 4, 4);
+    }
+
+    for(i = 0;i < 6;i++) {
+      ctx.fillRect(115, 51 + i * 16, 4, 4);
+    }
+
+    for(i = 0;i < 8;i++) {
+      ctx.fillRect(51 + i * 16, 99, 4, 4);
+    }
+
+    ctx.beginPath();
+    ctx.moveTo(83, 116);
+    ctx.lineTo(83, 102);
+    ctx.bezierCurveTo(83, 94, 89, 88, 97, 88);
+    ctx.bezierCurveTo(105, 88, 111, 94, 111, 102);
+    ctx.lineTo(111, 116);
+    ctx.lineTo(106.333, 111.333);
+    ctx.lineTo(101.666, 116);
+    ctx.lineTo(97, 111.333);
+    ctx.lineTo(92.333, 116);
+    ctx.lineTo(87.666, 111.333);
+    ctx.lineTo(83, 116);
+    ctx.fill();
+
+    ctx.fillStyle = 'white';
+    ctx.beginPath();
+    ctx.moveTo(91, 96);
+    ctx.bezierCurveTo(88, 96, 87, 99, 87, 101);
+    ctx.bezierCurveTo(87, 103, 88, 106, 91, 106);
+    ctx.bezierCurveTo(94, 106, 95, 103, 95, 101);
+    ctx.bezierCurveTo(95, 99, 94, 96, 91, 96);
+    ctx.moveTo(103, 96);
+    ctx.bezierCurveTo(100, 96, 99, 99, 99, 101);
+    ctx.bezierCurveTo(99, 103, 100, 106, 103, 106);
+    ctx.bezierCurveTo(106, 106, 107, 103, 107, 101);
+    ctx.bezierCurveTo(107, 99, 106, 96, 103, 96);
+    ctx.fill();
+
+    ctx.fillStyle = 'black';
+    ctx.beginPath();
+    ctx.arc(101, 102, 2, 0, Math.PI * 2, true);
+    ctx.fill();
+
+    ctx.beginPath();
+    ctx.arc(89, 102, 2, 0, Math.PI * 2, true);
+    ctx.fill();
+  }
+}
+
+// 角丸の四角形を描画するためのユーティリティ関数
+
+function roundedRect(ctx, x, y, width, height, radius) {
+  ctx.beginPath();
+  ctx.moveTo(x, y + radius);
+  ctx.lineTo(x, y + height - radius);
+  ctx.arcTo(x, y + height, x + radius, y + height, radius);
+  ctx.lineTo(x + width - radius, y + height);
+  ctx.arcTo(x + width, y + height, x + width, y + height - radius, radius);
+  ctx.lineTo(x + width, y + radius);
+  ctx.arcTo(x + width, y, x + width - radius, y, radius);
+  ctx.lineTo(x + radius, y);
+  ctx.arcTo(x, y, x, y + radius, radius);
+  ctx.stroke();
+}
+
+ +

以下の様な表示結果となります。

+ +
{{EmbedLiveSample("Making_combinations", 160, 160, "https://mdn.mozillademos.org/files/9849/combinations.png")}}
+ +

これらは非常に単純な例ですので、詳細は割愛します。ポイントは fillStyle を使用している点と、独自関数 roundedRect() を定義している点です。この様に繰り返し利用する可能性のある処理を関数化しておくと、コード量を減らすことができます。

+ +

fillStyle の詳細についてはこのチュートリアルの後半で説明します。プロパティで、塗りの色を初期値の黒から白に、そしてもう一度黒に変更しています。

+ +

Path2D オブジェクト

+ +

最後の例で見たように、オブジェクトを描くための一連のパスや描画コマンドを、canvas に置くことができます。コードをシンプルにしてパフォーマンスを向上させるために最近のバージョンのブラウザで使用できる {{domxref("Path2D")}} オブジェクトは、描画コマンドをキャッシュあるいは記録することを可能にしています。これにより、パスをすばやく再実行できます。Path2D オブジェクトの構築方法を見ていきましょう:

+ +
+
{{domxref("Path2D.Path2D", "Path2D()")}}
+
Path2D() コンストラクタは、新たにインスタンス化した Path2D オブジェクトを返します。任意で別のパス (コピーを作成)、あるいは SVG パスデータを構成する文字列を引数に指定できます。
+
+ +
new Path2D();     // 空のパスオブジェクトを作成する
+new Path2D(path); // 別の Path2D オブジェクトを複製する
+new Path2D(d);    // SVG パスデータからパスを作成する
+ +

これまで見てきた moveTorectarcquadraticCurveTo など、あらゆるパスメソッドPath2D オブジェクトで使用できます。

+ +

また Path2D API には、パスを結合するための addPath メソッドが追加されています。これは、複数の部品を組み合わせてオブジェクトを構築したい場合などに役立ちます。

+ +
+
{{domxref("Path2D.addPath", "Path2D.addPath(path [, transform])")}}
+
現在のパスに、変換行列 (任意指定) とともに、パスを追加します。
+
+ +

Path2D の例

+ +

この例では、矩形と円を作成します。どちらも Path2D オブジェクトとして保存しており、後で使用することができます。新たな Path2D API に合わせて、いくつかのメソッドが現在のパスに代わり任意で Path2D を受け入れられるように更新されました。ここでは、canvas に両方のオブジェクトを描くため、1つの path 引数を stroke および fill で使用しています。

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    var rectangle = new Path2D();
+    rectangle.rect(10, 10, 50, 50);
+
+    var circle = new Path2D();
+    circle.moveTo(125, 35);
+    circle.arc(100, 35, 25, 0, 2 * Math.PI);
+
+    ctx.stroke(rectangle);
+    ctx.fill(circle);
+  }
+}
+
+ +

{{EmbedLiveSample("Path2D_example", 130, 110, "https://mdn.mozillademos.org/files/9851/path2d.png")}}

+ +

SVG パスを使用する

+ +

canvas の新たな Path2D API の、もうひとつの強力な機能が、canvas でパスを初期化するために SVG パスデータを使用できることです。これにより、SVG と canvas の両方でパスデータを使い回すことができるでしょう。

+ +

パスはある点に移動して (M10 10) 、そこから右へ水平に 80 ポイント移動 (h 80)、下へ 80 ポイント移動 (v 80) 、80ポイント 左へ移動 (h -80) 、そして始点へ戻ります (z)。この例は Path2D コンストラクタのページで確認できます。

+ +
var p = new Path2D('M10 10 h 80 v 80 h -80 Z');
+ +
{{PreviousNext("Web/API/Canvas_API/Tutorial/Basic_usage", "Web/API/Canvas_API/Tutorial/Applying_styles_and_colors")}}
diff --git a/files/ja/web/api/canvas_api/tutorial/drawing_text/index.html b/files/ja/web/api/canvas_api/tutorial/drawing_text/index.html new file mode 100644 index 0000000000..d99101e457 --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/drawing_text/index.html @@ -0,0 +1,174 @@ +--- +title: 文字を描く +slug: Drawing_text_using_a_canvas +tags: + - Canvas + - Graphics + - Intermediate + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Drawing_text +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}
+ +
+

前の章でスタイルや色を適用する方法を見た後は、canvas にテキストを描画する方法を見ていきます。

+
+ +

テキストを描く

+ +

canvas のレンダリングコンテキストでは、2 種類のテキスト描画方法を提供します:

+ +
+
{{domxref("CanvasRenderingContext2D.fillText", "fillText(text, x, y [, maxWidth])")}}
+
(x,y) で指定した位置にテキストを塗りつぶして描画します。任意で最大描画幅を指定できます。
+
{{domxref("CanvasRenderingContext2D.strokeText", "strokeText(text, x, y [, maxWidth])")}}
+
(x,y) で指定した位置にテキストの輪郭を描画します。任意で最大描画幅を指定できます。
+
+ +

fillText の例

+ +

現在の fillStyle を使用して、テキストを塗りつぶして描画します。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.font = "48px serif";
+  ctx.fillText("Hello world", 10, 50);
+}
+ + + +

{{EmbedLiveSample("A_fillText_example", 310, 110)}}

+ +

strokeText の例

+ +

現在の strokeStyle を使用して、テキストの輪郭を描画します。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.font = "48px serif";
+  ctx.strokeText("Hello world", 10, 50);
+}
+ + + +

{{EmbedLiveSample("A_strokeText_example", 310, 110)}}

+ +

テキストのスタイルを設定する

+ +

上記の例ではテキストをデフォルトのサイズより若干大きくするため、すでに font プロパティを使用していました。canvas にテキストを表示する形式を調整できるプロパティは、さらにいくつかあります:

+ +
+
{{domxref("CanvasRenderingContext2D.font", "font = value")}}
+
テキストを描画する際に使用するテキストのスタイルです。CSS の {{cssxref("font")}} プロパティと同じ構文にのっとった文字列です。デフォルトのフォントは 10px sans-serif です。
+
{{domxref("CanvasRenderingContext2D.textAlign", "textAlign = value")}}
+
テキストの配置を設定します。使用できる値は startendleftrightcenter です。デフォルト値は start です。
+
{{domxref("CanvasRenderingContext2D.textBaseline", "textBaseline = value")}}
+
ベースラインの位置ぞろえを設定します。使用できる値は tophangingmiddlealphabeticideographicbottom です。デフォルト値は alphabetic です。
+
{{domxref("CanvasRenderingContext2D.direction", "direction = value")}}
+
書字方向を設定します。使用できる値は ltrrtlinherit です。デフォルト値は inherit です。
+
+ +

以前に CSS を扱ったことがあれば、これらのプロパティも見慣れているでしょう。

+ +

以下は WHATWG 提供の、textBaseline 属性によってサポートされている様々なベースラインを示した図です。The top of the em square is
+
+roughly at the top of the glyphs in a font, the hanging baseline is
+
+where some glyphs like आ are anchored, the middle is half-way
+
+between the top of the em square and the bottom of the em square,
+
+the alphabetic baseline is where characters like Á, ÿ,
+
+f, and Ω are anchored, the ideographic baseline is
+
+where glyphs like 私 and 達 are anchored, and the bottom
+
+of the em square is roughly at the bottom of the glyphs in a
+
+font. The top and bottom of the bounding box can be far from these
+
+baselines, due to glyphs extending far outside the em square.

+ +

textBaseline の例

+ +

以下のコードを編集すると、canvas の変更個所をその場で確認できます:

+ +
ctx.font = "48px serif";
+ctx.textBaseline = "hanging";
+ctx.strokeText("Hello world", 0, 100);
+
+ + + +

{{EmbedLiveSample('Playable_code', 700, 360)}}

+ +

高度なテキスト測定

+ +

テキストのより詳細な情報を得る必要がある場合は、以下のメソッドでそれを測定できます。

+ +
+
{{domxref("CanvasRenderingContext2D.measureText", "measureText()")}}
+
指定したテキストを現在のテキストスタイルで描画したときの幅をピクセル単位で表した情報を持つ、{{domxref("TextMetrics")}} オブジェクトを返します。
+
+ +

以下のコードスニペットは、テキストを測定して幅を得る方法を示しています。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var text = ctx.measureText("foo"); // TextMetrics オブジェクト
+  text.width; // 16;
+}
+
+ +

Gecko 固有の注意事項

+ +

Gecko (Firefox、Firefox OS および他の Mozilla ベースアプリケーション) では一部の接頭辞付き API で、早期バージョンのテキスト描画法を実装しています。これらは非推奨化または削除されており、動作を保証しません。

+ +
{{PreviousNext("Web/API/Canvas_API/Tutorial/Applying_styles_and_colors", "Web/API/Canvas_API/Tutorial/Using_images")}}
diff --git a/files/ja/web/api/canvas_api/tutorial/finale/index.html b/files/ja/web/api/canvas_api/tutorial/finale/index.html new file mode 100644 index 0000000000..e28beb611e --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/finale/index.html @@ -0,0 +1,51 @@ +--- +title: 最後に +slug: Web/Guide/HTML/Canvas_tutorial/Finale +tags: + - キャンバス + - グラウフィックス + - チュートリアル +translation_of: Web/API/Canvas_API/Tutorial/Finale +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Optimizing_canvas")}}
+ +
+

おめでとう! Canvas tutorialは終了です! ここでのナレッジはWebで2Dグラフィックスを作成する際に役立つでしょう。

+
+ +

他の例とチュートリアル

+ +

ここでは様々なデモや更なるcanvasについての例を紹介します。

+ +
+
Codepen.io
+
ブラウザ上のフロントエンドディベロッパー向けのプレイグラウンドとコードエディターです。
+
HTML5 Canvas Tutorials
+
Canvas APIsの例です。
+
Game development
+
ゲームは最も人気な活動の一つです。標準に準拠したWebブラウザで実行できる、より良くより強力なゲームを開発するための新しい技術が定期的に登場しています。
+
+ +

他の Web APIs

+ +

これらのAPIはcanvasとグラフィックスを更に動かす際におそらく使われます

+ +
+
WebGL
+
複雑なグラフィックスや3Dを含んだレンダリングのためのアドバンスドなAPIです。
+
SVG
+
スケーラブル・ベクター・グラフィックスを使用すると、スムーズなスケールを行うために描画されるサイズには関係なく、ベクター(ライン)とシェイプのセットとして画像を描画します。
+
Web Audio
+
WebAudioAPIは、Web上のオーディオを制御したり、ディベロッパーがオーディオのリソースを選択したり、エフェクトをオーディオに追加したり、オーディオ・ビジュアライザーを作成したり、空間的エフェクト(音響のような)を適用したり、他にも様々な処理を行うためのオーディオの多目的なシステムを提供します。
+
+ +

質問

+ +
+
Stackoverflow
+
質問のタグは"canvas"となります。
+
Comments about this tutorial – the MDN documentation community
+
このチュートリアルに対するコメントや感謝の言葉があるなら、是非我々に届けてほしいです。
+
+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Optimizing_canvas")}}

diff --git a/files/ja/web/api/canvas_api/tutorial/optimizing_canvas/index.html b/files/ja/web/api/canvas_api/tutorial/optimizing_canvas/index.html new file mode 100644 index 0000000000..0975cec653 --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/optimizing_canvas/index.html @@ -0,0 +1,118 @@ +--- +title: canvas の最適化 +slug: Web/Guide/HTML/Canvas_tutorial/Optimizing_canvas +tags: + - Advanced + - Canvas + - Graphics + - HTML + - HTML5 + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Optimizing_canvas +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility", "Web/API/Canvas_API/Tutorial/Finale")}}
+ +
+

{{HTMLElement("canvas")}} 要素は、ウェブで 2D グラフィックスを描画するためにもっとも広く使用されているツールのひとつです。しかし、ウェブサイトやアプリが Canvas API の限界付近まで使用するようになって、パフォーマンスが悪化するようになりました。この記事では、 canvas 要素の使用を最適化して、グラフィックを確実に改善するための提案を行います。

+
+ +

パフォーマンスに関する TIPS

+ +

キャンバスのパフォーマンスを向上させるための TIPS 集を以下に掲載します。

+ +

同様のプリミティブや繰り返し使用するオブジェクトをオフスクリーン canvas で事前にレンダリングする

+ +

アニメーションフレーム毎に同じ描画操作を繰り返していることに気づいたら、あらかじめオフスクリーンキャンバスに描画しておくことを検討しましょう。そして、必要な時に本来のキャンバスにオフスクリーン画像を、最初の場所で生成したときのステップなしで描画することができます。

+ +
myCanvas.offscreenCanvas = document.createElement('canvas');
+myCanvas.offscreenCanvas.width = myCanvas.width;
+myCanvas.offscreenCanvas.height = myCanvas.height;
+
+myCanvas.getContext('2d').drawImage(myCanvas.offScreenCanvas, 0, 0);
+
+ +

浮動小数点数値の座標を避けて整数を使用する

+ +

canvas で整数以外の値を使用してオブジェクトを描画すると、サブピクセルレンダリングを実行します。

+ +
ctx.drawImage(myImage, 0.3, 0.5);
+
+ +

これはアンチエイリアス効果を生成するために、ブラウザーに追加の計算処理を強制します。これを避けるために、たとえば {{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}} を呼び出す際に {{jsxref("Math.floor()")}} を使用して、すべての座標で端数処理を行ってください。

+ +

drawImage で画像のスケーリングを行わない

+ +

{{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}} でいつも画像のスケーリング処理を行うのではなく、さまざまなサイズの画像をオフスクリーン canvas でキャッシュしてください。

+ +

複雑なシーンでは複数レイヤーの canvas を使用する

+ +

アプリケーションでは、一部のオブジェクトは頻繁に動かしたり変更したりする必要があるのに対し、他のものは比較的静止していることが分かるかもしれません。この場合に可能な最適化は、複数の <canvas> 要素を使用してアイテムをレイヤー化することです。

+ +

例えば、 UI があるゲームが最上位にあり、中間にゲームプレイの動作があり、最下位に静止した背景があるとします。この場合、ゲームを3つの <canvas> レイヤーに分割することができます。 UI はユーザーの入力のみに基づいて変化し、ゲームプレイレイヤーはフレーム毎に変化し、背景は基本的に変化しないままでいます。

+ +
<div id="stage">
+  <canvas id="ui-layer" width="480" height="320"></canvas>
+  <canvas id="game-layer" width="480" height="320"></canvas>
+  <canvas id="background-layer" width="480" height="320"></canvas>
+</div>
+
+<style>
+  #stage {
+    width: 480px;
+    height: 320px;
+    position: relative;
+    border: 2px solid black;
+  }
+
+  canvas { position: absolute; }
+  #ui-layer { z-index: 3; }
+  #game-layer { z-index: 2; }
+  #background-layer { z-index: 1; }
+</style>
+
+ +

大きな背景画像に CSS を使用する

+ +

静止した背景画像がある場合は、ただの {{HTMLElement("div")}} に CSS の {{cssxref("background")}} プロパティを使用し、 canvas の下に配置することで描画することができます。これにより、大きな画像を毎回 canvas に描画する処理を避けます。

+ +

CSS transforms を使用して canvas をスケーリングする

+ +

CSS 変形 は、 GPU を使用しますのでより高速です。もっともよいのは拡大縮小しないことですが、そうでなければ大きな canvas を縮小するよりも小さな canvas を拡大したほうが良好です。

+ +
var scaleX = window.innerWidth / canvas.width;
+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 + ')';
+
+ +

透過をやめる

+ +

アプリケーションが canvas を使用していて背後のものを透過させる必要がない場合は、 {{domxref("HTMLCanvasElement.getContext()")}} で描画コンテキストを生成する際に alpha オプションを false に設定しましょう。この情報を使用してブラウザーが描画を最適化する可能性があります。

+ +
var ctx = canvas.getContext('2d', { alpha: false });
+ +

その他の TIPS

+ + + +

関連情報

+ + + +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility", "Web/API/Canvas_API/Tutorial/Finale")}}

diff --git a/files/ja/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html b/files/ja/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html new file mode 100644 index 0000000000..33e9ef3e21 --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/pixel_manipulation_with_canvas/index.html @@ -0,0 +1,264 @@ +--- +title: Canvas とピクセル操作 +slug: Web/Guide/HTML/Canvas_tutorial/Pixel_manipulation_with_canvas +tags: + - Canvas + - Graphics + - Intermediate + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Advanced_animations", "Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility")}}
+ +
+

これまで、canvas の実際のピクセルは見てきませんでした。ImageData オブジェクトを使用して、ピクセルデータを操作するためにデータ配列へ直接読み取りや書き込みを行うことが可能です。また、画像のスムージング (アンチエイリアシング) の制御方法や canvas の画像を保存する方法も見ていきます。

+
+ +

ImageData オブジェクト

+ +

{{domxref("ImageData")}} オブジェクトは、canvas オブジェクトの領域にあるピクセルデータを表します。これは以下の読み取り専用プロパティを持ちます:

+ +
+
width
+
画像の幅をピクセル数で表します。
+
height
+
画像の高さをピクセル数で表します。
+
data
+
0 から 255 の間の (両端の値を含む) 整数データを RGBA の順で収めた一次元配列を表す {{jsxref("Uint8ClampedArray")}} です。
+
+ +

data プロパティは、生のピクセルデータを参照するためにアクセス可能な {{jsxref("Uint8ClampedArray")}} を返します。それぞれのピクセルは 4 つの 1 バイト値 (赤、緑、青、アルファの順、すなわち "RGBA" 形式) で表します。また、それぞれの色成分は 0 から 255 の間の整数で表します。さらに、それぞれの成分は配列内で連続した添字が割り当てられており、左上のピクセルの赤色成分が配列の添え字 0 になります。配列の中でピクセルは左から右へ進み、さらに下へと進んでいきます。

+ +

{{jsxref("Uint8ClampedArray")}} は height × width × 4 バイトのデータがあり、添字の範囲は 0 から (height×width×4)-1 になります。

+ +

例えば画像の 50 行目の 200 列目にあるピクセルから青色成分の値を読み取るには、以下のようにします:

+ +
blueComponent = imageData.data[((50*(imageData.width*4)) + (200*4)) + 2];
+ +

Uint8ClampedArray.length 属性を読み取ると、ピクセル配列のサイズをバイト数で知ることができます:

+ +
var numBytes = imageData.data.length;
+
+ +

ImageData オブジェクトを作成する

+ +

新たに空の ImageData オブジェクトを作成するには、{{domxref("CanvasRenderingContext2D.createImageData", "createImageData()")}} メソッドを使用します。createImageData() メソッドは 2 種類の形式があります:

+ +
var myImageData = ctx.createImageData(width, height);
+ +

これは、特定の寸法の新たな ImageData オブジェクトを作成します。すべてのピクセルは透明な黒色に設定されます。

+ +

anotherImageData で指定したオブジェクトと同じ寸法の、新たな ImageData オブジェクトを作成することもできます。新しいオブジェクトのピクセルは、すべて透明な黒色に設定されます。画像データはコピーされません!

+ +
var myImageData = ctx.createImageData(anotherImageData);
+ +

コンテキストのピクセルデータを取得する

+ +

canvas コンテキストのピクセルデータの複製を持つ ImageData オブジェクトを取得するには、getImageData() メソッドを使用します:

+ +
var myImageData = ctx.getImageData(left, top, width, height);
+ +

このメソッドは (left,top)、(left+width, top)、(left, top+height)、(left+width, top+height) の点で四隅を表した canvas の領域のピクセルデータを表す ImageData オブジェクトを返します。点の座標は、canvas の座標空間の単位で指定します。

+ +
+

注記: 返される ImageData オブジェクトで、canvas の外部にあるピクセルはすべて透明な黒色になります。

+
+ +

このメソッドは、Manipulating video using canvas の記事でも説明しています。

+ +

カラーピッカー

+ +

この例では、マウスカーソルの下にある色を表示するために getImageData() メソッドを使用しています。ここでは現在のマウスカーソルの位置を layerXlayerY で求めて、getImageData() が提供するピクセル配列で該当位置のピクセルデータを探します。最後に、色を表示するための <div> で背景色とテキストを設定するために、配列データを使用します。

+ + + +
var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+img.onload = function() {
+  ctx.drawImage(img, 0, 0);
+  img.style.display = 'none';
+};
+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;
+  color.textContent = rgba;
+}
+canvas.addEventListener('mousemove', pick);
+
+ +

{{EmbedLiveSample('A_color_picker', 610, 240)}}

+ +

コンテキストにピクセルデータを描く

+ +

putImageData() メソッドを使用して、コンテキストにピクセルデータを描くことができます:

+ +
ctx.putImageData(myImageData, dx, dy);
+
+ +

引数 dxdy は、描画したいピクセルデータの左上の隅を描く位置を、コンテキストのデバイス座標で示します。

+ +

例えば myImageData が表す画像全体をコンテキストの左上の隅から描くには、単純に以下のようにします:

+ +
ctx.putImageData(myImageData, 0, 0);
+
+ +

色のグレースケール化と反転

+ +

この例ではすべてのピクセルの値を変更するためにイテレートを行って、putImageData() を使用して変更後のピクセル配列を canvas に書き戻しています。invert 関数は、単純に最大値の 255 からそれぞれの色の値を減算します。grayscale 関数は、単純に赤、緑、青の平均値を使用します。また、例えば x = 0.299r + 0.587g + 0.114b といった式による加重平均も使用できます。詳しくは Wikipedia の Grayscale (日本語版) をご覧ください。

+ + + +
var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+img.onload = function() {
+  draw(this);
+};
+
+function draw(img) {
+  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);
+  var data = imageData.data;
+
+  var invert = function() {
+    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() {
+    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 invertbtn = document.getElementById('invertbtn');
+  invertbtn.addEventListener('click', invert);
+  var grayscalebtn = document.getElementById('grayscalebtn');
+  grayscalebtn.addEventListener('click', grayscale);
+}
+
+ +

{{EmbedLiveSample('Grayscaling_and_inverting_colors', 330, 270)}}

+ +

ズームとアンチエイリアシング

+ +

{{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}} メソッド、第 2 の canvas、{{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}} プロパティの力を借りて、画像をズームアップして詳しく見ることができます。

+ +

マウスカーソルの位置を取得して、そこから上下左右に 5 ピクセルの範囲の画像を切り取ります。そして切り取った画像を別の canvas にコピーして、望むサイズにリサイズします。ズーム用の canvas では、元の canvas から切り取った 10×10 ピクセルの画像を 200×200 ピクセルにリサイズしています。

+ +
zoomctx.drawImage(canvas,
+                  Math.abs(x - 5), Math.abs(y - 5),
+                  10, 10, 0, 0, 200, 200);
+ +

アンチエイリアシングはデフォルトで有効ですので、ピクセルをはっきりさせるためにスムージングを無効化したいと考えるかもしれません。チェックボックスを切り替えると、imageSmoothingEnabled プロパティ (さまざまなブラウザ向けに接頭辞が必要です) の効果を確認できます。

+ + + + + +
var img = new Image();
+img.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+img.onload = function() {
+  draw(this);
+};
+
+function draw(img) {
+  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');
+
+  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);
+
+  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);
+  };
+
+  canvas.addEventListener('mousemove', zoom);
+}
+ +

{{EmbedLiveSample('Zoom_example', 620, 490)}}

+ +

画像を保存する

+ +

{{domxref("HTMLCanvasElement")}} は、画像を保存する際に役に立つ toDataURL() メソッドを提供します。これは、引数 type で指定した形式 (既定値は PNG) で表した画像を持つ data URI を返します。返される画像の解像度は 96 dpi です。

+ +
+
{{domxref("HTMLCanvasElement.toDataURL", "canvas.toDataURL('image/png')")}}
+
既定の設定。PNG 画像を作成します。
+
{{domxref("HTMLCanvasElement.toDataURL", "canvas.toDataURL('image/jpeg', quality)")}}
+
JPG 画像を作成します。オプションで、品質を 0 から 1 の範囲で指定できます。1 は最高品質、0 はほとんど見分けがつかなくなりますがファイルサイズを小さくできます。
+
+ +

canvas から生成した data URI は、例えば任意の {{HTMLElement("image")}} のソースとして使用したり、ディスクに保存するために download 属性を持つハイパーリンクに投入することができます。

+ +

また、canvas から {{domxref("Blob")}} を生成することもできます。

+ +
+
{{domxref("HTMLCanvasElement.toBlob", "canvas.toBlob(callback, type, encoderOptions)")}}
+
canvas に含まれる画像を表す Blob オブジェクトを作成します。
+
+ +

関連情報

+ + + +
{{PreviousNext("Web/API/Canvas_API/Tutorial/Advanced_animations", "Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility")}}
diff --git a/files/ja/web/api/canvas_api/tutorial/transformations/index.html b/files/ja/web/api/canvas_api/tutorial/transformations/index.html new file mode 100644 index 0000000000..066b5d2b84 --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/transformations/index.html @@ -0,0 +1,282 @@ +--- +title: Transformations +slug: Web/Guide/HTML/Canvas_tutorial/Transformations +tags: + - Canvas + - Graphics + - Guide + - HTML + - HTML5 + - Intermediate + - Web +translation_of: Web/API/Canvas_API/Tutorial/Transformations +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Using_images", "Web/API/Canvas_API/Tutorial/Compositing")}}
+ +
これまでのチュートリアルで、canvas のグリッド座標空間について学びました。今まではデフォルトのグリッドしか使用しておらず、また必要に応じて canvas 全体のサイズを変更していました。変換 (transformations) には、元の canvas を別の場所に移す、回転する、拡大縮小するといった、より強力な手段があります。
+ +

状態を保存および復元する

+ +

変換のメソッドを見ていく前に、より複雑な描画を始めたときに不可欠になメソッドを 2 つ見ておきましょう。

+ +
+
{{domxref("CanvasRenderingContext2D.save", "save()")}}
+
canvas 全体の状態を保存します。
+
{{domxref("CanvasRenderingContext2D.restore", "restore()")}}
+
直近に保存した canvas の状態を復元します。
+
+ +

canvas の状態は、スタックに保存されます。save() メソッドを呼び出すたびに、現在の描画状態をスタックにプッシュします。描画状態は以下の情報で構成されます:

+ + + +

save() メソッドは、何回でも呼び出すことができます。restore() メソッドを呼び出すたびに、最後に保存された状態をスタックからポップして、すべての保存済み設定を復元します。

+ +

save および restore の例

+ +

この例は、連続した矩形のセットを描画するときに、描画状態のスタックがどのように機能するかを示します。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.fillRect(0,0,150,150);   // 既定の設定で矩形を描画
+  ctx.save();                  // 既定の状態を保存
+
+  ctx.fillStyle = '#09F';      // 設定変更
+  ctx.fillRect(15,15,120,120); // 新たな設定で矩形を描画
+
+  ctx.save();                  // 現在の状態を保存
+  ctx.fillStyle = '#FFF';      // 設定変更
+  ctx.globalAlpha = 0.5;
+  ctx.fillRect(30,30,90,90);   // 新たな設定で矩形を描画
+
+  ctx.restore();               // 以前の状態を復元
+  ctx.fillRect(45,45,60,60);   // 復元した設定で矩形を描画
+
+  ctx.restore();               // 以前の状態を復元
+  ctx.fillRect(60,60,30,30);   // 復元した設定で矩形を描画
+}
+ + + +

最初のステップで、大きな矩形を既定の設定で描きます。次にこの状態を保存して、塗りつぶし色を変更します。そして、2 番目のやや小さい青色の矩形を描いて、状態を保存します。もう一度描画設定を変更して、3 番目の半透明な白色の矩形を描きます。

+ +

ここまでは、これまでの章で行ってきたことによく似ています。しかし最初に restore() 文を呼び出したとき、スタックの先頭の描画状態が削除されて、その設定が復元されます。save() を使用して状態を保存しなければ、前の状態に戻すために塗りつぶし色や透過性を手動で変更しなければなりません。ここではプロパティが 2 つであり容易ですが、プロパティが多ければコードが一気にとても長くなります。

+ +

2 番目の restore() 文を呼び出すと、元の状態 (1 番目の save を呼び出す前に設定した状態) を復元して、最後の矩形を再び黒色で描きます。

+ +

{{EmbedLiveSample("A_save_and_restore_canvas_state_example", "180", "180", "https://mdn.mozillademos.org/files/249/Canvas_savestate.png")}}

+ +

移動

+ +

1 番目の変換メソッドとして、translate() を見ていきましょう。このメソッドは、canvas や canvas の原点をグリッド内の別の位置へ移動するために使用します。

+ +
+
{{domxref("CanvasRenderingContext2D.translate", "translate(x, y)")}}
+
canvas や canvas の原点をグリッド上で移動します。x は水平方向の移動距離、y はグリッドを垂直方向の移動距離を示します。
+
+ +

変換を行う前に canvas の状態を保存しておくことは、よいアイデアです。ほとんどの場合、元の状態に戻すためには逆の変換を行うよりも restore メソッドを呼び出すほうが簡単です。また、ループ内で変換を行っているときに canvas の状態の保存や復元を行わなければ、canvas の端の外側に描画したために、描いたものの一部を失ってしまうかもしれません。

+ +

translate の例

+ +

この例は、canvas の原点を移動する利点をいくつか示しています。translate() メソッドを使用しなければ、すべての矩形が同じ位置 (0,0) に描かれます。また translate() によって、fillRect() 関数で座標を手動で調整する必要なく、どこにでも自由に矩形を置くことができます。これにより若干理解しやすく、また使いやすくなります。

+ +

draw() 関数で、for ループを使用して fillRect() 関数を 9 回呼び出しています。それぞれのループで canvas を移動して矩形を描き、その後に元の状態を復元します。描画位置を調節する translate() を頼って、fillRect() は毎回同じ座標を使用していることに注目してください。

+ +
function draw() {
+  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.translate(10+j*50,10+i*50);
+      ctx.fillRect(0,0,25,25);
+      ctx.restore();
+    }
+  }
+}
+
+ + + +

{{EmbedLiveSample("A_translate_example", "160", "160", "https://mdn.mozillademos.org/files/9857/translate.png")}}

+ +

回転

+ +

2 番目の変換メソッドは rotate() です。現在の原点を中心にして canvas を回転させるために使用します。

+ +
+
{{domxref("CanvasRenderingContext2D.rotate", "rotate(angle)")}}
+
現在の原点を中心にしてラジアンで示した angle の分、canvas を時計回りに回転します。
+
+ +

回転の中心は、常に canvas の原点です。中心を変更するには、translate() メソッドを使用して canvas を移動しなければなりません。

+ +

rotate の例

+ +

この例は、まずは canvas の原点で矩形を回転するために rotate() メソッドを使用して、次に矩形自身の中心で回転するために translate() の助けを借りています。

+ +
+

備忘: 角度はラジアン (radians) で表しており、度数 (degrees) ではありません。これは以下の方法で変換できます: radians = (Math.PI/180)*degrees

+
+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 左の矩形を canvas の原点で回転する
+  ctx.save();
+  // blue rect
+  ctx.fillStyle = "#0095DD";
+  ctx.fillRect(30,30, 100, 100);
+  ctx.rotate((Math.PI/180)*25);
+  // 灰色の矩形
+  ctx.fillStyle = "#4D4E53";
+  ctx.fillRect(30,30, 100, 100);
+  ctx.restore();
+
+  // 右の矩形を矩形の中心で回転する
+  // draw blue rect
+  ctx.fillStyle = "#0095DD";
+  ctx.fillRect(150, 30, 100, 100);
+
+  ctx.translate(200, 80); // 矩形の中心に移動する
+                          // x = x + 0.5 * 幅
+                          // y = y + 0.5 * 高さ
+  ctx.rotate((Math.PI/180)*25); // 回転する
+  ctx.translate(-200, -80); // 元の位置に移動する
+
+  // 灰色の矩形を描く
+  ctx.fillStyle = "#4D4E53";
+  ctx.fillRect(150, 30, 100, 100);
+}
+
+ +

矩形を中心で回転するために、canvas を矩形の中心へ移動した後に canvas を回転します。そして canvas を 0,0 へ移動した後に矩形を描きます。

+ + + +

{{EmbedLiveSample("A_rotate_example", "310", "210", "https://mdn.mozillademos.org/files/9859/rotate.png")}}

+ +

スケーリング

+ +

次の変換メソッドはスケーリングです。canvas のグリッドの単位を増減するために使用します。これは、図形やビットマップを縮小または拡大して描くために使用できます。

+ +
+
{{domxref("CanvasRenderingContext2D.scale", "scale(x, y)")}}
+
canvas の単位を x (水平方向) または y (垂直方向) で指定した分スケーリングします。どちらの引数も実数です。1.0 より小さい値は単位あたりのサイズが減少、1.0 より大きい値は単位あたりのサイズが増加します。1.0 では単位あたりのサイズが変わりません。
+
+ +

負数を使用すると軸を反転できます (例えば translate(0,canvas.height); scale(1,-1); で、原点が左下の隅にある有名なデカルト座標系になります)。

+ +

デフォルトでは、canvas の 1 単位は 1 ピクセルとまったく同じです。例えば、スケーリング係数に 0.5 を適用すると 1 単位が 0.5 ピクセルになり、図形が半分のサイズで描かれます。同様にスケーリング係数を 2.0 に設定すると単位あたりのサイズが増えて、1 単位あたり 2 ピクセルになります。この結果、図形は 2 倍の大きさで描かれます。

+ +

scale の例

+ +

この例は、図形をさまざまなスケーリング係数で描きます。

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // シンプルな図形を描いて、スケーリングする
+  ctx.save();
+  ctx.scale(10, 3);
+  ctx.fillRect(1,10,10,10);
+  ctx.restore();
+
+  // 水平方向に反転する
+  ctx.scale(-1, 1);
+  ctx.font = "48px serif";
+  ctx.fillText("MDN", -135, 120);
+}
+
+ + + +

{{EmbedLiveSample("A_scale_example", "160", "160", "https://mdn.mozillademos.org/files/9861/scale.png")}}

+ +

変形

+ +

最後に、以下の変換メソッドで、変換行列によって直接変更することができます。

+ +
+
{{domxref("CanvasRenderingContext2D.transform", "transform(a, b, c, d, e, f)")}}
+
引数で表した行列と、現在の変換行列で乗算を行います。変換行列は以下のとおりです: [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right]
+
+ +
+
いずれかの引数が Infinity になる場合は、メソッドで例外を発生させるのではなく行列を infinite としてマークしなければなりません。
+
+ +

この関数の引数は以下のとおりです:

+ +
+
a (m11)
+
水平方向のスケーリング。
+
b (m12)
+
水平方向のスキュー。
+
c (m21)
+
垂直方向のスキュー。
+
d (m22)
+
垂直方向のスケーリング。
+
e (dx)
+
水平方向の移動。
+
f (dy)
+
垂直方向の移動。
+
{{domxref("CanvasRenderingContext2D.setTransform", "setTransform(a, b, c, d, e, f)")}}
+
現在の変形を単位行列にリセットして、同じ引数で transform() メソッドを呼び出します。これは基本的に、現在の変形をアンドゥしてから指定した変形を行う操作を一度に行うものです。
+
{{domxref("CanvasRenderingContext2D.resetTransform", "resetTransform()")}}
+
現在の変形を単位行列にリセットします。これは ctx.setTransform(1, 0, 0, 1, 0, 0); を呼び出すことと同じです。
+
+ +

transformsetTransform の例

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  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);
+    ctx.fillStyle = "rgb(" + c + "," + c + "," + c + ")";
+    ctx.fillRect(0, 0, 100, 10);
+    ctx.transform(cos, sin, -sin, cos, 0, 0);
+  }
+
+  ctx.setTransform(-1, 0, 0, 1, 100, 100);
+  ctx.fillStyle = "rgba(255, 128, 255, 0.5)";
+  ctx.fillRect(0, 50, 100, 100);
+}
+
+ + + +

{{EmbedLiveSample("Example_for_transform_and_setTransform", "230", "280", "https://mdn.mozillademos.org/files/255/Canvas_transform.png")}}

+ +
{{PreviousNext("Web/API/Canvas_API/Tutorial/Using_images", "Web/API/Canvas_API/Tutorial/Compositing")}}
diff --git a/files/ja/web/api/canvas_api/tutorial/using_images/index.html b/files/ja/web/api/canvas_api/tutorial/using_images/index.html new file mode 100644 index 0000000000..588a662e5b --- /dev/null +++ b/files/ja/web/api/canvas_api/tutorial/using_images/index.html @@ -0,0 +1,337 @@ +--- +title: 画像を使う +slug: Web/Guide/HTML/Canvas_tutorial/Using_images +tags: + - Advanced + - Canvas + - Graphics + - HTML + - Tutorial +translation_of: Web/API/Canvas_API/Tutorial/Using_images +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations" )}}
+ +
+

これまで、図形を作成してスタイルを適用する方法を見てきました。{{HTMLElement("canvas")}} のより面白い機能のひとつが、画像を扱えることです。これは動的な画像合成を行う、グラフの背景として使用する、ゲームのスプライトとして使用するなどといったことが可能です。PNG、GIF、JPEG といった、ブラウザがサポートする形式の外部画像を使用できます。同じページ上の別の canvas 要素によって生成された画像も、ソースとして使用できます!

+
+ +

基本的には 2 ステップの手続きによって、画像を canvas にインポートします:

+ +
    +
  1. {{domxref("HTMLImageElement")}} オブジェクトまたは別の canvas 要素への参照を、ソースとして取得します。URL を与えることでも、画像を使用できます。
  2. +
  3. drawImage() 関数を使用して、画像を canvas に描きます。
  4. +
+ +

これを行う方法を見ていきましょう。

+ +

描く画像を取得する

+ +

canvas API は、以下のデータ形式を画像ソースとして使用できます:

+ +
+
{{domxref("HTMLImageElement")}}
+
{{HTMLElement("img")}} 要素だけでなく、Image() コンストラクタを使用して作成した画像も含みます。
+
{{domxref("HTMLVideoElement")}}
+
HTML の {{HTMLElement("video")}} 要素を画像ソースとして使用すると、現在のフレームを動画から取得して、画像として使用します。
+
{{domxref("HTMLCanvasElement")}}
+
別の {{HTMLElement("canvas")}} 要素を画像ソースとして使用できます。
+
+ +

これらのソースは集約的に、{{domxref("CanvasImageSource")}} 型から参照されています。

+ +

canvas で使用する画像を取得する方法がいくつかあります。

+ +

同一ページ上の画像を使用する

+ +

以下のいずれかを使用して、canvas として同一ページ上の画像への参照を取得できます:

+ + + +

ほかのドメインにある画像を使用する

+ +

{{HTMLElement("img")}} 要素の {{htmlattrxref("crossorigin", "img")}} 属性 ({{domxref("HTMLImageElement.crossOrigin")}} プロパティに反映されます) を使用して、drawImage() を呼び出してほかのドメインから画像を読み込む許可を求めることができます。ホスティングドメインが画像のクロスドメインアクセスを許可している場合は、canvas を汚染せずに画像を使用できます。そうでない場合は、画像を使用すると canvas を汚染します

+ +

ほかの canvas 要素を使用する

+ +

通常の画像と同様に、{{domxref("document.getElementsByTagName()")}} または {{domxref("document.getElementById()")}} メソッドを使用してほかの canvas 要素にアクセスできます。対象の canvas を使用する前に、そのキャンバスで描画を終えるようにしてください。

+ +

より実践的な使用法のひとつが、別の大きな canvas のサムネイルビューとして第 2 の canvas を使用することです。

+ +

最初から画像を作成する

+ +

もうひとつの方法は、スクリプト内で新たな {{domxref("HTMLImageElement")}} オブジェクトを作成することです。そのために、便利な Image() コンストラクタを使用できます:

+ +
var img = new Image();   // 新たな img 要素を作成
+img.src = 'myImage.png'; // ソースのパスを設定
+
+ +

このスクリプトを実行すると、画像の読み込みが始まります。

+ +

画像の読み込みが完了する前に drawImage() を呼び出しても、何も行いません (あるいは、古いブラウザでは例外が発生するかもしれません)。よって画像を読み込む前に描画しないようにするために、load イベントを使用する必要があります:

+ +
var img = new Image();   // 新たな img 要素を作成
+img.addEventListener("load", function() {
+  // drawImage を実行する文をここに置く
+}, false);
+img.src = 'myImage.png'; // ソースのパスを設定
+
+ +

これは、外部の画像を 1 つしか使用しない場合はよい方法ですが、複数の画像を追跡しなければならない場合は、より器用な方法に頼らなければなりません。画像の事前読み込み法を見ていくことはこのチュートリアルの対象を超えますが、心に留めておいてください。

+ +

data: URL で画像を埋め込む

+ +

画像を埋め込む別の方法が、data: url です。Data URL によって、画像を Base64 でエンコードした文字列として、コード内で完全に定義できます。

+ +
var img = new Image();   // 新たな img 要素を作成
+img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==';
+
+ +

data URL の利点のひとつが、別にサーバとの通信を行うことなく即座に結果の画像を使用できることです。ほかに潜在的な利点として CSSJavaScriptHTML、画像をひとつのファイルにカプセル化することもでき、ほかの場所へ持ち運びやすくなります。

+ +

この方法の欠点は画像がキャッシュされないことと、大きな画像をエンコードした URL がとても長くなることです。

+ +

動画のフレームを使用する

+ +

{{HTMLElement("video")}} 要素が提供する動画のフレームも (動画が非表示であっても) 使用できます。例えば ID が "myvideo" である {{HTMLElement("video")}} 要素があるとき、以下のようなことができます:

+ +
function getMyVideo() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    return document.getElementById('myvideo');
+  }
+}
+
+ +

これは動画の {{domxref("HTMLVideoElement")}} オブジェクトを返します。このオブジェクトは先に述べたとおり、CanvasImageSource として使用できるオブジェクトのひとつです。

+ +

画像を描く

+ +

ソース画像オブジェクトへの参照を取得したら、drawImage() メソッドを使用して画像を canvas に描画できます。後ほど見るように、drawImage() メソッドをオーバーロードした派生形がいくつかあります。もっとも基本的な形式は以下のようなものです:

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, x, y)")}}
+
引数 image で指定した CanvasImageSource を、座標 (x, y) に描画します。
+
+ +
+

SVG 画像は、ルート <svg> 要素で幅と高さを指定しなければなりません。

+
+ +

例: シンプルな折れ線グラフ

+ +

以下の例は、小さな折れ線グラフの背景として外部の画像を使用しています。背景画像を使用すると背景を生成するコードが不要になりますので、スクリプトをかなり小さくすることができます。この例では画像を 1 つしか使用しませんので、描画する文を実行するために image オブジェクトの load イベントハンドラを使用しています。drawImage() メソッドは背景画像を座標 (0, 0) に配置します。これは canvas の左上の隅です。

+ + + +
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 = 'https://mdn.mozillademos.org/files/5395/backdrop.png';
+}
+ +

結果のグラフは以下のようになります:

+ +

{{EmbedLiveSample("Example_A_simple_line_graph", 220, 160, "https://mdn.mozillademos.org/files/206/Canvas_backdrop.png")}}

+ +

スケーリング

+ +

drawImage() メソッドの第 2 の形式は引数が 2 つ追加されており、canvas に拡大・縮小した画像を配置することができます。

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, x, y, width, height)")}}
+
これは引数 width および height を追加しており、画像を canvas に描画する際のサイズを示します。
+
+ +

例: 画像をタイリングする

+ +

以下の例は画像を壁紙として使用して、canvas 上で数回繰り返して貼り付けています。ループ処理によって、さまざまな場所に縮小した画像を貼り付けました。以下のコードでは、最初の for ループで行の繰り返し処理を行います。2 番目の for ループで列の繰り返し処理を行います。画像は元のサイズの 3 分の 1 である、50x38 ピクセルに縮小しています。

+ +
+

注記: 画像を拡大しすぎると不鮮明に、あるいは縮小しすぎると荒くなります。読みやすくしておかなければならない文字列が画像内にある場合は、サイズを変更しないほうがよいでしょう。

+
+ + + +
function draw() {
+  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.src = 'https://mdn.mozillademos.org/files/5397/rhino.jpg';
+}
+ +

canvas の結果は以下のようになります:

+ +

{{EmbedLiveSample("Example_Tiling_an_image", 160, 160, "https://mdn.mozillademos.org/files/251/Canvas_scale_image.png")}}

+ +

切り抜き

+ +

drawImage() メソッドの第 3 かつ最後の形式は、画像ソースについて 8 個の引数が追加されています。これはソース画像の一部を切り抜いて、サイズ変更および canvas への描画を行います。

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)")}}
+
この関数は、image から左上の隅が (sx, sy)、幅と高さが sWidth および sHeight である矩形で指定されるソース画像の領域を取得して、canvas の (dx, dy) で示した位置に配置して、dWidth および dHeight で指定したサイズに拡大・縮小します。
+
+ +

何を行っているかを正しく理解するために、右の画像を見ると役に立つでしょう。始めの 4 つの引数は、ソース画像を切り抜く場所とサイズを定義します。最後の 4 つの引数は、描画先 canvas で画像を描画する矩形を定義します。

+ +

切り抜きは、画像を合成する際に役に立つでしょう。ひとつの画像ファイルにすべての要素を置いておき、このメソッドを使用して完成形の描画結果に合成します。例えばチャートを作成したいときに、すべての必要なテキストをひとつのファイルに収めた PNG 画像を用意して、データに応じてチャートの目盛りをとても簡単に変更できるでしょう。ほかの利点として、すべての画像を個別に読み込む必要がありませんので、読み込みパフォーマンスが向上するでしょう。

+ +

例: 画像をフレームに収める

+ +

以下の例では前の例と同じサイの画像を使用していますが、頭の部分を切り抜いて額縁の中に合成しています。額縁の画像は、ドロップシャドウを含む 24 ビット PNG 画像です。GIF や 8 ビット PNG 画像と異なり、24 ビット PNG 画像は 8 ビットのアルファチャンネルが含まれていますので、マットカラーに悩まされることなく背景に重ねることができます。

+ +
<html>
+ <body onload="draw();">
+   <canvas id="canvas" width="150" height="150"></canvas>
+   <div style="display:none;">
+     <img id="source" src="https://mdn.mozillademos.org/files/5397/rhino.jpg" width="300" height="227">
+     <img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
+   </div>
+ </body>
+</html>
+
+ +
function draw() {
+  var canvas = document.getElementById('canvas');
+  var ctx = canvas.getContext('2d');
+
+  // スライス画像を描く
+  ctx.drawImage(document.getElementById('source'),
+                33, 71, 104, 124, 21, 20, 87, 104);
+
+  // フレームを描く
+  ctx.drawImage(document.getElementById('frame'),0,0);
+}
+ +

この例では、画像の読み込みに別の方法を使用しています。新しい {{domxref("HTMLImageElement")}} オブジェクトを作成して画像を読み込む代わりに、画像を HTML ソース内の {{HTMLElement("img")}} タグとして直接含めておき、そこから画像を取り込んでいます。この画像は、CSS の {{cssxref("display")}} プロパティを none に設定して隠しています。

+ +

{{EmbedLiveSample("Example_Framing_an_image", 160, 160, "https://mdn.mozillademos.org/files/226/Canvas_drawimage2.jpg")}}

+ +

スクリプト自体はとてもシンプルです。それぞれの {{HTMLElement("img")}} に ID 属性を割り当てており、{{domxref("document.getElementById()")}} を使用して簡単に選択できます。最初の画像からサイを切り抜いて canvas 上でサイズを調整するため単純に drawImage() を使用して、その後に第 2 の drawImage() を呼び出して枠を描きます。

+ + + +

この章の最後の例では、小さなアートギャラリーを作ります。いくつかの画像を持つテーブルで、ギャラリーを構成します。ページを読み込むとそれぞれの画像のために {{HTMLElement("canvas")}} 要素を挿入して、そこに画像と額縁を描画します。

+ +

ここでは、周囲に描く額縁を含むすべての画像が一定の幅および高さです。額縁をぴったり合わせるために画像の幅と高さを使用するよう、スクリプトを改良することができるでしょう。

+ +

以下のコードは自明でしょう。{{domxref("document.images")}} コンテナに対するループ処理を行って、適宜新たな canvas 要素を追加します。おそらく、DOM についてあまり詳しくない場合に注意したほうがよいことは、{{domxref("Node.insertBefore")}} メソッドを使用していることです。insertBefore() は、ある要素 (image) の前に新たな要素 (canvas 要素) を挿入したいときに使用する、親ノード (テーブルのセル) のメソッドです。

+ +
<html>
+ <body onload="draw();">
+     <table>
+      <tr>
+        <td><img src="https://mdn.mozillademos.org/files/5399/gallery_1.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5401/gallery_2.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5403/gallery_3.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5405/gallery_4.jpg"></td>
+      </tr>
+      <tr>
+        <td><img src="https://mdn.mozillademos.org/files/5407/gallery_5.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5409/gallery_6.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5411/gallery_7.jpg"></td>
+        <td><img src="https://mdn.mozillademos.org/files/5413/gallery_8.jpg"></td>
+      </tr>
+     </table>
+     <img id="frame" src="https://mdn.mozillademos.org/files/242/Canvas_picture_frame.png" width="132" height="150">
+ </body>
+</html>
+
+ +

こちらが、見栄えをよくするための CSS です:

+ +
body {
+  background: 0 -100px repeat-x url(https://mdn.mozillademos.org/files/5415/bg_gallery.png) #4F191A;
+  margin: 10px;
+}
+
+img {
+  display: none;
+}
+
+table {
+  margin: 0 auto;
+}
+
+td {
+  padding: 15px;
+}
+
+ +

額縁付き画像を描く JavaScript が、すべてを結びつけます:

+ +
function draw() {
+
+  // すべての画像に対するループ処理
+  for (var i=0;i<document.images.length;i++){
+
+    // 額縁の画像用の canvas は追加しない
+    if (document.images[i].getAttribute('id')!='frame'){
+
+      // canvas 要素を作成
+      canvas = document.createElement('canvas');
+      canvas.setAttribute('width',132);
+      canvas.setAttribute('height',150);
+
+      // 画像の前に挿入
+      document.images[i].parentNode.insertBefore(canvas,document.images[i]);
+
+      ctx = canvas.getContext('2d');
+
+      // canvas に画像を描く
+      ctx.drawImage(document.images[i],15,20);
+
+      // 額縁を追加
+      ctx.drawImage(document.getElementById('frame'),0,0);
+    }
+  }
+}
+ +

{{EmbedLiveSample("Art_gallery_example", 725, 400)}}

+ +

画像のサイズ変更の動作を制御する

+ +

先に述べたとおり、サイズを変更した画像は変更処理の影響で、不鮮明またはブロック状のアーティファクトが発生します。描画コンテキスト内で画像のサイズを変更する際に使用する画像スムージングアルゴリズムを制御するために、描画コンテキストの {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}} プロパティを使用できます。デフォルトではこれが true であり、画像のサイズを変更する際にスムージングを行います。以下のように、この機能は無効化できます:

+ +
ctx.mozImageSmoothingEnabled = false;
+ctx.webkitImageSmoothingEnabled = false;
+ctx.msImageSmoothingEnabled = false;
+ctx.imageSmoothingEnabled = false;
+
+ +
{{PreviousNext("Web/API/Canvas_API/Tutorial/Drawing_text", "Web/API/Canvas_API/Tutorial/Transformations")}}
diff --git a/files/ja/web/api/css_painting_api/guide/index.html b/files/ja/web/api/css_painting_api/guide/index.html new file mode 100644 index 0000000000..af90696aac --- /dev/null +++ b/files/ja/web/api/css_painting_api/guide/index.html @@ -0,0 +1,540 @@ +--- +title: CSS Painting APIを使用する +slug: Web/API/CSS_Painting_API/ガイド +tags: + - CSS + - CSS Paint API + - Canvas + - Houdini + - Learn +translation_of: Web/API/CSS_Painting_API/Guide +--- +

CSS Paint API を用いると開発者がプログラムで画像を定義できます。CSS の background-image, border-image, mask-image など CSS 画像を呼び出せる場所ならどこでも使用できるように設計されています。

+ +

CSS スタイルシートで使用される画像をプログラムで作成するには、いくつかのステップを踏む必要があります:

+ +
    +
  1. registerPaint() 関数を用いたペイント Worklet を定義します
  2. +
  3. その Worklet を登録します
  4. +
  5. {{cssxref('paint()','paint()')}} という CSS 関数を読み込みます
  6. +
+ +

これらの手順を詳しく説明するために、このヘッダーのようなハーフハイライトの背景を作成することから始めます:

+ +

Text reading 'My Cool Header' with a solid yellow background image block on the bottom left two thirds of the header

+ +

CSS paint worklet

+ +

外部スクリプトファイルでは、registerPaint() 関数を使用して CSS Paint worklet の名前をつけています。この関数には 2 つの引数が必要です。最初の引数はその Worklet の名前です — これは CSS で要素にスタイルを適用する際に paint() 関数のパラメーターとして渡されます。2 つ目の引数は、すべての魔法を行うクラスで、その中でコンテキストオプションと、イメージとなる 2 次元キャンバスに何を描画するかを定義します。

+ +
registerPaint('headerHighlight', class {
+
+  /*
+       アルファ透明度を許可するかどうかを定義します。既定では true にします。
+       false に設定した場合、すべてのキャンバスに
+       使用されている色は完全に不透明になります。
+    */
+  static get contextOptions() {
+           return { alpha: true };
+    }
+
+    /*
+        ctx は 2D の描画コンテキストで
+        HTML5 Canvas API のサブセットです。
+    */
+  paint(ctx) {
+        ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
+        ctx.fillRect(0, 15, 200, 20);     /* 順序: x, y, w, h */
+  }
+});
+ +

このクラスの例では、contextOptions() を用いて 1 つだけコンテキストオプションを定義しています。そこではアルファ透明度を許可するシンプルなオブジェクトを返しています。

+ +

それでは paint() 関数を用いてキャンバスに描画していきます。

+ +

paint() 関数は 3 つの引数を持てます。ここでは最初の引数だけ渡していて、それはレンダリングコンテキスト(後ほど詳しく説明します)といい、ふつう ctx という変数名で表されます。2D レンダリングコンテキストは HTML5 Canvas API のサブセットで、Houdini (PaintRenderingContext2Dと呼ばれる) で利用可能なバージョンはCanvas APIのほとんどすべての機能を含むサブセットですが、そのうち CanvasImageData, CanvasUserInterface, CanvasText, CanvasTextDrawingStyles の各 API は 除かれています

+ +

黄色の影をつくるために fillStylehsla(55, 90%, 60%, 1.0) と定義し、その色の矩形を作成するために fillRect() を呼び出します。fillRect() のパラメータは、順に x 軸原点、y 軸原点、幅、高さです。fillRect(0, 15, 200, 20) は、幅 200 単位、高さ 20 単位の矩形を、コンテンツボックスの左端から 0 単位、上端から 15 単位に作成します。

+ +

CSS の background-sizebackground-position プロパティを使用して、この背景画像のサイズを変更したり、再配置したりすることができますが、これは描画 Worklet で作成した黄色のボックスのデフォルトのサイズと配置です。

+ +

この例はシンプルなものにしてみました。より多くのオプションについては、canvas のドキュメントを参照してください。また、このチュートリアルの後半では、少し複雑さを追加しています。

+ +

描画 Worklet を使用する

+ +

描画 Worklet を使用するためには、addModule() を用いて登録し、HTML 内の目的の DOM ノードに適用される CSS セレクターのスタイルに含める必要があります。

+ +

Worklet を登録する

+ +

描画 Worklet とデザインは、上に示した外部スクリプトで行われました。この Worklet をメインスクリプトから登録する必要があります。

+ +
CSS.paintWorklet.addModule('nameOfPaintWorkletFile.js');
+ +

これは、メイン HTML 内の <script> またはドキュメントからリンクされた外部 JavaScript ファイル内の、描画 Worklet の addModule() メソッドを使用して行うことができます。

+ +

以下の例では、描画 Worklet は Github でホストしています。

+ +
+
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/01partOne/header-highlight.js');
+ +

CSSで描画 Worklet を参照する

+ +

登録された描画 Worklet ができたら、それをCSSで使用することができます。他の <image> タイプと同様に CSS の paint() 関数を使用し、 描画 Worklet の registerPaint() 関数でセットしたのと同じ文字列識別子を使用してください。

+ +
.fancy {
+  background-image: paint(headerHighlight);
+}
+ +

一緒につかう

+ +

そして、ページ上の任意の要素に fancy クラスを追加して、背景として黄色のボックスを追加することができます。

+ +
<h1 class="fancy">My Cool Header</h1>
+ +

以下の例は、CSS Painting API をサポートしているブラウザーでは上の画像のようになります。

+
+ +

{{EmbedLiveSample("paintapi", 120, 120)}}

+ +

ワークレットのスクリプトを弄ることはできませんが、背景画像のサイズと位置を変更するために、background-sizebackground-position を変更することができます。

+ +

PaintSize

+ +

上の例では、20×200 の単位のボックスを作成し、要素の上端から 15 単位を塗りつぶしました。これは要素の大きさに関係なく同じです。テキストが小さい場合、黄色のボックスは巨大なアンダーラインのように見えます。文字が大きい場合は、最初の 3 文字の上にバーがあるように見えるかもしれません。 背景画像が要素のサイズと相対的なものであればより良いでしょう — 要素の paintSize プロパティを使用して、背景画像が要素のボックスモデルのサイズに比例するようにすることができます。

+ +

The background is 50% of the height and 60% of the width of the element

+ +

上の画像では、背景は要素の大きさに比例しています。3 番目の例では、ブロックレベルの要素に width: 50%; を設定しているため、要素が狭くなり、その結果、背景画像が狭くなります。

+ +

これを行うためのコードは次のようになります:

+ +
registerPaint('headerHighlight', class {
+
+  static get contextOptions() {
+           return { alpha: true };
+  }
+
+    /*
+        ctx は 2D 描画コンテキスト
+        size は paintSize, 描画するボックスの高さ(height)と幅(width)を持つ
+    */
+
+  paint(ctx, size) {
+        ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
+        ctx.fillRect( 0, size.height / 3, size.width * 0.4, size.height * 0.6 );
+  }
+});
+ +

このコード例は、最初の例とは 2 つの違いがあります:

+ +
    +
  1. paint() の第 2 引数として描画サイズを使用しています。
  2. +
  3. 矩形の寸法と位置を、絶対値ではなく、要素ボックスのサイズに相対するように変更しました。
  4. +
+ +

paint() に第 2 引数を渡すことで、.width.height プロパティを使って要素の幅と高さにアクセスすることができます。

+ +

私たちのヘッダーは、サイズに応じてハイライトが変化するようになりました。

+ + + +

Worklet のスクリプトをいじることはできませんが、要素の font-sizewidth を変更して背景画像のサイズを変更できます。

+ +

以下の例は、CSS Painting API をサポートしているブラウザーでは上の画像のようになります。

+ +

{{EmbedLiveSample("example2", 300, 300)}}

+ +

カスタムプロパティ

+ +

Worklet は、要素のサイズにアクセスするだけでなく、CSS のカスタムプロパティや通常のCSS プロパティにもアクセスすることができます。

+ +
registerPaint('cssPaintFunctionName', class {
+     static get inputProperties() { return ['PropertyName1', '--customPropertyName2']; }
+     static get inputArguments() { return ['<color>']; }
+     static get contextOptions() { return {alpha: true}; }
+
+     paint(drawingContext, elementSize, styleMap) {
+         // 描画コードはここに書く
+});
+
+ +

paint() 関数の 3 つの引数には、描画コンテキスト、描画サイズ、プロパティが含まれます。プロパティにアクセスできるようにするために、静的な inputProperties() メソッドをインクルードしています。これは、通常のプロパティやカスタムプロパティを含む CSS プロパティへの動的なアクセスを提供し、プロパティ名の array を返します。最後にinputArguments について見ていきます。

+ +

+ +
+

3 種類の色と 3 種類の幅の間で周回する背景画像を使って、項目一覧を作成してみましょう。

+ +

The width and color of the background image changes based on the custom properties

+ +

この CSS では、--boxColor--widthSubtractor のカスタム プロパティを使用して、作成した背景ボックスの色と幅の減算器を指定しています。

+ + + + + +
li {
+   background-image: paint(boxbg);
+   --boxColor: hsla(55, 90%, 60%, 1.0);
+}
+
+li:nth-of-type(3n) {
+   --boxColor: hsla(155, 90%, 60%, 1.0);
+   --widthSubtractor: 20;
+}
+
+li:nth-of-type(3n+1) {
+   --boxColor: hsla(255, 90%, 60%, 1.0);
+   --widthSubtractor: 40;
+}
+
+ +

Worklet ではこれらのカスタムプロパティを参照することができます。

+ +
registerPaint('boxbg', class {
+
+  static get contextOptions() { return {alpha: true}; }
+
+  /*
+     この関数を使用して、要素に対して定義されているカスタムプロパティ (または 'height' のような
+     通常のプロパティ) を取得します。指定された配列で返します。
+  */
+  static get inputProperties() { return ['--boxColor', '--widthSubtractor']; }
+
+  paint(ctx, size, props) {
+    /*
+       ctx -> 描画コンテキスト
+       size -> paintSize: 幅と高さ
+       props -> properties: get() メソッド
+    */
+
+    ctx.fillStyle = props.get('--boxColor');
+    ctx.fillRect(0, size.height/3, size.width*0.4 - props.get('--widthSubtractor'), size.height*0.6);
+  }
+});
+ +

registerPaint() に渡すクラスの inputProperties() メソッドを使用して、boxbg が適用されている要素に設定されている 2 つのカスタムプロパティの値を取得しました。そしてそれらを paint() 関数内で使用します。inputProperties() メソッドは、カスタムプロパティだけでなく、要素に影響するすべてのプロパティを返すことができます。

+ +

<script> 内で Worklet を登録するには以下のようにします:

+ +
+
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklet/boxbg.js');
+
+ +

{{EmbedLiveSample("example3", 300, 300)}}

+ +

Worklet のスクリプトをいじることはできませんが、カスタムプロパティの値を変更して背景画像の色や幅を変更することはできます。

+ +

より複雑にしてみる

+ +

これまでの例は、例えば装飾的に生成されたコンテンツ::before で配置したり、background: linear-gradient(yellow, yellow) 0 15px / 200px 20px no-repeat; とするなど、既存のCSSプロパティを使用する方法で再現することができるので、あまり刺激的には見えないかもしれません。CSS Painting API が面白くて強力なのは、変数を渡して自動的にサイズを変更する複雑な画像を作成できることです。

+ +

それではもっと複雑な例を見てみましょう。

+ +
registerPaint('headerHighlight', class {
+  static get inputProperties() { return ['--highColour']; }
+  static get contextOptions() { return {alpha: true}; }
+
+  paint(ctx, size, props) {
+
+		/* どの場所からハイライトを始めるか、寸法をセットする */
+		const x = 0;
+		const y = size.height * 0.3;
+		const blockWidth = size.width * 0.33;
+		const highlightHeight = size.height * 0.85;
+        const color = props.get('--highColour');
+
+		ctx.fillStyle = color;
+
+		ctx.beginPath();
+		ctx.moveTo( x, y );
+		ctx.lineTo( blockWidth, y );
+		ctx.lineTo( blockWidth + highlightHeight, highlightHeight );
+		ctx.lineTo( x, highlightHeight );
+		ctx.lineTo( x, y );
+		ctx.closePath();
+		ctx.fill();
+
+		/* 破線を作成 */
+		for (let i = 0; i < 4; i++) {
+			let start = i * 2;
+			ctx.beginPath();
+			ctx.moveTo( (blockWidth) + (start * 10) + 10, y );
+			ctx.lineTo( (blockWidth) + (start * 10) + 20, y );
+			ctx.lineTo( (blockWidth) + (start * 10) + 20 + (highlightHeight), highlightHeight );
+			ctx.lineTo( (blockWidth) + (start * 10) + 10 + (highlightHeight), highlightHeight );
+			ctx.lineTo( (blockWidth) + (start * 10) + 10, y );
+			ctx.closePath();
+			ctx.fill();
+		}
+  } // paint
+});
+ +
+

ここで作られる画像を背景とする小さな HTML を用意します:

+ +
<h1 class="fancy">Largest Header</h1>
+<h3 class="fancy">Medium size header</h3>
+<h6 class="fancy">Smallest Header</h6>
+ +

それぞれのヘッダーは、それぞれ異なった値の --highColor カスタムプロパティを持つことができます。

+ +
.fancy {
+  background-image: paint(headerHighlight);
+}
+h1 { --highColour: hsla(155, 90%, 60%, 0.7); }
+h3 { --highColour: hsla(255, 90%, 60%, 0.5); }
+h6 { --highColour: hsla(355, 90%, 60%, 0.3); }
+ +

そして、Worklet を登録します

+ +
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/03partThree/header-highlight.js');
+ +

{{EmbedLiveSample("example4", 300, 300)}}

+ +

この Worklet そのものを編集することはできませんが、CSS や HTML をいじることはできます。ヘッダーの floatclear を試してみるのはどうでしょう?

+ +

上記の背景画像を CSS paint API を使わずに作ってみるのもいいかもしれません。これは可能ですが、作成したい色ごとに異なる、かなり複雑な線形グラデーションを宣言しなければなりません。CSS paint API を使えば、1 つの Worklet を再利用することができ、その場合でも異なる色を渡すことができます。

+
+ +

パラメーターを渡す

+ +

CSS Paint API を使用すると、カスタムプロパティや通常のプロパティにアクセスできるだけでなく、カスタム引数を paint() 関数に渡すこともできます。

+ +

CSS で関数を呼び出すときに、これらの引数を追加することができます。例えばある時、背景を塗りつぶすのではなく、背景をなぞるようにしたいとしましょう — そのために追加の引数を加えておきましょう。

+ +
li {
+	background-image: paint(hollowHighlights, stroke);
+}
+
+ +

これで、registerPaint() に渡されるクラスの inputArguments() メソッドを使用して、paint() 関数に追加したカスタム引数にアクセスできるようになりました。

+ +
static get inputArguments() { return ['*']; }
+
+ +

実際にアクセスするにはこうします。

+ +
paint(ctx, size, props, args) {
+
+	// カスタム引数を使う
+	const hasStroke = args[0].toString();
+
+	// stroke 引数が 'stroke' の場合は塗りつぶしはしません
+	if (hasStroke === 'stroke') {
+		ctx.fillStyle = 'transparent';
+		ctx.strokeStyle = colour;
+	}
+	...
+}
+ +

2 つ以上の引数も渡せます。

+ +
li {
+	background-image: paint(hollowHighlights, stroke, 10px);
+}
+
+ +

また、特定のタイプの引数を指定することもできます。引数の値をリストで get する際に、特に <length> で単位を指定します。

+ +
static get inputArguments() { return ['*', '<length>']; }
+ +

この場合は <length> 属性を要求しました。返される配列の最初の要素は CSSUnparsedValue です。2 番目の要素は CSSStyleValue です。

+ +

カスタム引数がユニットなどの CSS 値である場合、registerPaint() 関数で取得する際にvalue type キーワードを使用することで、Typed OM CSSStyleValue クラス (およびサブクラス) を呼び出すことができます。

+ +

それではストロークの幅を何ピクセルにするか、2 番目の引数を追加してみましょう:

+ +
li {
+	background-image: paint(hollowHighlights, stroke, 10px);
+}
+
+ +

引数の値をリストで get する際に、<length> 単位を要求します。

+ +
static get inputArguments() { return ['*', '<length>']; }
+
+ +

これで型と値のプロパティにアクセスできるようになりました。つまり箱から出してすぐにピクセル数と数値型を取得できるということです。(確かに ctx.lineWidth は、長さの単位を持つ値ではなく float を値として受け取りますが、これは例ですから...)

+ +
paint(ctx, size, props, args) {
+
+		const strokeWidth = args[1];
+
+		if (strokeWidth.unit === 'px') {
+			ctx.lineWidth = strokeWidth.value;
+		} else {
+			ctx.lineWidth = 1.0;
+		}
+
+	...
+}
+
+ +

この Worklet のさまざまな部分を制御するためにカスタムプロパティを使用することと、ここに記載されている引数との違いに注目する価値があります。カスタムプロパティ (および実際にはスタイルマップ上のすべてのプロパティ) はグローバルなもので、CSS (および JS) 内の他の場所で使用することができます。

+ +

例えば paint() 関数内で色を設定するために --mainColor を用意するのは便利ですが、これは CSS の他の場所で色を設定するのにも使えます。これを paint のためだけに特別に変更したい場合は、かなり難しいかもしれません。そこで便利なのがカスタム引数です。もう一つの考え方としては、引数は実際に描画するものを制御するために設定され、プロパティはスタイルを制御するために設定されるということです。

+ +

The list items have a background image that is either pink, purple or green, with different stroke widths, and the green one being filled.

+ +

これでこの API の本当のメリットが見えてきました。カスタムプロパティと paint() 関数の引数の両方を使って CSS から無数の描画パラメータを制御できるようになれば、再利用可能で制御性の高いスタイリング関数を作り始めることができます。

+ +
registerPaint('hollowHighlights', class {
+
+  static get inputProperties() { return ['--boxColor']; }
+  // `paint` 関数に渡されるカスタム引数
+  static get inputArguments() { return ['*','']; }
+
+  static get contextOptions() { return {alpha: true}; }
+
+  paint(ctx, size, props, args) {
+    // ctx   -> 描画コンテキスト
+    // size  -> 描画したいボックスの大きさ
+    // props -> 要素に存在するカスタププロパティのリスト
+	// args  -> cssから paint() 関数を呼ばれた際のカスタム引数のリスト
+
+		// どの場所からハイライトを始めるか、寸法
+		const x = 0;
+		const y = size.height * 0.3;
+		const blockWidth = size.width * 0.33;
+		const blockHeight = size.height * 0.85;
+
+		// CSS から paint() 関数に渡された値
+		const colour = props.get( '--boxColor' );
+		const strokeType = args[0].toString();
+		const strokeWidth = parseInt(args[1]);
+
+
+		// 線幅を設定する
+		if ( strokeWidth ) {
+			ctx.lineWidth = strokeWidth;
+		} else {
+			ctx.lineWidth = 1.0;
+		}
+		// 塗りつぶしタイプを設定する
+		if ( strokeType === 'stroke' ) {
+			ctx.fillStyle = 'transparent';
+			ctx.strokeStyle = colour;
+		} else if ( strokeType === 'filled' ) {
+			ctx.fillStyle = colour;
+			ctx.strokeStyle = colour;
+		} else {
+			ctx.fillStyle = 'none';
+			ctx.strokeStyle = 'none';
+		}
+
+		// 四角
+		ctx.beginPath();
+		ctx.moveTo( x, y );
+		ctx.lineTo( blockWidth, y );
+		ctx.lineTo( blockWidth + blockHeight, blockHeight );
+		ctx.lineTo( x, blockHeight );
+		ctx.lineTo( x, y );
+		ctx.closePath();
+		ctx.fill();
+		ctx.stroke();
+		// 破線
+		for (let i = 0; i < 4; i++) {
+			let start = i * 2;
+			ctx.beginPath();
+			ctx.moveTo( blockWidth + (start * 10) + 10, y);
+			ctx.lineTo( blockWidth + (start * 10) + 20, y);
+			ctx.lineTo( blockWidth + (start * 10) + 20 + blockHeight, blockHeight);
+			ctx.lineTo( blockWidth + (start * 10) + 10 + blockHeight, blockHeight);
+			ctx.lineTo( blockWidth + (start * 10) + 10, y);
+			ctx.closePath();
+			ctx.fill();
+			ctx.stroke();
+		}
+
+  } // paint
+});
+
+ +

私たちは、異なる色、線幅を設定し、背景画像が塗りつぶされるべきか、中空になるべきかを選択することができます:

+ +
+
li {
+   --boxColor: hsla(155, 90%, 60%, 0.5);
+   background-image: paint(hollowHighlights, stroke, 5px);
+}
+
+li:nth-of-type(3n) {
+   --boxColor: hsla(255, 90%, 60%, 0.5);
+   background-image: paint(hollowHighlights, filled,  3px);
+}
+
+li:nth-of-type(3n+1) {
+   --boxColor: hsla(355, 90%, 60%, 0.5);
+   background-image: paint(hollowHighlights, stroke, 1px);
+}
+ + + +

私たちの作った Worklet を登録するには以下のようにします:

+ +
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/hollow.js');
+
+ +

{{EmbedLiveSample("example5", 300, 300)}}

+ +

関連情報

+ + diff --git "a/files/ja/web/api/css_painting_api/\343\202\254\343\202\244\343\203\211/index.html" "b/files/ja/web/api/css_painting_api/\343\202\254\343\202\244\343\203\211/index.html" deleted file mode 100644 index af90696aac..0000000000 --- "a/files/ja/web/api/css_painting_api/\343\202\254\343\202\244\343\203\211/index.html" +++ /dev/null @@ -1,540 +0,0 @@ ---- -title: CSS Painting APIを使用する -slug: Web/API/CSS_Painting_API/ガイド -tags: - - CSS - - CSS Paint API - - Canvas - - Houdini - - Learn -translation_of: Web/API/CSS_Painting_API/Guide ---- -

CSS Paint API を用いると開発者がプログラムで画像を定義できます。CSS の background-image, border-image, mask-image など CSS 画像を呼び出せる場所ならどこでも使用できるように設計されています。

- -

CSS スタイルシートで使用される画像をプログラムで作成するには、いくつかのステップを踏む必要があります:

- -
    -
  1. registerPaint() 関数を用いたペイント Worklet を定義します
  2. -
  3. その Worklet を登録します
  4. -
  5. {{cssxref('paint()','paint()')}} という CSS 関数を読み込みます
  6. -
- -

これらの手順を詳しく説明するために、このヘッダーのようなハーフハイライトの背景を作成することから始めます:

- -

Text reading 'My Cool Header' with a solid yellow background image block on the bottom left two thirds of the header

- -

CSS paint worklet

- -

外部スクリプトファイルでは、registerPaint() 関数を使用して CSS Paint worklet の名前をつけています。この関数には 2 つの引数が必要です。最初の引数はその Worklet の名前です — これは CSS で要素にスタイルを適用する際に paint() 関数のパラメーターとして渡されます。2 つ目の引数は、すべての魔法を行うクラスで、その中でコンテキストオプションと、イメージとなる 2 次元キャンバスに何を描画するかを定義します。

- -
registerPaint('headerHighlight', class {
-
-  /*
-       アルファ透明度を許可するかどうかを定義します。既定では true にします。
-       false に設定した場合、すべてのキャンバスに
-       使用されている色は完全に不透明になります。
-    */
-  static get contextOptions() {
-           return { alpha: true };
-    }
-
-    /*
-        ctx は 2D の描画コンテキストで
-        HTML5 Canvas API のサブセットです。
-    */
-  paint(ctx) {
-        ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
-        ctx.fillRect(0, 15, 200, 20);     /* 順序: x, y, w, h */
-  }
-});
- -

このクラスの例では、contextOptions() を用いて 1 つだけコンテキストオプションを定義しています。そこではアルファ透明度を許可するシンプルなオブジェクトを返しています。

- -

それでは paint() 関数を用いてキャンバスに描画していきます。

- -

paint() 関数は 3 つの引数を持てます。ここでは最初の引数だけ渡していて、それはレンダリングコンテキスト(後ほど詳しく説明します)といい、ふつう ctx という変数名で表されます。2D レンダリングコンテキストは HTML5 Canvas API のサブセットで、Houdini (PaintRenderingContext2Dと呼ばれる) で利用可能なバージョンはCanvas APIのほとんどすべての機能を含むサブセットですが、そのうち CanvasImageData, CanvasUserInterface, CanvasText, CanvasTextDrawingStyles の各 API は 除かれています

- -

黄色の影をつくるために fillStylehsla(55, 90%, 60%, 1.0) と定義し、その色の矩形を作成するために fillRect() を呼び出します。fillRect() のパラメータは、順に x 軸原点、y 軸原点、幅、高さです。fillRect(0, 15, 200, 20) は、幅 200 単位、高さ 20 単位の矩形を、コンテンツボックスの左端から 0 単位、上端から 15 単位に作成します。

- -

CSS の background-sizebackground-position プロパティを使用して、この背景画像のサイズを変更したり、再配置したりすることができますが、これは描画 Worklet で作成した黄色のボックスのデフォルトのサイズと配置です。

- -

この例はシンプルなものにしてみました。より多くのオプションについては、canvas のドキュメントを参照してください。また、このチュートリアルの後半では、少し複雑さを追加しています。

- -

描画 Worklet を使用する

- -

描画 Worklet を使用するためには、addModule() を用いて登録し、HTML 内の目的の DOM ノードに適用される CSS セレクターのスタイルに含める必要があります。

- -

Worklet を登録する

- -

描画 Worklet とデザインは、上に示した外部スクリプトで行われました。この Worklet をメインスクリプトから登録する必要があります。

- -
CSS.paintWorklet.addModule('nameOfPaintWorkletFile.js');
- -

これは、メイン HTML 内の <script> またはドキュメントからリンクされた外部 JavaScript ファイル内の、描画 Worklet の addModule() メソッドを使用して行うことができます。

- -

以下の例では、描画 Worklet は Github でホストしています。

- -
-
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/01partOne/header-highlight.js');
- -

CSSで描画 Worklet を参照する

- -

登録された描画 Worklet ができたら、それをCSSで使用することができます。他の <image> タイプと同様に CSS の paint() 関数を使用し、 描画 Worklet の registerPaint() 関数でセットしたのと同じ文字列識別子を使用してください。

- -
.fancy {
-  background-image: paint(headerHighlight);
-}
- -

一緒につかう

- -

そして、ページ上の任意の要素に fancy クラスを追加して、背景として黄色のボックスを追加することができます。

- -
<h1 class="fancy">My Cool Header</h1>
- -

以下の例は、CSS Painting API をサポートしているブラウザーでは上の画像のようになります。

-
- -

{{EmbedLiveSample("paintapi", 120, 120)}}

- -

ワークレットのスクリプトを弄ることはできませんが、背景画像のサイズと位置を変更するために、background-sizebackground-position を変更することができます。

- -

PaintSize

- -

上の例では、20×200 の単位のボックスを作成し、要素の上端から 15 単位を塗りつぶしました。これは要素の大きさに関係なく同じです。テキストが小さい場合、黄色のボックスは巨大なアンダーラインのように見えます。文字が大きい場合は、最初の 3 文字の上にバーがあるように見えるかもしれません。 背景画像が要素のサイズと相対的なものであればより良いでしょう — 要素の paintSize プロパティを使用して、背景画像が要素のボックスモデルのサイズに比例するようにすることができます。

- -

The background is 50% of the height and 60% of the width of the element

- -

上の画像では、背景は要素の大きさに比例しています。3 番目の例では、ブロックレベルの要素に width: 50%; を設定しているため、要素が狭くなり、その結果、背景画像が狭くなります。

- -

これを行うためのコードは次のようになります:

- -
registerPaint('headerHighlight', class {
-
-  static get contextOptions() {
-           return { alpha: true };
-  }
-
-    /*
-        ctx は 2D 描画コンテキスト
-        size は paintSize, 描画するボックスの高さ(height)と幅(width)を持つ
-    */
-
-  paint(ctx, size) {
-        ctx.fillStyle = 'hsla(55, 90%, 60%, 1.0)';
-        ctx.fillRect( 0, size.height / 3, size.width * 0.4, size.height * 0.6 );
-  }
-});
- -

このコード例は、最初の例とは 2 つの違いがあります:

- -
    -
  1. paint() の第 2 引数として描画サイズを使用しています。
  2. -
  3. 矩形の寸法と位置を、絶対値ではなく、要素ボックスのサイズに相対するように変更しました。
  4. -
- -

paint() に第 2 引数を渡すことで、.width.height プロパティを使って要素の幅と高さにアクセスすることができます。

- -

私たちのヘッダーは、サイズに応じてハイライトが変化するようになりました。

- - - -

Worklet のスクリプトをいじることはできませんが、要素の font-sizewidth を変更して背景画像のサイズを変更できます。

- -

以下の例は、CSS Painting API をサポートしているブラウザーでは上の画像のようになります。

- -

{{EmbedLiveSample("example2", 300, 300)}}

- -

カスタムプロパティ

- -

Worklet は、要素のサイズにアクセスするだけでなく、CSS のカスタムプロパティや通常のCSS プロパティにもアクセスすることができます。

- -
registerPaint('cssPaintFunctionName', class {
-     static get inputProperties() { return ['PropertyName1', '--customPropertyName2']; }
-     static get inputArguments() { return ['<color>']; }
-     static get contextOptions() { return {alpha: true}; }
-
-     paint(drawingContext, elementSize, styleMap) {
-         // 描画コードはここに書く
-});
-
- -

paint() 関数の 3 つの引数には、描画コンテキスト、描画サイズ、プロパティが含まれます。プロパティにアクセスできるようにするために、静的な inputProperties() メソッドをインクルードしています。これは、通常のプロパティやカスタムプロパティを含む CSS プロパティへの動的なアクセスを提供し、プロパティ名の array を返します。最後にinputArguments について見ていきます。

- -

- -
-

3 種類の色と 3 種類の幅の間で周回する背景画像を使って、項目一覧を作成してみましょう。

- -

The width and color of the background image changes based on the custom properties

- -

この CSS では、--boxColor--widthSubtractor のカスタム プロパティを使用して、作成した背景ボックスの色と幅の減算器を指定しています。

- - - - - -
li {
-   background-image: paint(boxbg);
-   --boxColor: hsla(55, 90%, 60%, 1.0);
-}
-
-li:nth-of-type(3n) {
-   --boxColor: hsla(155, 90%, 60%, 1.0);
-   --widthSubtractor: 20;
-}
-
-li:nth-of-type(3n+1) {
-   --boxColor: hsla(255, 90%, 60%, 1.0);
-   --widthSubtractor: 40;
-}
-
- -

Worklet ではこれらのカスタムプロパティを参照することができます。

- -
registerPaint('boxbg', class {
-
-  static get contextOptions() { return {alpha: true}; }
-
-  /*
-     この関数を使用して、要素に対して定義されているカスタムプロパティ (または 'height' のような
-     通常のプロパティ) を取得します。指定された配列で返します。
-  */
-  static get inputProperties() { return ['--boxColor', '--widthSubtractor']; }
-
-  paint(ctx, size, props) {
-    /*
-       ctx -> 描画コンテキスト
-       size -> paintSize: 幅と高さ
-       props -> properties: get() メソッド
-    */
-
-    ctx.fillStyle = props.get('--boxColor');
-    ctx.fillRect(0, size.height/3, size.width*0.4 - props.get('--widthSubtractor'), size.height*0.6);
-  }
-});
- -

registerPaint() に渡すクラスの inputProperties() メソッドを使用して、boxbg が適用されている要素に設定されている 2 つのカスタムプロパティの値を取得しました。そしてそれらを paint() 関数内で使用します。inputProperties() メソッドは、カスタムプロパティだけでなく、要素に影響するすべてのプロパティを返すことができます。

- -

<script> 内で Worklet を登録するには以下のようにします:

- -
-
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklet/boxbg.js');
-
- -

{{EmbedLiveSample("example3", 300, 300)}}

- -

Worklet のスクリプトをいじることはできませんが、カスタムプロパティの値を変更して背景画像の色や幅を変更することはできます。

- -

より複雑にしてみる

- -

これまでの例は、例えば装飾的に生成されたコンテンツ::before で配置したり、background: linear-gradient(yellow, yellow) 0 15px / 200px 20px no-repeat; とするなど、既存のCSSプロパティを使用する方法で再現することができるので、あまり刺激的には見えないかもしれません。CSS Painting API が面白くて強力なのは、変数を渡して自動的にサイズを変更する複雑な画像を作成できることです。

- -

それではもっと複雑な例を見てみましょう。

- -
registerPaint('headerHighlight', class {
-  static get inputProperties() { return ['--highColour']; }
-  static get contextOptions() { return {alpha: true}; }
-
-  paint(ctx, size, props) {
-
-		/* どの場所からハイライトを始めるか、寸法をセットする */
-		const x = 0;
-		const y = size.height * 0.3;
-		const blockWidth = size.width * 0.33;
-		const highlightHeight = size.height * 0.85;
-        const color = props.get('--highColour');
-
-		ctx.fillStyle = color;
-
-		ctx.beginPath();
-		ctx.moveTo( x, y );
-		ctx.lineTo( blockWidth, y );
-		ctx.lineTo( blockWidth + highlightHeight, highlightHeight );
-		ctx.lineTo( x, highlightHeight );
-		ctx.lineTo( x, y );
-		ctx.closePath();
-		ctx.fill();
-
-		/* 破線を作成 */
-		for (let i = 0; i < 4; i++) {
-			let start = i * 2;
-			ctx.beginPath();
-			ctx.moveTo( (blockWidth) + (start * 10) + 10, y );
-			ctx.lineTo( (blockWidth) + (start * 10) + 20, y );
-			ctx.lineTo( (blockWidth) + (start * 10) + 20 + (highlightHeight), highlightHeight );
-			ctx.lineTo( (blockWidth) + (start * 10) + 10 + (highlightHeight), highlightHeight );
-			ctx.lineTo( (blockWidth) + (start * 10) + 10, y );
-			ctx.closePath();
-			ctx.fill();
-		}
-  } // paint
-});
- -
-

ここで作られる画像を背景とする小さな HTML を用意します:

- -
<h1 class="fancy">Largest Header</h1>
-<h3 class="fancy">Medium size header</h3>
-<h6 class="fancy">Smallest Header</h6>
- -

それぞれのヘッダーは、それぞれ異なった値の --highColor カスタムプロパティを持つことができます。

- -
.fancy {
-  background-image: paint(headerHighlight);
-}
-h1 { --highColour: hsla(155, 90%, 60%, 0.7); }
-h3 { --highColour: hsla(255, 90%, 60%, 0.5); }
-h6 { --highColour: hsla(355, 90%, 60%, 0.3); }
- -

そして、Worklet を登録します

- -
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/03partThree/header-highlight.js');
- -

{{EmbedLiveSample("example4", 300, 300)}}

- -

この Worklet そのものを編集することはできませんが、CSS や HTML をいじることはできます。ヘッダーの floatclear を試してみるのはどうでしょう?

- -

上記の背景画像を CSS paint API を使わずに作ってみるのもいいかもしれません。これは可能ですが、作成したい色ごとに異なる、かなり複雑な線形グラデーションを宣言しなければなりません。CSS paint API を使えば、1 つの Worklet を再利用することができ、その場合でも異なる色を渡すことができます。

-
- -

パラメーターを渡す

- -

CSS Paint API を使用すると、カスタムプロパティや通常のプロパティにアクセスできるだけでなく、カスタム引数を paint() 関数に渡すこともできます。

- -

CSS で関数を呼び出すときに、これらの引数を追加することができます。例えばある時、背景を塗りつぶすのではなく、背景をなぞるようにしたいとしましょう — そのために追加の引数を加えておきましょう。

- -
li {
-	background-image: paint(hollowHighlights, stroke);
-}
-
- -

これで、registerPaint() に渡されるクラスの inputArguments() メソッドを使用して、paint() 関数に追加したカスタム引数にアクセスできるようになりました。

- -
static get inputArguments() { return ['*']; }
-
- -

実際にアクセスするにはこうします。

- -
paint(ctx, size, props, args) {
-
-	// カスタム引数を使う
-	const hasStroke = args[0].toString();
-
-	// stroke 引数が 'stroke' の場合は塗りつぶしはしません
-	if (hasStroke === 'stroke') {
-		ctx.fillStyle = 'transparent';
-		ctx.strokeStyle = colour;
-	}
-	...
-}
- -

2 つ以上の引数も渡せます。

- -
li {
-	background-image: paint(hollowHighlights, stroke, 10px);
-}
-
- -

また、特定のタイプの引数を指定することもできます。引数の値をリストで get する際に、特に <length> で単位を指定します。

- -
static get inputArguments() { return ['*', '<length>']; }
- -

この場合は <length> 属性を要求しました。返される配列の最初の要素は CSSUnparsedValue です。2 番目の要素は CSSStyleValue です。

- -

カスタム引数がユニットなどの CSS 値である場合、registerPaint() 関数で取得する際にvalue type キーワードを使用することで、Typed OM CSSStyleValue クラス (およびサブクラス) を呼び出すことができます。

- -

それではストロークの幅を何ピクセルにするか、2 番目の引数を追加してみましょう:

- -
li {
-	background-image: paint(hollowHighlights, stroke, 10px);
-}
-
- -

引数の値をリストで get する際に、<length> 単位を要求します。

- -
static get inputArguments() { return ['*', '<length>']; }
-
- -

これで型と値のプロパティにアクセスできるようになりました。つまり箱から出してすぐにピクセル数と数値型を取得できるということです。(確かに ctx.lineWidth は、長さの単位を持つ値ではなく float を値として受け取りますが、これは例ですから...)

- -
paint(ctx, size, props, args) {
-
-		const strokeWidth = args[1];
-
-		if (strokeWidth.unit === 'px') {
-			ctx.lineWidth = strokeWidth.value;
-		} else {
-			ctx.lineWidth = 1.0;
-		}
-
-	...
-}
-
- -

この Worklet のさまざまな部分を制御するためにカスタムプロパティを使用することと、ここに記載されている引数との違いに注目する価値があります。カスタムプロパティ (および実際にはスタイルマップ上のすべてのプロパティ) はグローバルなもので、CSS (および JS) 内の他の場所で使用することができます。

- -

例えば paint() 関数内で色を設定するために --mainColor を用意するのは便利ですが、これは CSS の他の場所で色を設定するのにも使えます。これを paint のためだけに特別に変更したい場合は、かなり難しいかもしれません。そこで便利なのがカスタム引数です。もう一つの考え方としては、引数は実際に描画するものを制御するために設定され、プロパティはスタイルを制御するために設定されるということです。

- -

The list items have a background image that is either pink, purple or green, with different stroke widths, and the green one being filled.

- -

これでこの API の本当のメリットが見えてきました。カスタムプロパティと paint() 関数の引数の両方を使って CSS から無数の描画パラメータを制御できるようになれば、再利用可能で制御性の高いスタイリング関数を作り始めることができます。

- -
registerPaint('hollowHighlights', class {
-
-  static get inputProperties() { return ['--boxColor']; }
-  // `paint` 関数に渡されるカスタム引数
-  static get inputArguments() { return ['*','']; }
-
-  static get contextOptions() { return {alpha: true}; }
-
-  paint(ctx, size, props, args) {
-    // ctx   -> 描画コンテキスト
-    // size  -> 描画したいボックスの大きさ
-    // props -> 要素に存在するカスタププロパティのリスト
-	// args  -> cssから paint() 関数を呼ばれた際のカスタム引数のリスト
-
-		// どの場所からハイライトを始めるか、寸法
-		const x = 0;
-		const y = size.height * 0.3;
-		const blockWidth = size.width * 0.33;
-		const blockHeight = size.height * 0.85;
-
-		// CSS から paint() 関数に渡された値
-		const colour = props.get( '--boxColor' );
-		const strokeType = args[0].toString();
-		const strokeWidth = parseInt(args[1]);
-
-
-		// 線幅を設定する
-		if ( strokeWidth ) {
-			ctx.lineWidth = strokeWidth;
-		} else {
-			ctx.lineWidth = 1.0;
-		}
-		// 塗りつぶしタイプを設定する
-		if ( strokeType === 'stroke' ) {
-			ctx.fillStyle = 'transparent';
-			ctx.strokeStyle = colour;
-		} else if ( strokeType === 'filled' ) {
-			ctx.fillStyle = colour;
-			ctx.strokeStyle = colour;
-		} else {
-			ctx.fillStyle = 'none';
-			ctx.strokeStyle = 'none';
-		}
-
-		// 四角
-		ctx.beginPath();
-		ctx.moveTo( x, y );
-		ctx.lineTo( blockWidth, y );
-		ctx.lineTo( blockWidth + blockHeight, blockHeight );
-		ctx.lineTo( x, blockHeight );
-		ctx.lineTo( x, y );
-		ctx.closePath();
-		ctx.fill();
-		ctx.stroke();
-		// 破線
-		for (let i = 0; i < 4; i++) {
-			let start = i * 2;
-			ctx.beginPath();
-			ctx.moveTo( blockWidth + (start * 10) + 10, y);
-			ctx.lineTo( blockWidth + (start * 10) + 20, y);
-			ctx.lineTo( blockWidth + (start * 10) + 20 + blockHeight, blockHeight);
-			ctx.lineTo( blockWidth + (start * 10) + 10 + blockHeight, blockHeight);
-			ctx.lineTo( blockWidth + (start * 10) + 10, y);
-			ctx.closePath();
-			ctx.fill();
-			ctx.stroke();
-		}
-
-  } // paint
-});
-
- -

私たちは、異なる色、線幅を設定し、背景画像が塗りつぶされるべきか、中空になるべきかを選択することができます:

- -
-
li {
-   --boxColor: hsla(155, 90%, 60%, 0.5);
-   background-image: paint(hollowHighlights, stroke, 5px);
-}
-
-li:nth-of-type(3n) {
-   --boxColor: hsla(255, 90%, 60%, 0.5);
-   background-image: paint(hollowHighlights, filled,  3px);
-}
-
-li:nth-of-type(3n+1) {
-   --boxColor: hsla(355, 90%, 60%, 0.5);
-   background-image: paint(hollowHighlights, stroke, 1px);
-}
- - - -

私たちの作った Worklet を登録するには以下のようにします:

- -
CSS.paintWorklet.addModule('https://mdn.github.io/houdini-examples/cssPaint/intro/worklets/hollow.js');
-
- -

{{EmbedLiveSample("example5", 300, 300)}}

- -

関連情報

- - diff --git a/files/ja/web/api/cssmatrix/index.html b/files/ja/web/api/cssmatrix/index.html deleted file mode 100644 index 756a3c4cb2..0000000000 --- a/files/ja/web/api/cssmatrix/index.html +++ /dev/null @@ -1,94 +0,0 @@ ---- -title: CSSMatrix -slug: Web/API/CSSMatrix -tags: - - API - - NeedsBrowserCompatibility - - Reference -translation_of: Web/API/DOMMatrix -translation_of_original: Web/API/CSSMatrix ---- -
{{APIRef("CSSOM")}}{{Non-standard_header}}
- -

CSSMatrix は、2D または 3D の変形が適用できる同次の 4x4 行列を表しています。このクラスは、ある時点で CSS Transitions モジュールレベル 3 の一部ということになっていましたが、現在のワーキングドラフトで存在しません。代わりに DOMMatrix を使用してください。

- -

仕様

- - - - - - - - - - - - - - - - -
仕様ステータスコメント
{{SpecName('Compat', '#webkitcssmatrix-interface', 'WebKitCSSMatrix')}}{{Spec2('Compat')}}WebKit プレフィックス付きバージョン、WebKitCSSMatrix の初期の標準化。
- -

ブラウザー互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
機能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本サポート{{CompatUnknown}}{{CompatUnknown}}10[1]{{CompatUnknown}}{{CompatVersionUnknown}}[2]
-
- -
- - - - - - - - - - - - - - - - - - - -
機能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本サポート{{CompatUnknown}}{{CompatUnknown}}11[1]{{CompatUnknown}}{{CompatVersionUnknown}}[2]
-
- -

[1] Internet Explorer は、MSCSSMatrix としてこの API を実行します。バージョン 11 で、WebKitCSSMatrix が追加されました。

- -

[2] WebKit は、WebKitCSSMatrix としてこの API を実行します。

- -

関連情報

- - diff --git a/files/ja/web/api/deviceacceleration/index.html b/files/ja/web/api/deviceacceleration/index.html deleted file mode 100644 index 982499c4a8..0000000000 --- a/files/ja/web/api/deviceacceleration/index.html +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: DeviceAcceleration -slug: Web/API/DeviceAcceleration -tags: - - API - - Device - - Experimental - - Interface - - Orienttation - - Reference - - events -translation_of: Web/API/DeviceMotionEventAcceleration -translation_of_original: Web/API/DeviceAcceleration ---- -
{{ ApiRef("Device Orientation Events") }}{{SeeCompatTable}}
- -

DeviceAccelerationオブジェクトは、3つの軸に沿って発生しているデバイスの加速度についての情報を提供します。

- -

プロパティ

- -
-
{{domxref("DeviceAcceleration.x")}} {{readonlyInline}}
-
X軸に沿った加速度の大きさ。読み取り専用。
-
{{domxref("DeviceAcceleration.y")}} {{readonlyInline}}
-
Y軸に沿った加速度の大きさ。読み取り専用。
-
{{domxref("DeviceAcceleration.z")}} {{readonlyInline}}
-
 Z軸に沿った加速度の大きさ。読み取り専用。
-
- -

仕様

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName("Device Orientation", "#device_acceleration", "DeviceAcceleration")}}{{Spec2("Device Orientation")}}Initial definition
diff --git a/files/ja/web/api/devicemotioneventacceleration/index.html b/files/ja/web/api/devicemotioneventacceleration/index.html new file mode 100644 index 0000000000..982499c4a8 --- /dev/null +++ b/files/ja/web/api/devicemotioneventacceleration/index.html @@ -0,0 +1,47 @@ +--- +title: DeviceAcceleration +slug: Web/API/DeviceAcceleration +tags: + - API + - Device + - Experimental + - Interface + - Orienttation + - Reference + - events +translation_of: Web/API/DeviceMotionEventAcceleration +translation_of_original: Web/API/DeviceAcceleration +--- +
{{ ApiRef("Device Orientation Events") }}{{SeeCompatTable}}
+ +

DeviceAccelerationオブジェクトは、3つの軸に沿って発生しているデバイスの加速度についての情報を提供します。

+ +

プロパティ

+ +
+
{{domxref("DeviceAcceleration.x")}} {{readonlyInline}}
+
X軸に沿った加速度の大きさ。読み取り専用。
+
{{domxref("DeviceAcceleration.y")}} {{readonlyInline}}
+
Y軸に沿った加速度の大きさ。読み取り専用。
+
{{domxref("DeviceAcceleration.z")}} {{readonlyInline}}
+
 Z軸に沿った加速度の大きさ。読み取り専用。
+
+ +

仕様

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Device Orientation", "#device_acceleration", "DeviceAcceleration")}}{{Spec2("Device Orientation")}}Initial definition
diff --git a/files/ja/web/api/document/activeelement/index.html b/files/ja/web/api/document/activeelement/index.html deleted file mode 100644 index 31c1b2bc7f..0000000000 --- a/files/ja/web/api/document/activeelement/index.html +++ /dev/null @@ -1,144 +0,0 @@ ---- -title: document.activeElement -slug: Web/API/Document/activeElement -tags: - - DOM - - Focus - - Gecko - - HTML5 - - NeedsTranslation - - 要更新 -translation_of: Web/API/DocumentOrShadowRoot/activeElement -translation_of_original: Web/API/Document/activeElement ---- -
{{ApiRef}}
- -

概要

- -

Returns the currently focused element, that is, the element that will get keystroke events if the user types any. This attribute is read only.

- -

Often this will return an {{HTMLElement("input")}} or {{HTMLElement("textarea")}} object, if it has the text selection at the time.  If so, you can get more detail by using the element's selectionStart and selectionEnd properties.  Other times the focused element might be a {{HTMLElement("select")}} element (menu) or an {{HTMLElement("input")}} element, of type button, checkbox or radio.

- -
注記: On Mac, elements that aren't text input elements tend not to get focus assigned to them.
- -

Typically a user can press the tab key to move the focus around the page among focusable elements, and use the space bar to activate it (press a button, choose a radio).

- -

Do not confuse focus with a selection over the document, consisting mostly of static text nodes.  See {{domxref("window.getSelection()")}} for that.

- -

When there is no selection, the active element is the page's {{HTMLElement("body")}}.

- -

{{Note("This attribute is part of the in-development HTML 5 specification.")}}

- -

構文

- -
var curElement = document.activeElement;
-
- -

- -
<!DOCTYPE HTML>
-<html>
-<head>
-    <script type="text/javascript" charset="utf-8">
-    function init() {
-
-        function onMouseUp(e) {
-            console.log(e);
-            var outputElement = document.getElementById('output-element');
-            var outputText = document.getElementById('output-text');
-            var selectedTextArea = document.activeElement;
-            var selection = selectedTextArea.value.substring(
-            selectedTextArea.selectionStart, selectedTextArea.selectionEnd);
-            outputElement.innerHTML = selectedTextArea.id;
-            outputText.innerHTML = selection;
-        }
-
-        document.getElementById("ta-example-one").addEventListener("mouseup", onMouseUp, false);
-        document.getElementById("ta-example-two").addEventListener("mouseup", onMouseUp, false);
-    }
-    </script>
-</head>
-<body onload="init()">
-<div>
-    Select some text from one of the Textareas below:
-</div>
-<form id="frm-example" action="#" accept-charset="utf-8">
-<textarea name="ta-example-one" id="ta-example-one" rows="8" cols="40">
-This is Textarea Example One:
-Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.
-</textarea>
-<textarea name="ta-example-two" id="ta-example-two" rows="8" cols="40">
-This is Textarea Example Two:
-Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.
-</textarea>
-</form>
-Active Element Id: <span id="output-element"></span><br/>
-Selected Text: <span id="output-text"></span>
-
-</body>
-</html>
-
- -

JSFiddle で確認

- -

注記

- -

Originally introduced as a proprietary DOM extension in Internet Explorer 4, this property also is supported in Opera and Safari (as of version 4).

- -

仕様

- - - -

ブラウザ実装状況

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - -
機能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本サポート23.049.64.0
-
- -
- - - - - - - - - - - - - - - - - - - -
機能AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本サポート{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
-
- -

 

diff --git a/files/ja/web/api/document/async/index.html b/files/ja/web/api/document/async/index.html deleted file mode 100644 index 00d0b0724c..0000000000 --- a/files/ja/web/api/document/async/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: XMLDocument.async -slug: Web/API/Document/async -tags: - - API - - DOM - - DOM Reference - - Deprecated - - Document - - Non-standard - - Property - - Reference - - async -translation_of: Web/API/XMLDocument/async ---- -

{{APIRef("DOM")}}{{Non-standard_header}}{{Deprecated_header}}

- -

document.async は、 {{DOMxRef("XMLDocument.load()")}} の呼び出しを同期で行うか、または非同期で行うかの指示を真偽値で設定します。 true が初期値であり、これは文書を非同期的に読み込むよう要求するものです。

- -

(1.4 アルファから、同期的に文書を読み込めるようになりました。)

- -

- -
function loadXMLData(e) {
-  alert(new XMLSerializer().serializeToString(e.target)); // querydata.xml の内容を文字列として取得
-}
-
-var xmlDoc = document.implementation.createDocument("", "test", null);
-
-xmlDoc.async = false;
-xmlDoc.onload = loadXMLData;
-xmlDoc.load('querydata.xml');
- -

ブラウザーの互換性

- - - -

{{Compat("api.XMLDocument.async")}}

- -

関連情報

- - diff --git a/files/ja/web/api/document/elementfrompoint/index.html b/files/ja/web/api/document/elementfrompoint/index.html deleted file mode 100644 index a24f1ce63a..0000000000 --- a/files/ja/web/api/document/elementfrompoint/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: document.elementFromPoint -slug: Web/API/Document/elementFromPoint -tags: - - DOM - - Gecko - - Gecko DOM Reference -translation_of: Web/API/DocumentOrShadowRoot/elementFromPoint -translation_of_original: Web/API/Document/elementFromPoint ---- -
- {{ApiRef()}} {{Fx_minversion_header(3)}}
-

概要

-

文書の左上を基点として指定された座標上にある要素を返します。

-

構文

-
element = document.elementFromPoint(x,y);
- -

-
<!DOCTYPE html>
-<html lang="ja">
-<head>
-<title>elementFromPoint の使用例</title>
-
-<script>
-function changeColor(newColor) {
-  elem = document.elementFromPoint(2, 2);
-  elem.style.color = newColor;
-}
-</script>
-</head>
-
-
-<body>
-<p id="para1">色は匂へど 散りぬるを……</p>
-<button onclick="changeColor('blue');">blue</button>
-<button onclick="changeColor('red');">red</button>
-</body>
-</html>
-
-

注記

-

指定された座標にある要素が別のドキュメント(例えば iframe 内にあるサブドキュメント) に属する場合、指定された座標にあるドキュメントの DOM 要素 (iframe) を返します。もし指定された座標にある要素が匿名あるいは textbox のスクロールバーのように XBL によって生成された内容の場合、指定された座標にある要素を基点として、匿名ではない最初の親要素(例えば textbox)が返されます。

-

指定された座標がドキュメントの表示外にあるか、座標のどちらかに負の値が設定されている場合は NULL を返します。

-

{{Note("XUL ドキュメントからは onload イベントが発生するまでは、このメソッドを使用してはいけません。")}}

-

仕様

- diff --git a/files/ja/web/api/document/getanimations/index.html b/files/ja/web/api/document/getanimations/index.html deleted file mode 100644 index eeb45f404e..0000000000 --- a/files/ja/web/api/document/getanimations/index.html +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Document.getAnimations() -slug: Web/API/Document/getAnimations -tags: - - API - - Animation - - CSS - - CSS Animations - - CSS Transitions - - Document - - Experimental - - Method - - Reference - - Transitions - - Web Animations - - getAnimations - - waapi - - web animations api -translation_of: Web/API/DocumentOrShadowRoot/getAnimations ---- -

{{ SeeCompatTable() }}{{APIRef("Web Animations")}}

- -

getAnimations() メソッドは {{domxref("Document")}} インターフェイスのメソッドで、この文書の配下にあるターゲット要素にあるすべての {{domxref("Animation")}} オブジェクトの配列を返します。この配列には CSS アニメーション, CSS トランジション, ウェブアニメーション が含まれます。

- -

構文

- -
var allAnimations = Document.getAnimations();
-
- -

引数

- -

なし。

- -

返値

- -

{{domxref("Animation")}} オブジェクトの {{jsxref("Array")}} で、それぞれの要素は呼び出された {{domxref("Document")}} の配下にある要素に現在関連付けられているアニメーション1つを表します。

- -

- -

次のコードスニペットは、ページ上のすべてのアニメーションの {{domxref("Animation.playbackRate")}} を半分にすることで速度をゆっくりにします。

- -
document.getAnimations().forEach(
-  function (animation) {
-    animation.playbackRate *= .5;
-  }
-);
- -

仕様書

- - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('Web Animations', '#dom-documentorshadowroot-getanimations', 'document.getAnimations()' )}}{{Spec2('Web Animations')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.Document.getAnimations")}}

- -

関連情報

- - diff --git a/files/ja/web/api/document/getselection/index.html b/files/ja/web/api/document/getselection/index.html deleted file mode 100644 index 740d006c66..0000000000 --- a/files/ja/web/api/document/getselection/index.html +++ /dev/null @@ -1,13 +0,0 @@ ---- -title: document.getSelection -slug: Web/API/Document/getSelection -tags: - - DOM - - Document - - Reference - - Selection -translation_of: Web/API/DocumentOrShadowRoot/getSelection -translation_of_original: Web/API/Document/getSelection ---- -

DOM の getSelection() メソッドは、 {{domxref("Window")}} インタフェース及び {{domxref("Document")}} インタフェースで利用可能です。
- 詳細については {{domxref("window.getSelection()")}} の頁を参照して下さい。

diff --git a/files/ja/web/api/document/inputencoding/index.html b/files/ja/web/api/document/inputencoding/index.html deleted file mode 100644 index bc128b09e8..0000000000 --- a/files/ja/web/api/document/inputencoding/index.html +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: document.inputEncoding -slug: Web/API/Document/inputEncoding -tags: - - DOM - - Document - - Gecko - - Gecko DOM Reference -translation_of: Web/API/Document/characterSet -translation_of_original: Web/API/Document/inputEncoding ---- -

{{ApiRef}} {{deprecated_header}}

-

概要

-

文書パース時のエンコーディングを表す文字列(※ ISO-8859-1 等)を返します。

-
- 注記: このメソッドは DOM 4 仕様書ドラフトから削除されており、Gecko の実装からも削除される可能性があります。使用しないようにしてください。
-

構文

-
encoding = document.inputEncoding;
- -

仕様書

- diff --git a/files/ja/web/api/document/onselectionchange/index.html b/files/ja/web/api/document/onselectionchange/index.html deleted file mode 100644 index 9793bde3fa..0000000000 --- a/files/ja/web/api/document/onselectionchange/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Document.onselectionchange -slug: Web/API/Document/onselectionchange -tags: - - API - - Document - - Experimental - - Reference - - イベントハンドラー - - プロパティ -translation_of: Web/API/GlobalEventHandlers/onselectionchange -translation_of_original: Web/API/Document/onselectionchange ---- -
{{ApiRef('DOM')}}{{SeeCompatTable}}
- -

Document.onselectionchange プロパティは、 {{event("selectionchange")}} イベントがこのオブジェクトに到達したときに呼び出されるイベントハンドラーを表します。

- -

構文

- -
obj.onselectionchange = function;
-
- - - -

- -
document.onselectionchange = function() { console.log("Selection changed!"); };
-
- -

仕様書

- - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('Selection API','','Document.onselectionchange')}}{{Spec2('Selection API')}}初回定義
- -

ブラウザーの対応

- - - -

{{Compat("api.Document.onselectionchange")}}

- -

関連情報

- - diff --git a/files/ja/web/api/document_object_model/preface/index.html b/files/ja/web/api/document_object_model/preface/index.html deleted file mode 100644 index 4a390b9177..0000000000 --- a/files/ja/web/api/document_object_model/preface/index.html +++ /dev/null @@ -1,52 +0,0 @@ ---- -title: 序文 -slug: Web/API/Document_Object_Model/Preface -tags: - - DOM - - Gecko - - Gecko DOM Reference -translation_of: Web/API/Document_Object_Model -translation_of_original: Web/API/Document_Object_Model/Preface ---- -
- {{ApiRef}}
-

この資料について

-

この節では、このガイドそのものについて説明します。誰のための資料で、どんな情報があって、あなた独自の DOM 開発を行うにあたってこの資料のなかの例をどのように使えるのか、について説明します。

-

この文書は書きかけなので、Gecko に実装されている DOM 関数と属性がきれいにまとめられてはいません。ただし、資料に含まれる各オブジェクトに関する文書 (DOM Document リファレンス など) は完結しています。多数の API に含まれるさまざまな資料が準備でき次第、この資料に追加します。

-

この資料の対象となる読者

-

Gecko DOM リファレンス の読者は web 開発者や web ページの仕組みを知っている web の利用者です。この資料では、読者の専門知識を前提とはしていません。DOM、XML、web サーバ、web 標準、読者が DOM にアクセスするための言語である JavaScript に関する知識があるとは限らないものとしています。ですが、web ページの基本である HTML とブラウザとスタイルシートなどは押さえているものとして書かれています。

-

「導入の記述がある」 「例が多様」 「説明が詳しい」 という点では、「初心者向け」 のハッキングガイドと言うこともできます。ただし、一般的に言って、技術資料というものは web 開発の経験があっても無くても、その人たちにとって有用な資料である必要があります。

-

Gecko とは?

-

Mozilla と Firefox、Netscape 6 以上、そのほかの Mozilla をもとにしたブラウザの DOM 実装は同一のものです。というのも、これらのブラウザは同じ技術を使用しているからです。naturally, it applies only to products based on the same version of Gecko, but it's tricky to explain

-

Gecko はこれらのブラウザの中にあるソフトウェアコンポーネントのことで、HTML の解析、ページのレイアウト、ドキュメント・オブジェクト・モデル、そしてアプリケーション・インタフェースの描画も処理しています。Gecko は、速く、標準に準拠した描画エンジンで、W3C の DOM 標準や DOM に類似した(しかし標準化されていない)ブラウザ・オブジェクト・モデル(例:window など)を、web ページやブラウザのアプリケーション・インタフェース(chrome)において、実装します。

-

ブラウザによって表示されるアプリケーション・インタフェースやコンテントは実際には異なりますが、DOM はこれらを一律にノードの階層として提示します。(commenting this incomplete sentence out for now...) The tree structure of the DOM (which in its application to the user

-

API 構文

-

各資料には、構文、入出力の引数 (return 型が与えられている return 型の場所) 、例、補足、該当仕様へのリンクがあります。

-

とくに読みとり専用属性の文法は基本的に一行だけです。なぜなら、それらのプロパティは設定できずアクセスしかできないからです。例えば、screen オブジェクトの availHeight は読取専用の属性なので、次のような構文で書かれています。

-
iAvail = window.screen.availHeight
-
-

つまり、式の右辺の属性だけが利用できるということです。それに対して、読み書き可能な属性の場合は、次の例でも分かるように、値を設定することもできます。

-
msg = window.status
-window.status = msg
-
-

一般に、メンバの記述があるオブジェクトの場合、その構文は簡潔な型になります。例えば、要素ならなんでも element ですし、document オブジェクトなら document ですし、TABLE オブジェクトなら TABLE といった具合です (データ型について詳しくは重要なデータ型 を参照してください)。

-

例の使い方

-

資料にある例のうち、その多くは単独のファイルとして完結しているものです。新しいファイルにコピーしてブラウザで開くと、きちんと動作します。コード断片もあります。断片の場合は、その断片を JavaScript コールバック関数内で使うことができます。例えば、 window.document 属性の資料にある例を次のように関数内に入れて、ボタンが押されたら呼ばれるような確認コードを書くことができます。

-
<!DOCTYPE html>
-<html>
-<head>
-<title>Test Page</title>
-<script>
-function testWinDoc() {
-  doc = window.document;
-  alert(doc.title);
-}
-</script>
-</head>
-
-<body>
-  <button onclick="testWinDoc();">test document property</button>
-</body>
-</html>
-
-

すぐに利用できるように梱包されていないオブジェクトのメンバーについても、上記のような関数やページを作り出すことができます。「テスト実行環境」 の導入部分にある DOM API のテスト の節を参照してください。それを使うと、一度に、たくさんの API の動作を確認できます。

diff --git a/files/ja/web/api/documentorshadowroot/activeelement/index.html b/files/ja/web/api/documentorshadowroot/activeelement/index.html new file mode 100644 index 0000000000..31c1b2bc7f --- /dev/null +++ b/files/ja/web/api/documentorshadowroot/activeelement/index.html @@ -0,0 +1,144 @@ +--- +title: document.activeElement +slug: Web/API/Document/activeElement +tags: + - DOM + - Focus + - Gecko + - HTML5 + - NeedsTranslation + - 要更新 +translation_of: Web/API/DocumentOrShadowRoot/activeElement +translation_of_original: Web/API/Document/activeElement +--- +
{{ApiRef}}
+ +

概要

+ +

Returns the currently focused element, that is, the element that will get keystroke events if the user types any. This attribute is read only.

+ +

Often this will return an {{HTMLElement("input")}} or {{HTMLElement("textarea")}} object, if it has the text selection at the time.  If so, you can get more detail by using the element's selectionStart and selectionEnd properties.  Other times the focused element might be a {{HTMLElement("select")}} element (menu) or an {{HTMLElement("input")}} element, of type button, checkbox or radio.

+ +
注記: On Mac, elements that aren't text input elements tend not to get focus assigned to them.
+ +

Typically a user can press the tab key to move the focus around the page among focusable elements, and use the space bar to activate it (press a button, choose a radio).

+ +

Do not confuse focus with a selection over the document, consisting mostly of static text nodes.  See {{domxref("window.getSelection()")}} for that.

+ +

When there is no selection, the active element is the page's {{HTMLElement("body")}}.

+ +

{{Note("This attribute is part of the in-development HTML 5 specification.")}}

+ +

構文

+ +
var curElement = document.activeElement;
+
+ +

+ +
<!DOCTYPE HTML>
+<html>
+<head>
+    <script type="text/javascript" charset="utf-8">
+    function init() {
+
+        function onMouseUp(e) {
+            console.log(e);
+            var outputElement = document.getElementById('output-element');
+            var outputText = document.getElementById('output-text');
+            var selectedTextArea = document.activeElement;
+            var selection = selectedTextArea.value.substring(
+            selectedTextArea.selectionStart, selectedTextArea.selectionEnd);
+            outputElement.innerHTML = selectedTextArea.id;
+            outputText.innerHTML = selection;
+        }
+
+        document.getElementById("ta-example-one").addEventListener("mouseup", onMouseUp, false);
+        document.getElementById("ta-example-two").addEventListener("mouseup", onMouseUp, false);
+    }
+    </script>
+</head>
+<body onload="init()">
+<div>
+    Select some text from one of the Textareas below:
+</div>
+<form id="frm-example" action="#" accept-charset="utf-8">
+<textarea name="ta-example-one" id="ta-example-one" rows="8" cols="40">
+This is Textarea Example One:
+Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec tincidunt, lorem a porttitor molestie, odio nibh iaculis libero, et accumsan nunc orci eu dui.
+</textarea>
+<textarea name="ta-example-two" id="ta-example-two" rows="8" cols="40">
+This is Textarea Example Two:
+Fusce ullamcorper, nisl ac porttitor adipiscing, urna orci egestas libero, ut accumsan orci lacus laoreet diam. Morbi sed euismod diam.
+</textarea>
+</form>
+Active Element Id: <span id="output-element"></span><br/>
+Selected Text: <span id="output-text"></span>
+
+</body>
+</html>
+
+ +

JSFiddle で確認

+ +

注記

+ +

Originally introduced as a proprietary DOM extension in Internet Explorer 4, this property also is supported in Opera and Safari (as of version 4).

+ +

仕様

+ + + +

ブラウザ実装状況

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
機能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本サポート23.049.64.0
+
+ +
+ + + + + + + + + + + + + + + + + + + +
機能AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本サポート{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

 

diff --git a/files/ja/web/api/documentorshadowroot/elementfrompoint/index.html b/files/ja/web/api/documentorshadowroot/elementfrompoint/index.html new file mode 100644 index 0000000000..a24f1ce63a --- /dev/null +++ b/files/ja/web/api/documentorshadowroot/elementfrompoint/index.html @@ -0,0 +1,50 @@ +--- +title: document.elementFromPoint +slug: Web/API/Document/elementFromPoint +tags: + - DOM + - Gecko + - Gecko DOM Reference +translation_of: Web/API/DocumentOrShadowRoot/elementFromPoint +translation_of_original: Web/API/Document/elementFromPoint +--- +
+ {{ApiRef()}} {{Fx_minversion_header(3)}}
+

概要

+

文書の左上を基点として指定された座標上にある要素を返します。

+

構文

+
element = document.elementFromPoint(x,y);
+ +

+
<!DOCTYPE html>
+<html lang="ja">
+<head>
+<title>elementFromPoint の使用例</title>
+
+<script>
+function changeColor(newColor) {
+  elem = document.elementFromPoint(2, 2);
+  elem.style.color = newColor;
+}
+</script>
+</head>
+
+
+<body>
+<p id="para1">色は匂へど 散りぬるを……</p>
+<button onclick="changeColor('blue');">blue</button>
+<button onclick="changeColor('red');">red</button>
+</body>
+</html>
+
+

注記

+

指定された座標にある要素が別のドキュメント(例えば iframe 内にあるサブドキュメント) に属する場合、指定された座標にあるドキュメントの DOM 要素 (iframe) を返します。もし指定された座標にある要素が匿名あるいは textbox のスクロールバーのように XBL によって生成された内容の場合、指定された座標にある要素を基点として、匿名ではない最初の親要素(例えば textbox)が返されます。

+

指定された座標がドキュメントの表示外にあるか、座標のどちらかに負の値が設定されている場合は NULL を返します。

+

{{Note("XUL ドキュメントからは onload イベントが発生するまでは、このメソッドを使用してはいけません。")}}

+

仕様

+ diff --git a/files/ja/web/api/documentorshadowroot/getanimations/index.html b/files/ja/web/api/documentorshadowroot/getanimations/index.html new file mode 100644 index 0000000000..eeb45f404e --- /dev/null +++ b/files/ja/web/api/documentorshadowroot/getanimations/index.html @@ -0,0 +1,81 @@ +--- +title: Document.getAnimations() +slug: Web/API/Document/getAnimations +tags: + - API + - Animation + - CSS + - CSS Animations + - CSS Transitions + - Document + - Experimental + - Method + - Reference + - Transitions + - Web Animations + - getAnimations + - waapi + - web animations api +translation_of: Web/API/DocumentOrShadowRoot/getAnimations +--- +

{{ SeeCompatTable() }}{{APIRef("Web Animations")}}

+ +

getAnimations() メソッドは {{domxref("Document")}} インターフェイスのメソッドで、この文書の配下にあるターゲット要素にあるすべての {{domxref("Animation")}} オブジェクトの配列を返します。この配列には CSS アニメーション, CSS トランジション, ウェブアニメーション が含まれます。

+ +

構文

+ +
var allAnimations = Document.getAnimations();
+
+ +

引数

+ +

なし。

+ +

返値

+ +

{{domxref("Animation")}} オブジェクトの {{jsxref("Array")}} で、それぞれの要素は呼び出された {{domxref("Document")}} の配下にある要素に現在関連付けられているアニメーション1つを表します。

+ +

+ +

次のコードスニペットは、ページ上のすべてのアニメーションの {{domxref("Animation.playbackRate")}} を半分にすることで速度をゆっくりにします。

+ +
document.getAnimations().forEach(
+  function (animation) {
+    animation.playbackRate *= .5;
+  }
+);
+ +

仕様書

+ + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('Web Animations', '#dom-documentorshadowroot-getanimations', 'document.getAnimations()' )}}{{Spec2('Web Animations')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Document.getAnimations")}}

+ +

関連情報

+ + diff --git a/files/ja/web/api/documentorshadowroot/nodefrompoint/index.html b/files/ja/web/api/documentorshadowroot/nodefrompoint/index.html deleted file mode 100644 index a7953136e6..0000000000 --- a/files/ja/web/api/documentorshadowroot/nodefrompoint/index.html +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: DocumentOrShadowRoot.nodeFromPoint() -slug: Web/API/DocumentOrShadowRoot/nodeFromPoint -tags: - - API - - DocumentOrShadowRoot - - Method - - Non-standard - - Reference - - nodeFromPoint - - メソッド - - 標準外 -translation_of: Web/API/DocumentOrShadowRoot -translation_of_original: Web/API/DocumentOrShadowRoot/nodeFromPoint ---- -
{{APIRef("DOM")}}{{Non-standard_header}}
- -

{{domxref("DocumentOrShadowRoot")}} インターフェイスの nodeFromPoint() プロパティは、 (ビューポートからの相対で) 指定された座標にある最上位のノードを返します。

- -

現在のところ、このメソッドは Firefox でしか実装されておらず、クロムコードでのみ利用できます。

- -

構文

- -
var node = document.nodeFromPoint(x, y);
- -

引数

- -
-
x
-
点の水平座標を表す倍精度浮動小数値。
-
y
-
点の垂直座標を表す倍精度浮動小数値。
-
- -

返値

- -

{{domxref('Node')}} オブジェクト。

- -

- -

HTML Content

- -
<div>
-  <p>Some text</p>
-</div>
-<p>Top node at point 30, 20:</p>
-<div id="output"></div>
-
- -

JavaScript Content

- -
var output = document.getElementById("output");
-if (document.nodeFromPoint) {
-  var node = document.nodeFromPoint(30, 20);
-    output.textContent += node.localName;
-} else {
-  output.innerHTML = "<span style=\"color: red;\">" +
-     "Browser does not support <code>document.nodeFromPoint()</code>" +
-     "</span>";
-}
- -

{{EmbedLiveSample('Example', '420', '120')}}

- -

仕様書

- -

現在はどの仕様書にも含まれていません。

- -

ブラウザーの対応

- - - -

{{Compat("api.DocumentOrShadowRoot.nodeFromPoint")}}

- -

関連情報

- - diff --git a/files/ja/web/api/documentorshadowroot/nodesfrompoint/index.html b/files/ja/web/api/documentorshadowroot/nodesfrompoint/index.html deleted file mode 100644 index d3f79b8d11..0000000000 --- a/files/ja/web/api/documentorshadowroot/nodesfrompoint/index.html +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: DocumentOrShadowRoot.nodesFromPoint() -slug: Web/API/DocumentOrShadowRoot/nodesFromPoint -tags: - - API - - DocumentOrShadowRoot - - Method - - Non-standard - - Reference - - nodesFromPoint - - メソッド -translation_of: Web/API/DocumentOrShadowRoot -translation_of_original: Web/API/DocumentOrShadowRoot/nodesFromPoint ---- -
{{APIRef("DOM")}}{{Non-standard_header}}
- -

{{domxref("DocumentOrShadowRoot")}} インターフェイスの nodesFromPoint() プロパティは、 (ビューポートからの相対で) 指定された座標のすべてのノードの配列を返します。

- -

現在のところ、このメソッドは Firefox でしか実装されておらず、クロムコードでのみ利用できます。

- -

構文

- -
var nodes = document.nodesFromPoint(x, y);
- -

引数

- -
-
x
-
点の水平座標。
-
y
-
点の垂直座標。
-
- -

返値

- -

{{domxref('Node')}} オブジェクトの配列。

- -

- -

HTML コンテンツ

- -
<div>
-  <p>Some text</p>
-</div>
-<p>Nodes at point 30, 20:</p>
-<div id="output"></div>
-
- -

JavaScript コンテンツ

- -
var output = document.getElementById("output");
-if (document.nodesFromPoint) {
-  var nodes = document.nodesFromPoint(30, 20);
-  for(var i = 0; i < nodes.length; i++) {
-    output.textContent += nodes[i].localName;
-    if (i < nodes.length - 1) {
-      output.textContent += " < ";
-    }
-  }
-} else {
-  output.innerHTML = "<span style=\"color: red;\">" +
-     "Browser does not support <code>document.nodesFromPoint()</code>" +
-     "</span>";
-}
- -

{{EmbedLiveSample('Example', '420', '120')}}

- -

仕様書

- -

現在はどの仕様書にも含まれていません。

- -

ブラウザーの対応

- - - -

{{Compat("api.DocumentOrShadowRoot.nodesFromPoint")}}

- -

関連情報

- - diff --git a/files/ja/web/api/dommatrix/index.html b/files/ja/web/api/dommatrix/index.html new file mode 100644 index 0000000000..756a3c4cb2 --- /dev/null +++ b/files/ja/web/api/dommatrix/index.html @@ -0,0 +1,94 @@ +--- +title: CSSMatrix +slug: Web/API/CSSMatrix +tags: + - API + - NeedsBrowserCompatibility + - Reference +translation_of: Web/API/DOMMatrix +translation_of_original: Web/API/CSSMatrix +--- +
{{APIRef("CSSOM")}}{{Non-standard_header}}
+ +

CSSMatrix は、2D または 3D の変形が適用できる同次の 4x4 行列を表しています。このクラスは、ある時点で CSS Transitions モジュールレベル 3 の一部ということになっていましたが、現在のワーキングドラフトで存在しません。代わりに DOMMatrix を使用してください。

+ +

仕様

+ + + + + + + + + + + + + + + + +
仕様ステータスコメント
{{SpecName('Compat', '#webkitcssmatrix-interface', 'WebKitCSSMatrix')}}{{Spec2('Compat')}}WebKit プレフィックス付きバージョン、WebKitCSSMatrix の初期の標準化。
+ +

ブラウザー互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
機能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本サポート{{CompatUnknown}}{{CompatUnknown}}10[1]{{CompatUnknown}}{{CompatVersionUnknown}}[2]
+
+ +
+ + + + + + + + + + + + + + + + + + + +
機能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本サポート{{CompatUnknown}}{{CompatUnknown}}11[1]{{CompatUnknown}}{{CompatVersionUnknown}}[2]
+
+ +

[1] Internet Explorer は、MSCSSMatrix としてこの API を実行します。バージョン 11 で、WebKitCSSMatrix が追加されました。

+ +

[2] WebKit は、WebKitCSSMatrix としてこの API を実行します。

+ +

関連情報

+ + diff --git a/files/ja/web/api/element/accesskey/index.html b/files/ja/web/api/element/accesskey/index.html deleted file mode 100644 index 82738c792f..0000000000 --- a/files/ja/web/api/element/accesskey/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Element.accessKey -slug: Web/API/Element/accessKey -translation_of: Web/API/HTMLElement/accessKey -translation_of_original: Web/API/Element/accessKey ---- -
{{APIRef("DOM")}}
- -
 
- -
Element.accessKeyは、ユーザが他の要素へジャンプする時に押す、キーストロークを設定します。
- -
 
- -
-

Element.accessKey は、ブラウザの既定のキーバインディングと競合する為、めったに使われません。この競合を回避するために、ブラウザはアクセスキーの挙動を他の「最適な」キーと一緒に押されたときに動くように実装しています。( Alt + アクセスキー、の様に。)

-
- -

See also 

- - diff --git a/files/ja/web/api/element/name/index.html b/files/ja/web/api/element/name/index.html deleted file mode 100644 index e069431e6e..0000000000 --- a/files/ja/web/api/element/name/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: element.name -slug: Web/API/Element/name -translation_of: Web/API -translation_of_original: Web/API/Element/name ---- -

{{ ApiRef() }}

-

概要

-

name はDOM オブジェクトのname 属性を取得または設定します。

-

ただし、この属性が適用されるのは次の要素に限られます。

-

{{ HTMLelement("a") }}, {{ HTMLelement("applet") }}, {{ HTMLelement("form") }}, {{ HTMLelement("frame") }}, {{ HTMLelement("iframe") }}, {{ HTMLelement("img") }}, {{ HTMLelement("input") }}, {{ HTMLelement("map") }}, {{ HTMLelement("meta") }}, {{ HTMLelement("object") }}, {{ HTMLelement("option") }}, {{ HTMLelement("param") }}, {{ HTMLelement("select") }}, {{ HTMLelement("textarea") }}.

-

name は、 {{ domxref("document.getElementsByName()") }} メソッドか、 formform.elements のコレクションで使用することができます。 form や form.elements のコレクションで使われた場合、一つの要素かコレクションを返します。

-

構文

-
HTMLElement.name = string;
-var elName = HTMLElement.name;
-
-var fControl = HTMLFormElement.elementName;
-var controlCollection = HTMLFormElement.elements.elementName;
-
-

-
<form action="" name="formA">
-  <input type="text" value="foo">
-</form>
-
-<script type="text/javascript">
-
-  // form の最初の要素の参照を取得します。
-  var formElement = document.forms['formA'].elements[0];
-
-  // name 属性を設定します。
-  formElement.name = 'inputA';
-
-  // input の value を表示します。
-  alert(document.forms['formA'].elements['inputA'].value);
-
-</script>
-
-

注記

-

Internet Explorer (IE)では、 {{ domxref("document.createElement()") }}を使って作成されたDOM オブジェクトの name 属性 は、設定および変更をすることができません。

-

仕様

-

W3C DOM 2 HTML Specification:

- -

{{ languages( { "en" :"en/DOM/element.name", "fr": "fr/DOM/element.name", "pl": "pl/DOM/element.name" } ) }}

diff --git a/files/ja/web/api/event/button/index.html b/files/ja/web/api/event/button/index.html deleted file mode 100644 index 572f611ebc..0000000000 --- a/files/ja/web/api/event/button/index.html +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: event.button -slug: Web/API/Event/button -tags: - - DOM - - Gecko - - Gecko DOM Reference -translation_of: Web/API/MouseEvent/button -translation_of_original: Web/API/event.button ---- -

{{ ApiRef() }}

-

Summary

-

イベントを発生させたマウスのボタンを示しています。

-

Syntax

-
var buttonCode = event.button;
-
-

state を変えたボタンを示す整数値を返します。

- -

ボタンの順序はどのようにポインティングデバイスが設定されているかによります。

-

Example

-
<script type="text/javascript">
-
-function whichButton(e)
-{
-  // Handle different event models
-  var e = e || window.event;
-  var btnCode;
-
-  if ('object' == typeof e){
-    btnCode = e.button;
-
-    switch (btnCode){
-      case 0  : alert('Left button clicked');
-                break;
-      case 1  : alert('Middle button clicked');
-                break;
-      case 2  : alert('Right button clicked');
-                break;
-      default : alert('Unexpected code: ' + btnCode);
-    }
-  }
-}
-
-</script>
-
-<p onclick="whichButton(event);">Click with mouse...</p>
-
-
-

Notes

-

マウスのクリックはしばしばUIによって横取りされるため、ある状況では普通のクリック(通常は左クリック)でないマウスのクリックを検出することが普通のクリックよりも難しいかもしれません。

-

ユーザーはポインティングデバイスのボタンの設定を変更する可能性があり、たといこのイベントの button プロパティが 0 であったとしても、それは物理的にポインティングデバイスの最も左に存在するボタンによるものではないかもしれません。しかし、そんな場合にも、標準的なボタン配置における左クリックと同様の動作をするべきであるとされています。

-

Specification

-

DOM 2 Events Specification: button

-
-  
-

{{ languages( { "en": "en/DOM/event.button", "pl": "pl/DOM/event.button" } ) }}

diff --git a/files/ja/web/api/event/createevent/index.html b/files/ja/web/api/event/createevent/index.html deleted file mode 100644 index d9dc6aef3f..0000000000 --- a/files/ja/web/api/event/createevent/index.html +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Event.createEvent() -slug: Web/API/Event/createEvent -translation_of: Web/API/Document/createEvent -translation_of_original: Web/API/Event/createEvent ---- -

{{APIRef("DOM")}}

- -

新規イベントを生成します。生成されたイベントは初期化処理が必須です。

- -

構文

- -
document.createEvent(type) 
- -
-
type
-
生成するイベントタイプ名
-
- -

このメソッドは指定されたイベントタイプの新規DOM {{ domxref("Event") }} オブジェクトを返り値として返します。

- -

オブジェクトには初期化処理が必須です。

- -

- -
var newEvent = document.createEvent("UIEvents");
- -

仕様書

- - diff --git a/files/ja/web/api/gamepad_api/using_the_gamepad_api/index.html b/files/ja/web/api/gamepad_api/using_the_gamepad_api/index.html new file mode 100644 index 0000000000..1cd391adb2 --- /dev/null +++ b/files/ja/web/api/gamepad_api/using_the_gamepad_api/index.html @@ -0,0 +1,347 @@ +--- +title: ゲームパッド API の使用 +slug: Web/Guide/API/Gamepad +tags: + - API + - Advanced + - Gamepad API + - Games + - Guide +translation_of: Web/API/Gamepad_API/Using_the_Gamepad_API +--- +

{{DefaultAPISidebar("Gamepad API")}}

+ +

HTML5 はリッチでインタラクティブなゲームを開発するために必要なコンポーネントを多く搭載しています。 <canvas> や WebGL、 <audio><video> などの技術は、今までネイティブコードを書く必要のあった機能をサポートできるほどに成長しました。ゲームパッド API は開発者とデザイナーにゲームパッドやコントローラーへのアクセスを提供するものです。

+ +

ゲームパッドAPI は {{ domxref("Window") }} オブジェクトにゲームパッドとコントローラー (以下、ゲームパッド) の状態を読み取る新しいイベントをいくつか追加します。さらに、 {{ domxref("Gamepad") }} というゲームパッドの接続状態が得られるオブジェクトと {{ domxref("navigator.getGamepads") }} というゲームパッドの一覧を取得できるメソッドが追加されます。

+ +

ゲームパッドの接続

+ +

新しいゲームパッドが接続された時、アクティブなページは {{ domxref("Window/gamepadconnected_event", "gamepadconnected") }} イベントを受け取ります。ページ読み込み時にゲームパッドがすでに接続されている場合、ゲームパッドのボタンを押すなどの操作をした時に {{ domxref("Window/gamepadconnected_event", "gamepadconnected") }} イベントがアクティブなページに対して発生します。

+ +
+

Firefox では、ページが見える状態でかつユーザーによるゲームパッドの操作を受け付けたときにのみ、ゲームパッドが利用可能になります。これによって、ユーザーを特定する Fingerprinting に利用されることを防止しています。一度一つのコントローラーが操作されれば、他のコントローラーも自動で接続され利用可能になります。

+
+ +

以下のようにして {{ domxref("Window/gamepadconnected_event", "gamepadconnected") }} を使用します:

+ +
window.addEventListener("gamepadconnected", function(e) {
+  console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",
+    e.gamepad.index, e.gamepad.id,
+    e.gamepad.buttons.length, e.gamepad.axes.length);
+});
+
+ +

ゲームパッドはそれぞれ固有の ID を gamepad プロパティの中に持っています。

+ +

ゲームパッドの切断

+ +

ゲームパッドが切断されると、ゲームパッドが以前に受信したデータ(例: {{ domxref("Window/gamepadconnected_event", "gamepadconnected") }} )があると、2番目のイベント(例: {{ domxref("Window/gamepadconnected_event", "gamepadconnected") }} )がフォーカスされたウィンドウにディスパッチします:

+ +
window.addEventListener("gamepaddisconnected", function(e) {
+  console.log("Gamepad disconnected from index %d: %s",
+    e.gamepad.index, e.gamepad.id);
+});
+ +

ゲームパッドの {{domxref("Gamepad.index", "index")}} というプロパティは同じタイプの複数のコントローラーが使用されている場合であっても、システムに接続されたデバイスごとにユニークになります。 Index プロパティもまた {{ domxref("Navigator.getGamepads()") }} として戻される {{jsxref("Array")}} の index として機能します。

+ +
var gamepads = {};
+
+function gamepadHandler(event, connecting) {
+  var gamepad = event.gamepad;
+  // Note:
+  // gamepad === navigator.getGamepads()[gamepad.index]
+
+  if (connecting) {
+    gamepads[gamepad.index] = gamepad;
+  } else {
+    delete gamepads[gamepad.index];
+  }
+}
+
+window.addEventListener("gamepadconnected", function(e) { gamepadHandler(e, true); }, false);
+window.addEventListener("gamepaddisconnected", function(e) { gamepadHandler(e, false); }, false);
+
+ +

この前の例ではイベントが完了した後に gamepad プロパティがどのように保持できるかを示しています - 後でデバイスの状態照会のために使用する技術となります。

+ +

Gamepad オブジェクトの問い合わせ

+ +

ご覧のように、上述の gamepad イベントは {{ domxref("Gamepad") }} オブジェクトを返すイベントオブジェクト、上の gamepad のプロパティが含まれています。複数のゲームパッド(すなわち、そのID ) を一度に接続される可能性があるため、イベントを発生させたのはどのゲームパッドを決定するためにこれらを使用することができます。それへの参照を保持し、それがボタンや軸のいずれかの時点で押されているかを知るために照会するなど、{{ domxref("Gamepad") }} オブジェクトから様々なことを行うことができます。そうすることで、多くの場合、今回と次回のイベント発生とゲームパッドの状態を知っておく必要があり、ゲームやその他のインタラクティブな Web ページであることが望ましいです。

+ +

このようなチェックを実行すると、開発者はゲームパッドやゲームパッドの状態に基づいて、現在のフレームのための意思決定を行うために必要なアニメーションループ (例 : {{ domxref("Window.requestAnimationFrame","requestAnimationFrame") }}) と一緒に {{ domxref("Gamepad") }} オブジェクトを使用して関与する傾向があります。

+ +

{{ domxref("Navigator.getGamepads()") }} メソッドは現在 Web ページから見える {{ domxref("Gamepad") }} オブジェクト (ゲームパッドが繋がっていない時は毎回 null が返される ) のような、すべてのデバイスを配列として戻します。これは、同じ情報を得るために使用することができます。例えば、 以下に示すように上記の最初のコード例を書き換えます。

+ +
window.addEventListener("gamepadconnected", function(e) {
+  var gp = navigator.getGamepads()[e.gamepad.index];
+  console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.",
+    gp.index, gp.id,
+    gp.buttons.length, gp.axes.length);
+});
+ +

{{ domxref("Gamepad") }} オブジェクトの機能は以下の通りです。

+ + + +
+

: Gamepadオブジェクトは、セキュリティ上の理由から {{ domxref("Window") }} オブジェクトではなく {{ domxref("Window/gamepadconnected_event", "gamepadconnected") }} イベントで使用できます。一度リファレンスを取得すると、そのプロパティでゲームパッドの現在の状態に関する情報を照会できます。 このオブジェクトは、ゲームパッドの状態が変わるたびに更新されます。

+
+ +

ボタン情報の使用

+ +

1つのゲームパッドの接続情報を表示する簡単な例を見てみましょう (後続のゲームパッド接続を無視します)。ゲームパッドの右側にある4つのゲームパッドボタンを使用してボールを画面の周りに移動できます。デモをライブで見ることができことができ、Githubでソースコードを見つけることができます

+ +

まず、いくつかの変数を宣言します: 接続情報が書き込まれる gamepadInfo のパラグラフ、移動する ballrequestAnimation Frame の ID として機能する start 変数、ボールを移動するための位置変更子として機能する a および b 変数、および短縮形変数 これは、 {{ domxref("Window.requestAnimationFrame", "requestAnimationFrame()") }} および {{ domxref("Window.cancelAnimationFrame", "cancelAnimationFrame()") }} クロスブラウザフォークで使用されます。

+ +
var gamepadInfo = document.getElementById("gamepad-info");
+var ball = document.getElementById("ball");
+var start;
+var a = 0;
+var b = 0;
+
+ +

次に {{ domxref("Window/gamepadconnected_event", "gamepadconnected") }} イベントを使用して、接続されているゲームパッドを確認します。接続されると {{ domxref("Navigator.getGamepads()") }}[0] を使用してゲームパッドを取得し、ゲームパッドに関する情報をゲームパッドの情報 div に出力し、全体のボールの動きが始まる gameLoop() 関数が呼び出されます。

+ +
window.addEventListener("gamepadconnected", function(e) {
+  var gp = navigator.getGamepads()[e.gamepad.index];
+  gamepadInfo.innerHTML = "Gamepad connected at index " + gp.index + ": " + gp.id + ". It has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes.";
+
+  gameLoop();
+});
+ +

これで {{domxref("Window/gamepaddisconnected_event", "gamepaddisconnected")}} イベントを使用して、ゲームパッドが再び切断されたかどうかを確認します。 もしそうならば、 {{DOMxRef("Window.requestAnimationFrame", "requestAnimationFrame()")}} ループ (下記参照) を停止し、ゲームパッドの情報を元の状態に戻します。

+ +
window.addEventListener("gamepaddisconnected", function(e) {
+  gamepadInfo.innerHTML = "Waiting for gamepad.";
+
+  cancelRequestAnimationFrame(start);
+});
+ +

Chrome では異なる挙動になります。変数にゲームパッドの最新の状態を常に保存するのではなく、スナップショットを保存するだけなので、 Chrome で同じことを行うにはポーリングしてから {{ domxref("Gamepad") }} オブジェクトをコードで使用する必要があり、それは利用可能です。私たちはこれを {{ domxref("Window.setInterval()") }} オブジェクトが利用可能になると、ゲームパッド情報が出力され、ゲームループが開始され、 {{ domxref("Window.clearInterval()") }} を使用して間隔がクリアされます。 Chrome {{ domxref("Navigator.getGamepads()") }} の古いバージョンでは、 Webkit 接頭辞を使用して実装されています。下位互換性のために、接頭辞付きのバージョンと関数の標準バージョンの両方を検出して処理しようとします。

+ +
var interval;
+
+if (!('ongamepadconnected' in window)) {
+  // No gamepad events available, poll instead.
+  interval = setInterval(pollGamepads, 500);
+}
+
+function pollGamepads() {
+  var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []);
+  for (var i = 0; i < gamepads.length; i++) {
+    var gp = gamepads[i];
+    if (gp) {
+      gamepadInfo.innerHTML = "Gamepad connected at index " + gp.index + ": " + gp.id +
+        ". It has " + gp.buttons.length + " buttons and " + gp.axes.length + " axes.";
+      gameLoop();
+      clearInterval(interval);
+    }
+  }
+}
+ +

今度はメインのゲームループです。ループが実行されるたびに、4つのボタンの1つが押されているかどうかがチェックされます。そうすると、ab の移動変数の値を適切に更新し、 {{ cssxref("left") }} と {{ cssxref("top") }} のプロパティを更新し、その値を a および b とする。これはボールを画面の周りに動かす効果があります。 現在のバージョンの Chrome (この記事の執筆時点ではバージョン34) では、ボタンの値は {{ domxref("GamepadButton") }} オブジェクトではなく、 double 値の配列として保存されます。

+ +

この作業がすべて完了したら、 requestAnimationFrame() を使用して gameLoop() を再び実行して次のアニメーションフレームを要求します。

+ +
function buttonPressed(b) {
+  if (typeof(b) == "object") {
+    return b.pressed;
+  }
+  return b == 1.0;
+}
+
+function gameLoop() {
+  var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []);
+  if (!gamepads) {
+    return;
+  }
+
+  var gp = gamepads[0];
+  if (buttonPressed(gp.buttons[0])) {
+    b--;
+  } else if (buttonPressed(gp.buttons[2])) {
+    b++;
+  }
+  if (buttonPressed(gp.buttons[1])) {
+    a++;
+  } else if (buttonPressed(gp.buttons[3])) {
+    a--;
+  }
+
+  ball.style.left = a * 2 + "px";
+  ball.style.top = b * 2 + "px";
+
+  start = requestAnimationFrame(gameLoop);
+}
+ +

完全な例: ゲームパッドの状態を表示する

+ +

この例では、 {{ domxref("Gamepad") }} オブジェクト、 {{ domxref("Window/gamepadconnected_event", "gamepadconnected") }} イベント、 {{domxref("Window/gamepaddisconnected_event", "gamepaddisconnected")}} イベントを使用してシステムに接続されているすべてのゲームパッドの状態を表示します。デモを見て、Githubの完全なソースコードを見ることができます。

+ +
var haveEvents = 'ongamepadconnected' in window;
+var controllers = {};
+
+function connecthandler(e) {
+  addgamepad(e.gamepad);
+}
+
+function addgamepad(gamepad) {
+  controllers[gamepad.index] = gamepad;
+
+  var d = document.createElement("div");
+  d.setAttribute("id", "controller" + gamepad.index);
+
+  var t = document.createElement("h1");
+  t.appendChild(document.createTextNode("gamepad: " + gamepad.id));
+  d.appendChild(t);
+
+  var b = document.createElement("div");
+  b.className = "buttons";
+  for (var i = 0; i < gamepad.buttons.length; i++) {
+    var e = document.createElement("span");
+    e.className = "button";
+    //e.id = "b" + i;
+    e.innerHTML = i;
+    b.appendChild(e);
+  }
+
+  d.appendChild(b);
+
+  var a = document.createElement("div");
+  a.className = "axes";
+
+  for (var i = 0; i < gamepad.axes.length; i++) {
+    var p = document.createElement("progress");
+    p.className = "axis";
+    //p.id = "a" + i;
+    p.setAttribute("max", "2");
+    p.setAttribute("value", "1");
+    p.innerHTML = i;
+    a.appendChild(p);
+  }
+
+  d.appendChild(a);
+
+  // See https://github.com/luser/gamepadtest/blob/master/index.html
+  var start = document.getElementById("start");
+  if (start) {
+    start.style.display = "none";
+  }
+
+  document.body.appendChild(d);
+  requestAnimationFrame(updateStatus);
+}
+
+function disconnecthandler(e) {
+  removegamepad(e.gamepad);
+}
+
+function removegamepad(gamepad) {
+  var d = document.getElementById("controller" + gamepad.index);
+  document.body.removeChild(d);
+  delete controllers[gamepad.index];
+}
+
+function updateStatus() {
+  if (!haveEvents) {
+    scangamepads();
+  }
+
+  var i = 0;
+  var j;
+
+  for (j in controllers) {
+    var controller = controllers[j];
+    var d = document.getElementById("controller" + j);
+    var buttons = d.getElementsByClassName("button");
+
+    for (i = 0; i < controller.buttons.length; i++) {
+      var b = buttons[i];
+      var val = controller.buttons[i];
+      var pressed = val == 1.0;
+      if (typeof(val) == "object") {
+        pressed = val.pressed;
+        val = val.value;
+      }
+
+      var pct = Math.round(val * 100) + "%";
+      b.style.backgroundSize = pct + " " + pct;
+
+      if (pressed) {
+        b.className = "button pressed";
+      } else {
+        b.className = "button";
+      }
+    }
+
+    var axes = d.getElementsByClassName("axis");
+    for (i = 0; i < controller.axes.length; i++) {
+      var a = axes[i];
+      a.innerHTML = i + ": " + controller.axes[i].toFixed(4);
+      a.setAttribute("value", controller.axes[i] + 1);
+    }
+  }
+
+  requestAnimationFrame(updateStatus);
+}
+
+function scangamepads() {
+  var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
+  for (var i = 0; i < gamepads.length; i++) {
+    if (gamepads[i]) {
+      if (gamepads[i].index in controllers) {
+        controllers[gamepads[i].index] = gamepads[i];
+      } else {
+        addgamepad(gamepads[i]);
+      }
+    }
+  }
+}
+
+window.addEventListener("gamepadconnected", connecthandler);
+window.addEventListener("gamepaddisconnected", disconnecthandler);
+
+if (!haveEvents) {
+ setInterval(scangamepads, 500);
+}
+ +

仕様書

+ + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName("Gamepad", "#gamepad-interface", "Gamepad")}}{{Spec2("Gamepad")}}初回定義
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Gamepad")}}

diff --git a/files/ja/web/api/globaleventhandlers/onreset/index.html b/files/ja/web/api/globaleventhandlers/onreset/index.html new file mode 100644 index 0000000000..c9862667e8 --- /dev/null +++ b/files/ja/web/api/globaleventhandlers/onreset/index.html @@ -0,0 +1,57 @@ +--- +title: window.onreset +slug: Web/API/Window/onreset +tags: + - DOM + - Gecko + - Gecko DOM Reference + - Window +translation_of: Web/API/GlobalEventHandlers/onreset +--- +
+ {{ApiRef}}
+

概要

+

フォームの reset イベントに対応するイベントハンドラです。

+

構文

+
window.onreset = funcRef;
+
+

引数

+ +

+
<!DOCTYPE html>
+<html lang="ja">
+<head>
+<meta charset="UTF-8" />
+<title>onreset のテスト</title>
+
+<script>
+function reg() {
+  window.onreset = hit;
+}
+
+function hit() {
+ alert('リセットイベントが発生しました。');
+}
+</script>
+
+</head>
+<body onload="reg();">
+
+<form>
+  <div>
+    <textarea></textarea>
+  </div>
+  <div>
+    <input type="reset" value="reset" />
+  </div>
+</form>
+
+</body>
+</html>
+
+

注記

+

reset イベントは、ユーザがフォーム内のリセットボタン (<input type="reset"/>) をクリックした際に発生します。

+

仕様

+

標準仕様書には含まれていません。

diff --git a/files/ja/web/api/globaleventhandlers/onresize/index.html b/files/ja/web/api/globaleventhandlers/onresize/index.html new file mode 100644 index 0000000000..db2b2bbae9 --- /dev/null +++ b/files/ja/web/api/globaleventhandlers/onresize/index.html @@ -0,0 +1,78 @@ +--- +title: window.onresize +slug: Web/API/Window/onresize +tags: + - DOM + - Gecko + - Property + - Window +translation_of: Web/API/GlobalEventHandlers/onresize +--- +

{{ ApiRef() }}

+ +

GlobalEventHandlers.onresize プロパティは、{{event("resize")}} イベントを受信するとトリガーされる {{domxref("EventHandler")}} を含みます。

+ +

構文

+ +
window.onresize = funcRef;
+
+ +

引数

+ + + +

+ +
window.onresize = doFunc;
+
+ +
<html>
+<head>
+
+<title>onresize test</title>
+
+</head>
+
+<body>
+<p>Resize the browser window to fire the resize event.</p>
+
+<p>Window height: <span id="height"></span></p>
+<p>Window width: <span id="width"></span></p>
+
+<script type="text/javascript">
+  var heightOutput = document.querySelector('#height');
+  var widthOutput = document.querySelector('#width');
+
+  function resize() {
+    heightOutput.textContent = window.innerHeight;
+    widthOutput.textContent = window.innerWidth;
+  }
+
+  window.onresize = resize;
+</script>
+</body>
+</html>
+
+ +

注記

+ +

ブラウザウィンドウのサイズが変更された後に resize イベントが発生します。

+ +

仕様

+ + + + + + + + + + + + + + +
使用ステータスコメント
{{SpecName('HTML WHATWG','webappapis.html#handler-onresize','onresize')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/ja/web/api/globaleventhandlers/onselectionchange/index.html b/files/ja/web/api/globaleventhandlers/onselectionchange/index.html new file mode 100644 index 0000000000..9793bde3fa --- /dev/null +++ b/files/ja/web/api/globaleventhandlers/onselectionchange/index.html @@ -0,0 +1,62 @@ +--- +title: Document.onselectionchange +slug: Web/API/Document/onselectionchange +tags: + - API + - Document + - Experimental + - Reference + - イベントハンドラー + - プロパティ +translation_of: Web/API/GlobalEventHandlers/onselectionchange +translation_of_original: Web/API/Document/onselectionchange +--- +
{{ApiRef('DOM')}}{{SeeCompatTable}}
+ +

Document.onselectionchange プロパティは、 {{event("selectionchange")}} イベントがこのオブジェクトに到達したときに呼び出されるイベントハンドラーを表します。

+ +

構文

+ +
obj.onselectionchange = function;
+
+ + + +

+ +
document.onselectionchange = function() { console.log("Selection changed!"); };
+
+ +

仕様書

+ + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('Selection API','','Document.onselectionchange')}}{{Spec2('Selection API')}}初回定義
+ +

ブラウザーの対応

+ + + +

{{Compat("api.Document.onselectionchange")}}

+ +

関連情報

+ + diff --git a/files/ja/web/api/html_drag_and_drop_api/drag_operations/index.html b/files/ja/web/api/html_drag_and_drop_api/drag_operations/index.html new file mode 100644 index 0000000000..4739714e52 --- /dev/null +++ b/files/ja/web/api/html_drag_and_drop_api/drag_operations/index.html @@ -0,0 +1,350 @@ +--- +title: ドラッグ操作 +slug: DragDrop/Drag_Operations +tags: + - Advanced + - Guide + - HTML + - HTML5 + - XUL + - ドラッグ&ドロップ +translation_of: Web/API/HTML_Drag_and_Drop_API/Drag_operations +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

以下は、ドラッグ&ドロップ操作が行われる時の各段階についての解説です。

+ +

この文書で記述されているドラッグ操作は {{domxref("DataTransfer")}} インターフェイスを使用します。この文書では {{domxref("DataTransferItem")}} インターフェイスや {{domxref("DataTransferItemList")}} インターフェイスは説明しません

+ +

draggable 属性

+ +

ウェブページにおいては、既定のドラッグ&ドロップの挙動が使われる場合がいくつかあります。文字列の選択範囲、画像、リンクなどのドラッグなどがこれにあたります。画像かリンクがドラッグされた時は、画像もしくはリンク先の URL がドラッグデータとして設定され、ドラッグ操作が始まります。その他の要素は、既定のドラッグ操作が行われるためには選択範囲に含まれていなければなりません。実際の様子を確認するには、ウェブページの一部を選択して、その上でマウスのボタンを押下し、そのまま選択範囲をドラッグしてください。ドラッグ中、選択範囲の内容を半透明で描画した物がマウスポインターに伴って表示されるでしょう。ただしこの挙動は、ドラッグされたデータを加工するイベントリスナーが存在しない場合の、既定のドラッグの挙動によるものです。

+ +

HTML では、画像、リンク、選択範囲の上での既定の動作を除くと、他の要素は初期状態ではドラッグできません。 XUL では、すべての要素がドラッグ可能です。

+ +

上記以外の他の HTML 要素をドラッグできるようにするには、以下の3つの事をしなくてはなりません。

+ + + +

以下は、コンテンツの一部がドラッグできるようにする例です。

+ +
<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'この文字列はドラッグができます')">
+  この文字列はドラッグが<strong>できます</strong>。
+</div>
+
+ +

{{htmlattrxref("draggable")}} 属性を true に設定すると、その要素はドラッグできるようになります。この属性が設定されていない、あるいは false に設定されている場合、その要素をドラッグする事はできず、代わりにテキストが選択されるでしょう。 {{htmlattrxref("draggable")}} 属性は画像やリンクを含めてあらゆる要素に設定できます。ただし、画像とリンクについてだけは初期値がtrueとなっていますので、実際にこれらの要素で使う場合は、要素をドラッグできないようにするために {{htmlattrxref("draggable")}} 属性に false を設定するという場合がほとんどでしょう。

+ +

要素がドラッグ可能になった場合、文字列やその要素に含まれている他の要素が、マウスによるクリックやドラッグなどの通常の操作では選択する事ができなくなることに注意してください。ユーザーが文字列を選択するには、通常の操作の代わりに、 Alt キーを押しながらマウスで選択するか、キーボードで操作を行う必要があります。

+ +

XUL 要素では、 {{htmlattrxref("draggable")}} 属性を使う必要はありません。全ての XUL 要素はドラッグ可能です。

+ +
<button label="ドラッグしてください" ondragstart="event.dataTransfer.setData('text/plain', '「ドラッグしてください」ボタン');">
+
+ +

ドラッグ操作の開始

+ +

この例では、 {{domxref("GlobalEventHandlers.ondragstart","ondragstart")}} 属性を使って、 {{event("dragstart")}} イベントのためのリスナーが追加されています。

+ +
<div draggable="true" ondragstart="event.dataTransfer.setData('text/plain', 'この文字列はドラッグができます')">
+  この文字列はドラッグが<strong>できます</strong>。
+</div>
+
+ +

ユーザーがドラッグを開始しようとした時、 {{event("dragstart")}} イベントが発行されます。この例では {{event("dragstart")}} のリスナーは、ドラッグされる要素自身に追加されていますが、他の多くのイベントがそうであるようにドラッグイベントもバブリングしますので、より上位の祖先要素でイベントを監視することもできます。 {{event("dragstart")}} イベントでは、以下で解説している「ドラッグデータ」「フィードバック画像」「ドラッグの種類」を設定することができます。ドラッグデータの指定は必須ですが、多くの状況では、フィードバック画像とドラッグの種類は既定のもので問題ありません。

+ +

ドラッグデータ

+ +

全ての{{domxref("DragEvent","ドラッグイベント")}}は、ドラッグデータを保持するための {{domxref("DragEvent.dataTransfer","dataTransfer")}} と呼ばれるプロパティを持っています(dataTransfer は {{domxref("DataTransfer")}} オブジェクトの一つです)。

+ +

ドラッグが行われた時には、何がドラッグされているのかを識別するデータが、そのドラッグに対して関連付けられなくてはなりません。例えば、テキストボックスの中の選択された文字列がドラッグされた時は、ドラッグに関連付けられたデータは、文字列それ自体となります。同様に、ウェブページの中のリンクがドラッグされた時は、リンク先の URL がドラッグデータとなります。

+ +

ドラッグデータは、データの型(データの形式)と、データの値の、2つの情報を含んでいます。データの形式はタイプ文字列(テキストデータを示すtext/plainなどのような)で指定し、データの値は文字列で指定します。ドラッグが開始された時、あなたはデータを型と値の設定で指定するでしょう。ドラッグが行われている間、dragenterおよびdragoverイベントのイベントリスナーにおいて、あなたはデータの型を、ドロップが許可されているかどうかの判定に使うでしょう。具体例としては、リンクのドロップを受け付けるドロップターゲットは、リンクの型である text/uri-list かどうかを確認するでしょう。dropイベントにおいてはリスナーは、この型の情報を元にドラッグされたデータを取得して、ドロップ位置に挿入するでしょう。

+ +

型は、 text/plainimage/jpeg などのような、 MIME-type に似た形式の文字列で、独自の型を作ることもできます。広く一般的に使われている型の一覧がドラッグ型のページにあります。

+ +

一つのドラッグ操作で、複数の異なる形式のデータを提供できます。この仕組みにより、独自の形式や、その形式のデータを受け取れない要素向けのフォールバック用の形式など、データをより適切な形式で引き渡すことができます。通常、最後のフォールバック先として使われる形式は、 text/plain 型として表される普通のテキストデータです。このデータは元のテキストの単純な文字列となるでしょう。

+ +

データを {{domxref("DragEvent.dataTransfer","dataTransfer")}} に設定するには、 {{domxref("DataTransfer.setData","setData()")}} メソッドを使います。このメソッドは、データの型とデータの値の、2つの引数を取ります。例:

+ +
event.dataTransfer.setData("text/plain", "ドラッグされたテキスト");
+
+ +

この例では、データの値は「ドラッグされたテキスト」で、形式は text/plain です。

+ +

データは複数の形式で提供できます。これを実現するには、異なる形式を指定して {{domxref("DataTransfer.setData","setData()")}} メソッドを複数回呼び出します。最も具体的な形式から、具体的でない形式に向けて呼び出します。

+ +
var dt = event.dataTransfer;
+dt.setData("application/x-bookmark", bookmarkString);
+dt.setData("text/uri-list", "http://www.mozilla.org");
+dt.setData("text/plain", "http://www.mozilla.org");
+
+ +

これは、3つの異なる型のデータを追加する例です。最初の型の「application/x-bookmark」は独自の形式です。他のアプリケーションはこの形式をサポートしていないでしょうが、同じウェブサイトやアプリケーションの中の領域同士でのドラッグでは、このような独自の形式を利用できます。また、他の型でもデータを提供することで、このような独自形式をサポートしていない他のアプリケーション向けにも、代替の形式でドラッグできるようになります。「application/x-bookmark」型はそのアプリケーションの中ではより使いやすく詳細な情報を提供できますが、他の型で渡されるデータは、単純な1つの URL もしくは文字列となります。

+ +

なお、この例では text/uri-listtext/plain も同じデータを含んでいます。このようにすることが多いのですが、こうしなければならない訳ではありません。

+ +

同じ形式で2回データを登録すると、古いデータは新しいデータによって置き換えられますが、データの形式の登録の順番自体は古いデータを登録した時のままになります。

+ +

登録したデータは {{domxref("DataTransfer.clearData","clearData()")}} メソッドによって削除できます。このメソッドは、削除するデータの形式を引数として求めます。

+ +
event.dataTransfer.clearData("text/uri-list");
+
+ +

{{domxref("DataTransfer.clearData","clearData()")}} メソッドの引数によるデータ形式の指定は省略可能です。データの形式が指定されなかった時は、全ての型のデータが削除されます。ドラッグ開始時にデータが1つも登録されなかった場合、もしくは後の処理で全てのデータが削除された場合、ドラッグ操作は発生しません。

+ +

ドラッグフィードバック画像の設定

+ +

ドラッグが行われた時、ドラッグ元(dragstartイベントが発行された要素)を元にして OS によって画像が生成され(例えば Windows では半透明の画像になります)、ドラッグしている間マウスポインターに伴って表示されます。この画像は自動的に生成されるため、あなたが用意する必要はありません。しかし、 {{domxref("DataTransfer.setDragImage","setDragImage()")}} によって、独自のドラッグ中のフィードバック画像を指定することができます。

+ +
event.dataTransfer.setDragImage(image, xOffset, yOffset);
+
+ +

このメソッドは3つの引数を要求します。第1引数は一般的には画像の要素ですが、 canvas 要素やその他の要素を指定することもできます。フィードバック画像は、その画像が画面上で表示される場合と同じ形・原寸大で生成されます。 {{domxref("DataTransfer.setDragImage","setDragImage()")}} の第2、第3引数は画像を表示するマウスポインターからの相対オフセットです。

+ +

文書中に存在しないものをフィードバック画像として使うために、以下の例のようにして、画像や canvas を利用することもできます。

+ +
function dragWithCustomImage(event) {
+  var canvas = document.createElementNS("http://www.w3.org/1999/xhtml","canvas");
+  canvas.width = canvas.height = 50;
+
+  var ctx = canvas.getContext("2d");
+  ctx.lineWidth = 4;
+  ctx.moveTo(0, 0);
+  ctx.lineTo(50, 50);
+  ctx.moveTo(0, 50);
+  ctx.lineTo(50, 0);
+  ctx.stroke();
+
+  var dt = event.dataTransfer;
+  dt.setData('text/plain', 'ドラッグされるデータ');
+  dt.setDragImage(canvas, 25, 25);
+}
+
+ +

この例では、 canvas の大きさは幅50ピクセル・高さ50ピクセルで、オフセット値はそれぞれの半分の値(各25ピクセル)となっており、画像はマウスポインターの中央に表示されます(マウスポインターが画像の中央に表示されます)。

+ +

{{h2_gecko_minversion("Using XUL panels as drag images", "9.0")}}

+ +

Gecko の開発者(アドオンまたは Mozilla アプリケーションコードのどちらかを開発している人)の場合、 Gecko 9.0 {{geckoRelease("9.0")}} は XUL {{XULElem("panel")}} 要素をドラッグフィードバック画像として使用することの対応を追加します。 {{domxref("DataTransfer.setDragImage","setDragImage()")}} に {{XULElem("panel")}} 要素に渡すだけです。

+ +

この XUL {{XULElem("panel")}} を考えてみてください。

+ +
<panel id="panel" style="opacity: 0.6">
+  <description id="pb">Drag Me</description>
+</panel>
+
+<vbox align="start" style="border: 1px solid black;" ondragstart="startDrag(event)">
+  <description>Drag Me</description>
+</vbox>
+
+ +

ユーザーが上記の {{XULElem("vbox")}} をクリックしてドラッグを始めると、以下の startDrag() 関数が呼び出されます。

+ +
function startDrag(event) {
+  event.dataTransfer.setData("text/plain", "<strong>Body</strong>");
+  event.dataTransfer.setDragImage(document.getElementById("panel"), 20, 20);
+}
+
+ +

これは "<strong>Body</strong>" という文字列が HTML 形式で入った panel をドラッグ画像として使用します。パネルをテキストエディタ―にドロップすると、 "Body" という文字列がテキスト中のドロップした場所に挿入されます。

+ +

ドラッグの種類

+ +

ドラッグを行う時の操作には、いくつかの種類があります。 copy (コピー)はドラッグされているデータが現在の場所からドロップ先の場所にコピーされることを示します。 move (移動)はドラッグされているデータがドロップ先に移動されることを示し、 link (リンク)はドラッグ元とドロップ先の場所との間に何らかの形での関連付けや繋がりが作られることを示します。

+ +

{{event("dragstart")}} イベントのリスナーにおいて、 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} プロパティに値を設定することで、 ドラッグ元について上記の3つの操作のうちどれが許可されているのかを示すことができます。

+ +
event.dataTransfer.effectAllowed = "copy";
+
+ +

この例では、コピーのみが許可されています。複数の種類の操作を組み合わせることもできます。

+ +
+
none
+
どの操作も許可されていない(ドロップを禁止)。
+
copy
+
コピーのみが許可されている。
+
move
+
移動のみが許可されている。
+
link
+
リンクのみが許可されている。
+
copyMove
+
コピーまたは移動のみが許可されている。
+
copyLink
+
コピーまたはリンクのみが許可されている。
+
linkMove
+
リンクまたは移動のみが許可されている。
+
all
+
コピー、移行、リンクの全ての操作が許可されている。
+
+ +

上に列挙されている値のいずれかと全く等しい値だけが利用可能であることに注意してください。 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} プロパティを copyMove に設定すると、コピーや移動の操作を許可しますが、ユーザーがリンク操作を行うことを防ぐことができます。 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} プロパティを変更しない場合、「all」が指定された時と同様に、全ての操作が許可されます。ですので、特定の種類の操作を除外したい場合を除いて、プロパティの値を手動で設定する必要はありません。

+ +

ドラッグ操作の間、 {{event("dragenter")}} または {{event("dragover")}} イベントのリスナーは、操作が許可されているかどうかを確かめるために {{domxref("DataTransfer.effectAllowed","effectAllowed")}} プロパティを参照できます。これらのイベントにおいて、関連するプロパティである {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティへ、実際に行われる操作の種類1つだけが指定されるべきです。 {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティの値として妥当な物は、nonecopymove、またはlinkのみです。このプロパティへは、複数の操作を組み合わせた値は指定できません。

+ +

{{event("dragenter")}} および {{event("dragover")}} イベントにおいて、 {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティはユーザーが要求している操作に初期化されます。ユーザーは操作の種類を修飾キーを押すことにより変更することができます。実際に使用されるキーはプラットフォームごとに異なりますが、大抵の場合は Shift キーと Control キーが、コピー・移動・リンクの各操作の切り替えに使われるでしょう。マウスポインターはどの操作が望まれているのかを示すために、例えばコピーならカーソルの横に「+」記号が表示される、といった風に変化するでしょう。

+ +

{{event("dragenter")}} または {{event("dragover")}} イベントの間に {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティの値を変更すると、ユーザーが選択した操作の種類を上書きし、特定のドロップ操作を強制することができます。この時に指定できる操作の種類は、 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} プロパティの値として列挙されている操作に含まれていなくてはならないことに注意してください。それ以外の値を設定した場合は、許可されている操作の中から代わりの値が設定されます。

+ +
event.dataTransfer.dropEffect = "copy";
+
+ +

この例では、「コピー」が行なわれる効果です。

+ +

その場所へのドロップが禁止されていることを示すために、値として none を設定することもできます。

+ +

{{event("drop")}} および {{event("dragend")}} イベントの中では、 {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティをチェックすることで最終的に選択されている効果を特定できます。選択された効果が「move」であれば、 {{event("dragend")}} イベントの中でドラッグ元から元のデータを削除するべきです。

+ +

ドロップ先の指定

+ +

{{event("dragenter")}} および {{event("dragover")}} イベントのリスナーは、ドラッグされている項目がどの場所にドロップされようとしているのかを正確に示す働きをすることが多いです。ウェブページやアプリケーションのほとんどの領域は、ドロップデータを受け取る場所としては不適切です。従って、これらのイベントに対する既定の動作はドロップを禁止する働きをします。

+ +

ドロップを許可したい場合、イベントをキャンセルして既定の動作を無効化する必要があります。属性値として定義されたイベントリスナーで false を返すか、イベントの {{domxref("Event.preventDefault","preventDefault()")}} メソッドを呼ぶことで、既定の動作を無効にできます。別のファイルに分けられたスクリプトで機能を定義する場合は、後者の方が便利でしょう。

+ +
<div ondragover="return false">
+<div ondragover="event.preventDefault()">
+
+ +

{{event("dragenter")}} および {{event("dragover")}} イベントのどちらにおいても、 {{domxref("Event.preventDefault","preventDefault()")}} メソッドを呼び出すと、その場所がドロップ可能な場所であるということを示します。多くの場合は、例えばリンクがドラッグされている時だけなど、特定の状況でのみ {{domxref("Event.preventDefault","preventDefault()")}} メソッドを呼び出したいと思うでしょう。これを実現するには、条件を確かめて、条件が満たされている時だけイベントをキャンセルするような関数を使って下さい。条件が満たされていない時はイベントをキャンセルしないでおけば、ユーザーがマウスのボタンを放してもその場所へのドロップは行われません。

+ +

ドロップを受け付けるか拒絶するかを決める最も一般的な方法は、データ転送の仕組みに含まれているドラッグデータの型を判別するものです。例えば、画像やリンク、もしくはその両方のみを受け付けるといった事ができます。これを実現するには、イベントの {{domxref("DragEvent.dataTransfer","dataTransfer")}} (プロパティ)の {{domxref("DataTransfer.types","types")}} プロパティを確認します。 {{domxref("DataTransfer.types","types")}} プロパティはドラッグが開始された時に登録されたタイプ文字列のリストで、最も適切なものから最も適切でないものの順で並んでいます。

+ +
function contains(list, value) {
+    for( var i = 0; i < list.length; ++i ) {
+        if(list[i] === value) return true;
+    }
+    return false;
+}
+
+function doDragOver(event) {
+  var isLink = contains( event.dataTransfer.types, "text/uri-list");
+  if (isLink) {
+    event.preventDefault();
+  }
+}
+ +

この例では、型のリストの中に text/uri-list 型があるかどうかを確認するために contains メソッドを使用しています。もし条件が真であれば、イベントはキャンセルされて、ドロップが許可されるでしょう。もしドラッグデータがリンクを含んでいなければ、イベントはキャンセルされず、その場所でのドロップも行われません。

+ +

実際に行われる処理の種類をより適切に示すために、 {{domxref("DataTransfer.effectAllowed","effectAllowed")}} や {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティのいずれか、あるいはその両方に値を指定したいと思う事もあるでしょう。当然ですが、イベントをキャンセルするのを忘れると、これらのプロパティの値を変えても何も起こりません。

+ +

DataTransfer.types の更新

+ +

なお、最新の仕様書では {{domxref("DataTransfer.types")}} は {{domxref("DOMStringList")}} ではなく {{domxref("DOMString")}} の凍結した配列を返すべきだとしています(Firefox 52 以降で対応されました)。

+ +

結果として、 contains メソッドはこのプロパティでは動作しなくなりました。特定の種類のデータが提供されているかをチェックするためには、代わりに includes メソッドを使用してください。以下のようなコードを使用します。

+ +
if ([...event.dataTransfer.types].includes('text/html')) {
+  // Do something
+}
+ +

types がどちらのメソッドに対応しているかを判別する機能を使用すれば、適切なコードを実行できます。

+ +

ドロップのフィードバック

+ +

その場所へのドロップが許可されていることをユーザーに示す方法はいくつかあります。マウスポインターは {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティの値に応じて適切なものに変化します。実際の正確な表示のされ方はユーザーのプラットフォームに依存しますが、通常は例えば「コピー」に対しては「+」記号が表示され、また、ドロップが許可されていない時は「ここにはドロップできません」という意味のアイコンが表示されるでしょう。多くの場合において、このポインターによるフィードバックは十分に役立ちます。

+ +

それ以外にも必要に応じて、ユーザーインターフェースを更新して挿入箇所を示したりハイライト表示したりすることもできます。単にハイライト表示するだけであれば、ドロップ対象においてCSSの-moz-drag-over疑似クラスが利用できます。

+ +
.droparea:-moz-drag-over {
+  border: 1px solid black;
+}
+
+ +

この例においてdropareaクラスの要素は、 {{event("dragenter")}} イベントの中で {{domxref("Event.preventDefault","preventDefault()")}} メソッドが呼ばれて有効なドロップ対象となっている間、1ピクセルの黒い枠が表示されます。この疑似クラスは {{event("dragover")}} イベントでの状態の変化には反応しませんので、この疑似クラスでの指定を適用させるには {{event("dragenter")}} イベントをキャンセルしなくてはならない事に注意してください。

+ +

より凝った視覚効果のために、例えばドロップが行われる位置に要素を挿入するなど、 {{event("dragenter")}} イベントの間に他の操作をすることもできます。この例なら、挿入される要素は、挿入箇所を示すマーカーあるいはドラッグされている要素が新しい位置に挿入された時の状態のプレビューなどとして利用できるでしょう。このような効果は、例えば imageseparator を生成して、 {{event("dragenter")}} イベントの処理中にドキュメント中に単に挿入するだけで実現できます。

+ +

{{event("dragover")}} イベントは、マウスポインターが現在指している要素において発行されます。挿入点のマーカーを {{event("dragover")}} イベントの発行に応じて移動させたいと思うのは自然な欲求でしょう。そのような場合には、他のマウスイベントでマウスポインターの位置を取得するために使われるのと同じ要領で、イベントの {{domxref("MouseEvent.clientX","clientX")}} と {{domxref("MouseEvent.clientY","clientY")}} プロパティを利用できます。

+ +

最後に、ドラッグ中にマウスポインターが要素の上を離れる時、 {{event("dragleave")}} イベントが発行されます。これは挿入点のマーカーやハイライト表示を消すのにちょうどいいタイミングです。このイベントをキャンセルする必要はありません。 -moz-drag-over 疑似クラスを使って指定されたハイライト表示やその他の視覚効果は、すべて自動的に消去されます。 {{event("dragleave")}} イベントは、ドラッグがキャンセルされた時でも常に発行されますので、このイベントによって、挿入点の消去などを確実に行うことができます。

+ +

ドロップの実行

+ +

ユーザーがマウスのボタンを放した時、ドラッグ&ドロップの操作は終了します。有効なドロップ対象となっている要素の上でマウスのボタンが放された場合、最後の {{event("dragenter")}} と {{event("dragover")}} イベントはキャンセルされて、ドロップが成功し、 {{event("drop")}} イベントがそのドロップ対象において発行されます。それ以外の場所でボタンが放された場合は、ドラッグ操作はキャンセルされ、 {{event("drop")}} イベントは発行されません。

+ +

{{event("drop")}} イベントの間、あなたはドロップされたデータをイベントから取得して、ドロップ位置に挿入することになります。どのドラッグ&ドロップ操作が望まれていたのかは、 {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティで判別することができます。

+ +

すべてのドラッグ&ドロップ関連のイベントにおいて、イベントの {{domxref("DragEvent.dataTransfer","dataTransfer")}} プロパティはドラッグされた対象に関するデータを保持しています。データの取得には {{domxref("DataTransfer.getData","getData()")}} メソッドを利用することになるでしょう。

+ +
function onDrop(event) {
+  var data = event.dataTransfer.getData("text/plain");
+  event.target.textContent = data;
+  event.preventDefault();
+}
+
+ +

{{domxref("DataTransfer.getData","getData()")}} メソッドは、取得したいデータの型を引数として取ります。実行すると、ドラッグ操作の開始時に {{domxref("DataTransfer.setData","setData()")}} メソッドによって登録された値が文字列として返されます。その型に対するデータが存在しない場合は、空文字が返されます。当然ながら、直前の {{event("dragover")}} イベントでの処理においてチェックした時と同様に、あなたはデータの正しい形式が利用可能かどうかを知りたいと思うでしょう。

+ +

上記の例では、まずデータを取得し、ドロップ対象の内容テキストとしてそれを挿入しています。これは p 要素や div 要素がドロップ対象の領域として使われる事を想定しており、ドラッグされたテキストをドロップ位置に挿入するという効果をもたらします。

+ +

ウェブページにおいては、ドロップを受け付けた場合、イベントの {{domxref("Event.preventDefault","preventDefault()")}} メソッドを呼び出すべきです。これによって、ブラウザ内でのドロップ時の既定の挙動がキャンセルされます。例えば、リンクがウェブページにドロップされた場合、 Firefox はそのリンク先を読み込もうとします。イベントをキャンセルすることで、この動作は抑止されます。

+ +

他の形式でデータを取得することもできます。データがリンクであった場合、そのデータは text/uri-list 型でも提供されているでしょう。その場合、リンクを内容に挿入することができます。

+ +
function doDrop(event) {
+  var lines = event.dataTransfer.getData("text/uri-list").split("\n");
+  for (let line of lines) {
+    if (line.startsWith("#"))
+      continue;
+
+    let link = document.createElement("a");
+    link.href = line;
+    link.textContent = line;
+    event.target.appendChild(link);
+  }
+  event.preventDefault();
+}
+
+ +

この例は、ドラッグされたデータからリンクを挿入します。名前から想像できる通り、 text/uri-list 型は実際に複数のURLの改行区切りのリストを含んでいる場合があります。このコードでは、 split を使って文字列を行ごとに分割し、各行に繰り返し処理を行って、それぞれをリンクとして文書中に挿入しています。ナンバー記号(#)で始まる物はコメントとして除外していることに注意してください。

+ +

単純な使い方として、リストの中の最初の有効なURLを取得するために、特別な型 URL も利用できます。例:

+ +
var link = event.dataTransfer.getData("URL");
+
+ +

これによって、コメントの除外などの処理は一切不要になります。しかし、これはリストの中の最初の URL だけしか取得できないという制限があります。

+ +

URL 型は特別な省略表記用の型で、 {{domxref("DataTransfer.types","types")}} プロパティで取得できる型のリストには列挙されません。

+ +

時には、複数の形式をサポートして、そのうち最も適切な形式で提供されたデータを取得したいと思う事もあるでしょう。以下の例では、3つの形式がドロップ対象によってサポートされています。

+ +

以下の例は、提供されたデータの中で最も適切なデータを返す例です。

+ +
function doDrop(event) {
+  var types = event.dataTransfer.types;
+  var supportedTypes = ["application/x-moz-file", "text/uri-list", "text/plain"];
+  types = supportedTypes.filter((value) => types.includes(value));
+  if (types.length)
+    var data = event.dataTransfer.getData(types[0]);
+  event.preventDefault();
+}
+
+ +

この例は Firefox 3 で利用可能な JavaScript の拡張された機能を使って書かれていますが、他の環境でも動作する様に書き換えることもできます。

+ +

ドラッグの終了

+ +

1回のドラッグ操作が終了すると、 {{event("dragend")}} イベントがドラッグ元( {{event("dragstart")}} イベントが発行されるのと同じ要素)において発行されます。このイベントは、ドラッグ操作が成功したかキャンセルされたかに関わらず発行されます。どの操作が行われたのかは、 {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティを参照して知ることができます。

+ +

{{event("dragend")}} イベントにおいて {{domxref("DataTransfer.dropEffect","dropEffect")}} プロパティの値がnoneである場合、ドラッグ操作がキャンセルされたことを意味します。それ以外の場合は、プロパティの値は実際に行われた操作の種類を示します。ドラッグ元はこの情報に基づいて、ドラッグされた項目を「移動」の操作の後に元の場所から削除することができます。 {{domxref("DataTransfer.mozUserCancelled","mozUserCancelled")}} プロパティの値は、ユーザーが(Escapeキーを押すなどして)ドラッグ操作をキャンセルした場合は true となり、不正なドロップ先だった場合などの他の理由でドラッグ操作がキャンセルされた場合や、ドロップに成功した場合はfalseとなります。

+ +

ドロップ操作は同じウィンドウの中または他のアプリケーションの上で行われ得ます。いずれの場合も常に {{event("dragend")}} イベントは発行されます。このイベントの {{domxref("MouseEvent.screenX","screenX")}} および {{domxref("MouseEvent.screenY","screenY")}} プロパティの値には、ドロップが行われたときの画面上での座標が設定されます。

+ +

{{event("dragend")}} イベントの伝搬が終了した後、ドラッグ&ドロップの操作は完了します。

+ +

[1] Gecko では、元のノードがドラッグ中(例えばドロップ中や {{event("dragover")}})に移動したり削除されたりした場合、 {{event("dragend")}} が発行されません。 bug 460801

+ +

関連情報

+ + diff --git a/files/ja/web/api/html_drag_and_drop_api/multiple_items/index.html b/files/ja/web/api/html_drag_and_drop_api/multiple_items/index.html new file mode 100644 index 0000000000..aadaeb095d --- /dev/null +++ b/files/ja/web/api/html_drag_and_drop_api/multiple_items/index.html @@ -0,0 +1,108 @@ +--- +title: 複数の項目のドラッグ&ドロップ +slug: DragDrop/Dragging_and_Dropping_Multiple_Items +translation_of: Web/API/HTML_Drag_and_Drop_API/Multiple_items +--- +

{{ Fx_minversion_header(3.5) }} Mozillaはいくつかの非標準の機能によって、複数の項目のドラッグをサポートしています。それらの機能はtypesプロパティやgetDatasetDataclearDataの各メソッドに酷似していますが、データの取得や変更、削除の際などに項目のインデックスを追加の引数として要求します。

+

mozSetDataAtを使うと、dragstartイベントで複数の項目を登録することができます。これはsetDataメソッドとよく似た働きをします。

+
var dt = event.dataTransfer;
+dt.mozSetDataAt("text/plain", "ドラッグされるデータ", 0);
+dt.mozSetDataAt("text/plain", "ドラッグされる2つめのデータ", 1);
+
+

この例では2つのドラッグ項目を追加しています。最後の引数は追加する項目のインデックスを示しています。これらの項目は0番から順番に登録するべきで、最後の方(インデックスの大きなもの)から逆順に登録することはできません。また、すでにデータが登録されているインデックスを指定してもう1度データを登録すると、前に登録したデータを置き換えることができます。インデックスとして0を指定すると、setDataメソッドを呼んだのと等しく扱われます。

+

mozClearDataAtメソッドを使って、指定した項目を削除することもできます。

+
event.dataTransfer.mozClearDataAt("text/plain", 1);
+
+

あるインデックスで示される項目について、最後のデータ形式の削除によって項目全体を削除すると、残りの項目が繰り上がって項目のインデックスが変わることに注意してください。例えば、

+
var dt = event.dataTransfer;
+dt.mozSetDataAt("text/uri-list", "URL1", 0);
+dt.mozSetDataAt("text/plain",    "URL1", 0);
+dt.mozSetDataAt("text/uri-list", "URL2", 1);
+dt.mozSetDataAt("text/plain",    "URL2", 1);
+dt.mozSetDataAt("text/uri-list", "URL3", 2);
+dt.mozSetDataAt("text/plain",    "URL3", 2);
+// [item1] data=URL1, index=0
+// [item2] data=URL2, index=1
+// [item3] data=URL3, index=2
+
+

このように2つの形式で提供されたデータを持つ3つの項目を登録した後で、

+
dt.mozClearDataAt("text/uri-list", 1);
+dt.mozClearDataAt("text/plain", 1);
+
+

このように2番目の項目についてすべての形式のデータを削除すると、3番目だった項目が繰り上がって2番目の項目になり、インデックスが2から1に変わります。

+
// [item1] data=URL1, index=0
+// [item2] data=URL3, index=1
+
+

幸いなことに、通常は項目を削除する必要がある場合は希で、それよりも、必要に応じて項目を追加するだけの場合の方がずっと多いです。

+

複数の項目のドラッグが使われる場合の代表は、複数のファイルやブックマークをドラッグする時です。この場合には、適切な形式でそれらの項目を追加してください。また必須ではありませんが、それぞれの項目は常に同じ形式でデータを追加するべきです。これによりドロップ対象は、一貫したデータの受け取りを期待できます。

+

複数のファイルがドラッグされているかどうかを確認するには、mozItemCountプロパティを調べます。このプロパティにはドラッグされている項目の数がセットされます。もしそのドロップ対象が1つの項目のドロップだけを受け付ける場合には、ドラッグされた項目すべてを拒否することもできますし、最初の項目だけを受け取ることもできます。複数の項目の受け取りを拒否するには、dragoverイベントをキャンセルしないか、effectAllowedプロパティにnoneを指定します。他のイベントリスナがすでにイベントをキャンセルしている場合に備えて、両方を実行しても構いません。

+

ドロップされた項目のうち最初の項目だけを扱う場合は、1つだけの項目のドラッグの場合と同様にgetDataを使います。これは、何も追加の処理が必要ないドロップ項目を1つだけ受け取るドロップ対象のために有用です。

+

それに対して、任意のインデックスの項目をデータトランスファーから取得するにはmozGetDataAtメソッドを使います。以下の例は、ドラッグされたファイルを取得し、それらを配列に追加するものです。

+
function onDrop(event)
+{
+  var files = [];
+  var dt = event.dataTransfer;
+  for (var i = 0; i < dt.mozItemCount; i++)
+    files.push(dt.mozGetDataAt("application/x-moz-file", i));
+}
+
+

mozTypesAtメソッドを使って、望んでいる形式のデータが存在しているかどうかを確かめたいとも思うでしょう。typesプロパティと同様に、このメソッドは、その項目が保持しているデータの型の文字列を返します。typesプロパティを取得する事は、インデックスが0の項目の型のリストを取得する事に等しいです。

+
var types = event.dataTransfer.mozTypesAt(1);
+
+

文字列でないデータのドラッグ

+

上で解説した追加のメソッドが扱えるデータは文字列に限定されず、どんな種類のデータでも指定することができます。例えば、ファイルはapplication/x-moz-file型でnsIFileのオブジェクトとして保持されてドラッグされます。setDataメソッドは文字列しかサポートしておらず、 ドラッグするファイルを指定するのには利用できないため、代わりにmozSetDataAtメソッドを使わなくてはなりません。

+
dt.mozSetDataAt("application/x-moz-file", file, 0);
+
+

複数の項目を扱う必要がない場合でも、このメソッドを使うことによって任意のオブジェクトをデータに指定できます。この場合には、インデックスとして0を指定しておきます。

+

同様に、ファイルやその他のオブジェクトを取得するにはmozGetDataAtメソッドを使う必要があります。もしgetDataを使った場合は、値が文字列でない型のデータは空文字として取得されます。ただし、数値のような単純な型のデータについては文字列に変換できるため、この場合はgetDataを使っても問題ありません。

+

複数項目のドロップの例

+

以下は、ドロップされた項目のデータとその形式を一覧表示するボックスの例です。

+
<html>
+<head>
+<script>
+
+function dodrop(event)
+{
+  var dt = event.dataTransfer;
+  var count = dt.mozItemCount;
+  output("Items: " + count + "\n");
+
+  for (var i = 0; i < count; i++) {
+    output(" Item " + i + ":\n");
+    var types = dt.mozTypesAt(i);
+    for (var t = 0; t < types.length; t++) {
+      output("  " + types[t] + ": ");
+      try {
+        var data = dt.mozGetDataAt(types[t], i);
+        output("(" + (typeof data) + ") : <" + data + " >\n");
+      } catch (ex) {
+        output("<<error>>\n");
+        dump(ex);
+      }
+    }
+  }
+}
+
+function output(text)
+{
+  document.getElementById("output").textContent += text;
+  dump(text);
+}
+
+</script>
+</head>
+<body>
+
+<div id="output" style="min-height: 100px; white-space: pre; border: 1px solid black;"
+     ondragenter="document.getElementById('output').textContent = ''; event.stopPropagation(); event.preventDefault();"
+     ondragover="event.stopPropagation(); event.preventDefault();"
+     ondrop="event.stopPropagation(); event.preventDefault(); dodrop(event);">
+<div>
+
+</body>
+</html>
+
+

この例は、preventDefaultメソッドによってdragenterイベントとdragoverイベントを両方ともキャンセルします。これにより、要素の上でのドロップが可能になっています。

+

項目をドロップした時に、dodrop関数が呼ばれます。この関数はmozItemCountプロパティを見て、いくつの項目がドロップされたのかを調べ、それらに繰り返し処理を行います。それぞれの項目について、型の一覧を得るためにmozTypesAtメソッドが呼ばれます。この一覧の生成処理は、ドラッグに対して関連づけられたすべてのデータに対して繰り返されます。

+

この例は、あるドラッグ操作が保持しているデータを確かめたい時に便利です。ただ項目をこの例のドロップ対象にドロップするだけで、ドラッグされたどの項目がどんな形式でどのようなデータを保持しているのかを見ることができます。

+

{{ languages( { "en": "En/DragDrop/Dragging_and_Dropping_Multiple_Items" } ) }}

diff --git a/files/ja/web/api/html_drag_and_drop_api/recommended_drag_types/index.html b/files/ja/web/api/html_drag_and_drop_api/recommended_drag_types/index.html new file mode 100644 index 0000000000..eb8487d158 --- /dev/null +++ b/files/ja/web/api/html_drag_and_drop_api/recommended_drag_types/index.html @@ -0,0 +1,228 @@ +--- +title: 推奨されるドラッグのデータ型 +slug: DragDrop/Recommended_Drag_Types +tags: + - Guide + - drag and drop +translation_of: Web/API/HTML_Drag_and_Drop_API/Recommended_drag_types +--- +

{{DefaultAPISidebar("HTML Drag and Drop API")}}

+ +

HTML Drag and Drop API は、プレーンテキスト、URL、HTML コード、ファイルなど、さまざまな形式のデータのドラッグをサポートしています。このドキュメントでは、一般的なドラッグ可能なデータ形式のベストプラクティスについて説明しています。

+ +
+

注意事項:
+ mozSetDataAt() のような moz プレフィックスを持つこのドキュメントのすべてのメソッドとプロパティは、Gecko ベースのブラウザでのみ動作します。

+
+ +

テキストのドラッグ

+ +

テキストをドラッグする時は、text/plain 型を使用します。2番目の引数には、ドラッグした文字列を指定します。例えば、以下のようになります。

+ +
event.dataTransfer.setData("text/plain", "これはドラッグされるテキストです");
+
+ +

Web ページのテキストボックスや選択範囲の文字列のドラッグは、ブラウザが自動的に処理を行うので、自分で処理する必要はありません。

+ +

そのデータが代替テキストでは表現できない物である場合を除いて、他のデータ形式をサポートしないアプリケーションやドロップ対象のためのフォールバック用に、常に text/plain 型のデータを提供することをおすすめします。そのために、データを追加する時には最後に text/plain 型のデータを登録しておいてください。

+ +

注: 古いコードにおいて、text/unicodetext といった型の記述を見かけることがあるかもしれません。これらはどちらも text/plain と等しく扱われ、プレーンテキスト型のデータとして登録・取得されます。

+ + + +

ドラッグされたハイパーリンクには、text/uri-listtext/plain2種類のデータを含める必要があります。どちらの形式もリンクの URL をデータに使用しなければなりません。例えば、以下のようになります。

+ +
var dt = event.dataTransfer;
+dt.setData("text/uri-list", "https://www.mozilla.org");
+dt.setData("text/plain", "https://www.mozilla.org");
+
+ +

text/uri-list 型のフォールバックとして、text/plain 型を最後に設定します。

+ +

注:URL 用の型は uri-list-list で、L ではなく I であることに注意してください。

+ +

複数のリンクをドラッグするには、それぞれのリンクを text/uri-list データ内で CRLF 改行で区切ってください。ナンバー記号 (#) で始まる行はコメントで、有効な URL として扱われません。コメントは、リンクの目的を示したり、リンクに関連づけられたタイトルを保持したりする目的で利用できます

+ +
+

複数のリンクのための text/plain 型のフォールバックは、すべての URL を含むべきですが、コメントを含めるべきではありません。

+
+ +

例えば、以下のサンプル text/uri-list データには、2つのリンクと1つのコメントが含まれています。

+ +
http://www.mozilla.org
+#2つ目のリンク
+http://www.example.com
+
+ +

ドロップされたリンクを取得する時は、コメントを含めて複数のリンクをドラッグした場合の処理を確実に行ってください。便宜上、text/uri-list 型のデータ内の最初の有効なリンクを参照するために、特別な型として URL を使用することができます。

+ +
+

URL 型でデータを追加しないでください - それを行うと、代わりに text/uri-list 型のデータとして登録されます。

+
+ +
var url = event.dataTransfer.getData("URL");
+
+ +

Mozilla 特有の型として、text/x-moz-url 型のデータを見かけることがあるかもしれません。この型が表示される場合は、text/uri-list 型の前に表示されるはずです。この型のデータは、リンクの URL に続いてリンクのタイトルが保持されており。例えば、以下のようになります。

+ +
http://www.mozilla.org
+Mozilla
+http://www.example.com
+Example
+
+ +

HTMLとXMLのドラッグ

+ +

HTML の内容は text/html 型を使用します。この型のデータはドラッグされる HTML をシリアライズしたものであるべきです。具体的には、この型のデータとして登録されるのに適した値は、要素の {{domxref("Element.innerHTML","innerHTML")}} プロパティの値です。

+ +

XML の内容は text/xml 型を使用することができますが、内容は整形式の XML に変換しておくべきです。

+ +

また、text/plain 型を使用して、HTML または XML のプレーンテキストでの表現を提供することもできます。その場合のデータは単純なテキストであるべきで、タグや属性などのソース文字列を含めるべきではありません。例えば、以下のようになります。

+ +
var dt = event.dataTransfer;
+dt.setData("text/html", "こんにちは、<strong>見知らぬ人</strong>");
+dt.setData("text/plain", "こんにちは、見知らぬ人");
+
+ +

ファイルのドラッグ

+ +

ローカルのファイルは application/x-moz-file 型で、 nsIFile のオブジェクトとしてドラッグされます。特権を持っていない Web ページでは、この型のデータを取得することも変更することもできません。

+ +

ファイルを文字列にはできないため、データを登録するには {{domxref("DataTransfer.mozSetDataAt","mozSetDataAt()")}} メソッドを使用する必要があります。同様に、データを取得するには {{domxref("DataTransfer.mozGetDataAt","mozGetDataAt()")}} メソッドを使わなくてはなりません。

+ +
event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
+
+ +

可能であれば、text/uri-list 型と text/plain 型の両方を使ってファイルの URL を含めてください。これらの型は最後に登録されるべきで、それによって、 application/x-moz-file 型は優先度の高い、より適切な型となります。

+ +

複数のファイルは、データ転送中に複数のアイテムとしてドロップ中に受信されます。これについての詳細は、複数の項目のドラッグ&ドロップを参照してください。

+ +

以下の例は、ドロップしたファイルを受信するための領域を作成する方法を示しています。

+ +
<listbox ondragenter="return checkDrag(event)"
+         ondragover="return checkDrag(event)"
+         ondrop="doDrop(event)"/>
+
+<script>
+function checkDrag(event) {
+  return event.dataTransfer.types.contains("application/x-moz-file");
+}
+
+function doDrop(event) {
+  var file = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0);
+  if (file instanceof Components.interfaces.nsIFile) {
+    event.currentTarget.appendItem(file.leafName);
+  }
+}
+</script>
+
+ +

この例では、データ転送に application/x-moz-file 型が含まれている場合にのみ、イベントが false を返します。ドロップイベントの間、ファイル型に関連付けられたデータが取得され、ファイルのファイル名がリストボックスに追加されます。{{domxref("DataTransfer.mozGetDataAt","mozGetDataAt()")}} メソッドは、nsISupports を返すので、nsIFile 型に変換するために、ここでは instanceof 演算子を使用していることに注意してください。これは、誤ってファイルではない型のデータを登録した場合のためのチェックとしても有効です。

+ +

DataTransfer.types の更新

+ +

最新の仕様では、{{domxref("DataTransfer.types")}} は {{domxref("DOMStringList")}} ではなく、{{domxref("DOMString")}} で固定した配列を返すようになっています(これは Firefox 52 以上でサポートされています)。

+ +

その結果、contains メソッドはもう機能しません。代わりに includes メソッドを使用し、以下のようなコードで特定の形式のデータが提供されているかどうかを確認する必要があります。

+ +
if ([...event.dataTransfer.types].includes('text/html')) {
+  // 実行するコード
+}
+ +

特徴検出を使用して、どのメソッドがサポートされているなのかを判断し、適切なコードを実行することができます。

+ +

画像のドラッグ

+ +

画像の直接のドラッグは一般的ではありません。そのため、Mozilla は Mac と Linux での画像の直接のドラッグをサポートしていません。その代わり、画像は通常その URL としてドラッグされます。そのためには、他の URL と同様に text/uri-list 型を使用します。データは、画像の URL、または画像がWeb上やディスク上に無い場合は データ URL である必要があります。

+ +

リンクと同様に、text/plain 型のデータには URL も含まれている必要があります。しかし、データ URL は通常のテキストの内容には有用ではないので、このような状況では text/plain 型のデータを除外した方がよいでしょう。

+ +

Chrome などの特権的なコードでは、画像の種類に応じて、image/jpegimage/pngimage/gif のいずれかの形式を使用することもできます。データは、nsIInputStream インターフェースを実装したオブジェクトでなければなりません。このストリームが読み込まれる時には、そのファイル形式での画像のデータビットを提供しなければなりません。

+ +

画像がディスク上にある場合は、application/x-moz-file 型も含める必要があります。実際に、これは画像ファイルをドラッグする一般的なやり方です。

+ +

最も適切なデータ形式からそうでない形式まで、正しい順序でデータを登録することが重要です。最初に image/jpeg のような標準的な画像型を設定し、次に application/x-moz-file 型を設定します。次に、text/uri-list 型を設定し、最後に text/plain 型を設定します。例えば、以下のようになります。

+ +
var dt = event.dataTransfer;
+dt.mozSetDataAt("image/png", stream, 0);
+dt.mozSetDataAt("application/x-moz-file", file, 0);
+dt.setData("text/uri-list", imageurl);
+dt.setData("text/plain", imageurl);
+
+ +

{{domxref("DataTransfer.mozGetDataAt","mozGetDataAt()")}} メソッドは、テキスト以外のデータに使用されることに注意してください。内容によっては、これらの型の一部しか含まれていない場合があるので、ドロップされた画像を受信する時には、どの型が利用可能になっているかを確認することが重要です。

+ +

ノードのドラッグ

+ +

ドキュメント内のノードや要素は、application/x-moz-node 型を使ってドラッグすることができます。型のデータは DOM ノードでなければなりません。これにより、ドロップ対象はドラッグが開始された実際のノードを受け取ることができます。ノードがドロップされていても、異なるドメインからの呼び出し元はそのノードにアクセスできないことに注意してください。

+ +

ノードの内容は常に text/plain 型の代替文字列で提供するべきです。

+ +

独自データのドラッグ

+ +

独自の目的のために、他の型を使うこともできます。そのデータが特定のサイトやアプリケーションに固有のものでない限り、常に text/plain 型の代替文字列を含めるようにしてください。代替テキストを用意しなかった場合は、他の場所にドロップできなくなります。

+ +

OS のフォルダにファイルをドラッグ

+ +

既存のドラッグイベントセッションにファイルを追加したり、コードが対象フォルダーの場所の通知を受信したときに、オペレーティングシステム内のフォルダーに対してのドロップ操作だった場合、ファイルをディスクに書き出したい場合があります。これは拡張機能(またはその他の特権コード)でのみ動作し、application/moz-file-promise 型を使用する必要があります。次のサンプルでは、この高度なケースの概要を説明します。

+ +
// currentEvent is an existing drag operation event
+
+currentEvent.dataTransfer.setData("text/x-moz-url", URL);
+currentEvent.dataTransfer.setData("application/x-moz-file-promise-url", URL);
+currentEvent.dataTransfer.setData("application/x-moz-file-promise-dest-filename", leafName);
+currentEvent.dataTransfer.mozSetDataAt('application/x-moz-file-promise',
+                  new dataProvider(success,error),
+                  0, Components.interfaces.nsISupports);
+
+function dataProvider(){}
+
+dataProvider.prototype = {
+  QueryInterface : function(iid) {
+    if (iid.equals(Components.interfaces.nsIFlavorDataProvider)
+                  || iid.equals(Components.interfaces.nsISupports))
+      return this;
+    throw Components.results.NS_NOINTERFACE;
+  },
+  getFlavorData : function(aTransferable, aFlavor, aData, aDataLen) {
+    if (aFlavor == 'application/x-moz-file-promise') {
+
+       var urlPrimitive = {};
+       var dataSize = {};
+
+       aTransferable.getTransferData('application/x-moz-file-promise-url', urlPrimitive, dataSize);
+       var url = urlPrimitive.value.QueryInterface(Components.interfaces.nsISupportsString).data;
+       console.log("URL file orignal is = " + url);
+
+       var namePrimitive = {};
+       aTransferable.getTransferData('application/x-moz-file-promise-dest-filename', namePrimitive, dataSize);
+       var name = namePrimitive.value.QueryInterface(Components.interfaces.nsISupportsString).data;
+
+       console.log("target filename is = " + name);
+
+       var dirPrimitive = {};
+       aTransferable.getTransferData('application/x-moz-file-promise-dir', dirPrimitive, dataSize);
+       var dir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile);
+
+       console.log("target folder is = " + dir.path);
+
+       var file = Cc['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);
+       file.initWithPath(dir.path);
+       file.appendRelativePath(name);
+
+       console.log("output final path is =" + file.path);
+
+       // now you can write or copy the file yourself…
+    }
+  }
+}
+
+ +

関連情報

+ + diff --git a/files/ja/web/api/htmlelement/accesskey/index.html b/files/ja/web/api/htmlelement/accesskey/index.html new file mode 100644 index 0000000000..82738c792f --- /dev/null +++ b/files/ja/web/api/htmlelement/accesskey/index.html @@ -0,0 +1,23 @@ +--- +title: Element.accessKey +slug: Web/API/Element/accessKey +translation_of: Web/API/HTMLElement/accessKey +translation_of_original: Web/API/Element/accessKey +--- +
{{APIRef("DOM")}}
+ +
 
+ +
Element.accessKeyは、ユーザが他の要素へジャンプする時に押す、キーストロークを設定します。
+ +
 
+ +
+

Element.accessKey は、ブラウザの既定のキーバインディングと競合する為、めったに使われません。この競合を回避するために、ブラウザはアクセスキーの挙動を他の「最適な」キーと一緒に押されたときに動くように実装しています。( Alt + アクセスキー、の様に。)

+
+ +

See also 

+ + diff --git a/files/ja/web/api/installtrigger/index.html b/files/ja/web/api/installtrigger/index.html new file mode 100644 index 0000000000..6b2353e403 --- /dev/null +++ b/files/ja/web/api/installtrigger/index.html @@ -0,0 +1,15 @@ +--- +title: InstallTrigger オブジェクト +slug: XPInstall_API_Reference/InstallTrigger_Object +--- +

 

+

InstallTrigger

+

ソフトウェアのダウンロードとインストールをする引き金となる Web ページ上のスクリプトには、InstallTrigger オブジェクトを使用します。

+

概要

+

とても簡単なインストール方法は、インストールスクリプトに必要な InstallTrigger オブジェクトを使用するだけです。

+

複雑なインストール方法では、 Install オブジェクトや File オブジェクトを使用する必要があります。どちらの場合も Web ページスクリプトを作成してインストール処理の引き金にします。そのページ内の InstallTrigger メソッドが、指定した XPI ファイルをダウンロードし、その XPI ファイルのトップレベルに置かれた install.js スクリプトを起動する "引き金" になります。

+

InstallTrigger オブジェクト上の最初のメソッドは install です。これは、XPI ファイル形式にまとめられた一つまたはそれ以上のソフトウェアパッケージをダウンロードし、インストールします。以下は、Web ページ上からインストールする引き金の基本的な例です:

+
xpi={'XPInstall Dialog Display Name':'simple.xpi'};
+InstallTrigger.install(xpi);
+
+

また、InstallTrigger オブジェクトをソフトウェアのバージョンチェックに使用したり、Netscape 6 や Mozilla のテーマ、言語パックをインストールしたり、 install オブジェクトを使用して複数のパッケージをインストールすることもできます。

diff --git a/files/ja/web/api/mediarecorder_api/index.html b/files/ja/web/api/mediarecorder_api/index.html deleted file mode 100644 index a2e3ec8eaf..0000000000 --- a/files/ja/web/api/mediarecorder_api/index.html +++ /dev/null @@ -1,187 +0,0 @@ ---- -title: MediaRecorder API -slug: Web/API/MediaRecorder_API -translation_of: Web/API/MediaStream_Recording_API -translation_of_original: Web/API/MediaRecorder_API ---- -
-

MediaRecorder API (MediaStream Recording) はインプットデバイスからのメディアストリームを記録するための API です。記録したストリームは PCM データのエンコードと言った操作をせずに利用できます。 {{ domxref("Navigator.getUserMedia()") }} を単体で利用する際の利用が想定されています。

-
- -

キーコンセプトと利用例

- -

MediaRecorder を {{ domxref("Navigator.getUserMedia()") }} とともに利用することで、メディアデータを記録できます。単純には、 {{ domxref("MediaRecorder.start()") }} メソッドを呼ぶことで記録を開始できます。MediaStream の終了、もしくは {{ domxref("MediaRecorder.stop()") }} や{{ domxref("MediaRecorder.requestData()") }} の呼び出しによって記録用のデータが準備できた際には、dataavailable イベントが発生します。現在のところ、データはプラットホームの標準でエンコードされ、 dataavailableの data 属性に {{ domxref("Blob") }} として配置されます。

- -

アプリは利用可能なエンコード方式を問い合わせ、その中から利用するものを選択することも可能です。またデータをより小さなバッファとして一定間隔で受け取ることもできます。間隔は {{ domxref("MediaRecorder.start()") }} を呼ぶ際に指定できます。

- -
-

注意: MediaRecorder API の基本的な利用方法については MediaRecorder API の利用  をご覧ください。

-
- -

MediaRecorder インタフェース

- -
-
{{ domxref("MediaRecorder") }}
-
MediaRecorder API を利用してメディアデータを記録するために必要な機能を保持するオブジェクト。 MediaRecorder() コンストラクタによって作成される。
-
{{ domxref("BlobEvent") }}
-
{{ domxref("MediaRecorder") }} によって記録されたメディアデータを保持する {{ domxref("Blob") }} オブジェクトへのアクセス手段を提供する。
-
- -

- -
if (navigator.getUserMedia) {
-   console.log('getUserMedia supported.');
-   navigator.getUserMedia (
-      // constraints - only audio needed for this app
-      {
-         audio: true
-      },
-
-      // Success callback
-      function(stream) {
-           var mediaRecorder = new MediaRecorder(stream);
-
-           record.onclick = function() {
-               mediaRecorder.start();
-               console.log("recorder started");
-           }
-
-           stop.onclick = function() {
-               mediaRecorder.stop();
-               console.log("recorder stopped");
-           }
-
-           mediaRecorder.ondataavailable = function(e) {
-             console.log("data available after MediaRecorder.stop() called.");
-
-             var audio = document.createElement('audio');
-             audio.setAttribute('controls', '');
-             var audioURL = window.URL.createObjectURL(e.data);
-             audio.src = audioURL;
-           }
-      },
-
-      // Error callback
-      function(err) {
-         console.log('The following gUM error occured: ' + err);
-      }
-   );
-} else {
-   console.log('getUserMedia not supported on your browser!');
-}
- -
-

注意: このサンプルコードはWeb Dictaphoneのデモを参考にしています。コードを簡単にする為にいくつかの行は省略されています。完全なコードは 元ソース を参照して下さい。

-
- -

ブラウザ互換性

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support -

{{ CompatChrome(47.0) }}

-
{{ CompatGeckoDesktop("25.0") }}{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)Firefox OSIE PhoneOpera MobileSafari Mobile
Basic support{{ CompatChrome(47.0) }}{{ CompatGeckoDesktop("25.0") }}1.3{{ CompatNo() }}{{ CompatNo() }}{{ CompatNo() }}
-
- -

[1] The initial Firefox OS implementation only supported audio recording.

- -

[2] To use {{domxref("MediaRecorder")}} in Chrome 47 and 48, enable experimental Web Platform features from the chrome://flags page.

- -

[3] Audio recording works in Chrome 49 and above; Chrome 47 and 48 only support video recording.

- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('MediaStream Recording', '#MediaRecorderAPI')}}{{Spec2('MediaStream Recording')}}
- -

関連項目

- - - - diff --git a/files/ja/web/api/node/baseuriobject/index.html b/files/ja/web/api/node/baseuriobject/index.html deleted file mode 100644 index 1de7600c48..0000000000 --- a/files/ja/web/api/node/baseuriobject/index.html +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Node.baseURIObject -slug: Web/API/Node/baseURIObject -tags: - - DOM - - DOM 3 - - Gecko - - Node -translation_of: Web/API/Node -translation_of_original: Web/API/Node/baseURIObject ---- -
{{ApiRef}} {{Fx_minversion_header("3")}} {{Non-standard_header}}
- -

概要

- -

baseURIObject は、文書の基底 URL (base URL) を示す {{Interface("nsIURI")}} オブジェクトを返します。

- -

このプロパティは、HTML 、 XUL、 SVG、 MathML 等のノード全てに存在します。但し、このプロパティの使用を試みるスクリプトが UniversalXPConnect 特権を持つ場合に限ります。

- -

基底 URL の詳細については {{domxref("Node.baseURI")}} の頁をご覧下さい。

- -

構文

- -
uriObj = element.baseURIObject
-
- -

注記

- -

このプロパティは読取専用です。書込を試みた場合、例外がスローされます。また、このプロパティには、特権を持つコードからのみアクセス可能です。

- -

仕様書

- -

標準仕様書には含まれません。

diff --git a/files/ja/web/api/node/nodeprincipal/index.html b/files/ja/web/api/node/nodeprincipal/index.html deleted file mode 100644 index 41547615f2..0000000000 --- a/files/ja/web/api/node/nodeprincipal/index.html +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Node.nodePrincipal -slug: Web/API/Node/nodePrincipal -tags: - - DOM - - Gecko - - Gecko DOM Reference -translation_of: Web/API/Node -translation_of_original: Web/API/Node/nodePrincipal ---- -
- {{ApiRef}}{{Fx_minversion_header("3")}}{{Non-standard_header}}
-

概要

-

nodePrincipal は、ノードの現在のセキュリティ・コンテキストを表す {{interface("nsIPrincipal")}} オブジェクトを返します

-

{{note("このプロパティは、HTML 、XUL 、SVG 、MathML などの全てのノードに存在しますが、スクリプトが使用を試みた場合にのみ、 UniversalXPConnect 特権を持ちます。")}}

-

構文

-
principalObj = element.nodePrincipal
-

注記

-

このプロパティは読取専用です。書込みを試みた場合、例外がスローされます。また、このプロパティには特権コードからのみアクセス可能です。

-

仕様書

-

仕様書はありません。

diff --git a/files/ja/web/api/page_visibility_api/index.html b/files/ja/web/api/page_visibility_api/index.html new file mode 100644 index 0000000000..524153a17e --- /dev/null +++ b/files/ja/web/api/page_visibility_api/index.html @@ -0,0 +1,272 @@ +--- +title: Page Visibility API +slug: Web/Guide/User_experience/Using_the_Page_Visibility_API +tags: + - DOM + - Intermediate + - Tutorials +translation_of: Web/API/Page_Visibility_API +--- +
{{DefaultAPISidebar("Page Visibility API")}}
+ +

タブを使って閲覧している場合、どのウェブページもバックグラウンドにあってユーザーから見えていない場合があります。 Page Visibility API では、現在ページが見えているかどうかを調べる機能とともに、文書が表示されたり非表示になったりした時を監視することができるイベントを提供します。

+ +
+

メモ: The Page Visibility API は、文書が表示されていない時に不必要なタスクの実行を抑止することで、リソースを節約したり実行効率を上げたりするために特に有用です。

+
+ +

ユーザーがウィンドウを最小化したり他のタブに切り替えたりした時、 API は {{event("visibilitychange")}} イベントを送信してリスナーにページの状態が変化したことを知らせます。イベントを検出していくつかの操作を実行したり、様々な動作をしたりすることができます。例えば、ウェブアプリで動画を再生している場合、ユーザーがタブをバックグラウンドにした場合に動画を一時停止させ、ユーザーがこのタブに戻ったときに再生を再開させたりすることができます。ユーザーは動画の位置に迷うことがなく、動画の音声が新しく前景になったタブの音声を邪魔せず、ユーザーがその間に動画を見落とすことがなくなります。

+ +

{{HTMLElement("iframe")}} の可視状態は、親文書と同じになります。 CSS プロパティにより ({{cssxref("display", "display: none;")}} のように) <iframe> を隠しても visibility のイベントは発生せず、またフレームに含まれる文書の状態も変わりません。

+ +

使用例

+ +

Page Visibility API の使用例をいくつか考えてみましょう。

+ + + +

以前、開発者はこれを検出するために不完全な代替手段を使用していました。例えば window で onblur/onfocus ハンドラーを登録することでページがアクティブではないときを知る助けになりますが、ページがユーザーから隠された状態であることは知らせてくれません。 Page Visibility API はこれを解決します。

+ +
+

メモ: {{domxref("GlobalEventHandlers.onblur", "onblur")}} 及び {{domxref("GlobalEventHandlers.onfocus", "onfocus")}} はユーザーがウィンドウを切り替えたことを教えてくれますが、非表示にしたという意味になるとは限りません。ページが非表示になるのは、ユーザーがタブを切り替えたり、タブを含むブラウザーウィンドウを最小化したりした時だけです。

+
+ +

Policies in place to aid background page performance

+ +

Separately from the Page Visibility API, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. These may include:

+ + + +

Some processes are exempt from this throttling behavior. In these cases, you can use the Page Visibility API to reduce the tabs' performance impact while they're hidden.

+ + + +

+ +

ライブサンプルをご覧ください (音声つき動画あり)。

+ +

この例では別のタブに切り替えたときに動画再生を一時停止、また元のタブに戻った時に再生を再開しており、以下のコードで作られました:

+ +
// hidden プロパティおよび可視性の変更イベントの名前を設定
+var hidden, visibilityChange;
+if (typeof document.hidden !== "undefined") { // Opera 12.10 や Firefox 18 以降でサポート
+  hidden = "hidden";
+  visibilityChange = "visibilitychange";
+} else if (typeof document.msHidden !== "undefined") {
+  hidden = "msHidden";
+  visibilityChange = "msvisibilitychange";
+} else if (typeof document.webkitHidden !== "undefined") {
+  hidden = "webkitHidden";
+  visibilityChange = "webkitvisibilitychange";
+}
+
+var videoElement = document.getElementById("videoElement");
+
+// ページが隠れたとき、動画再生を一時停止する。
+// ページが表示されたとき、動画を再生する。
+function handleVisibilityChange() {
+  if (document[hidden]) {
+    videoElement.pause();
+  } else {
+    videoElement.play();
+  }
+}
+
+// ブラウザーが addEventListener または Page Visibility API をサポートしない場合に警告
+if (typeof document.addEventListener === "undefined" || hidden === undefined) {
+  console.log("This demo requires a browser, such as Google Chrome or Firefox, that supports the Page Visibility API.");
+} else {
+  // Page Visibility の変更を扱う
+  document.addEventListener(visibilityChange, handleVisibilityChange, false);
+
+  // 動画が一時停止されたときに、タイトルを設定する。
+  // 一時停止したことを示す。
+  videoElement.addEventListener("pause", function(){
+    document.title = 'Paused';
+  }, false);
+
+  // 動画を再生するときに、タイトルを設定する。
+  videoElement.addEventListener("play", function(){
+    document.title = 'Playing';
+  }, false);
+
+}
+
+ +

Document インターフェイスに追加されたプロパティ

+ +

The Page Visibility API adds the following properties to the {{domxref("Document")}} interface:

+ +
+
{{domxref("Document.hidden")}} {{ReadOnlyInline}}
+
ページがユーザーから隠された状態であると思われる場合に true を、そうでない場合に false を返します。
+
{{domxref("Document.visibilityState")}} {{ReadOnlyInline}}
+
文書の現在の可視状態を示す {{domxref("DOMString")}} です。取りうる値は以下の通りです。 +
+
visible
+
ページのコンテンツは少なくとも部分的に可視状態です。実際は、最小化されていないウィンドウのフォアグラウンドのタブにページがあることを意味します。
+
hidden
+
ページのコンテンツはユーザーから見えていません。実際は、文書がバックグラウンドのタブか最小化されているウィンドウにある、あるいは OS のスクリーンがロックされていることを意味します。
+
prerender
+
ページのコンテンツはプリレンダリングされており、ユーザーから見えていません (document.hidden では隠されているとみなされます)。文書は prerender の状態から始まるかもしれませんが、プリレンダリングは1つの文書は1回しか行われないので、他の状態からこの状態に移ることはありません。 +
メモ: すべてのブラウザーがプリレンダリングに対応しているわけではありません。
+
+
unloaded
+
ページがメモリからアンロードされている途中です。 +
メモ: すべてのブラウザーが unloaded の値に対応しているわけではありません。
+
+
+
+
{{domxref("Document.onvisibilitychange")}}
+
{{event("visibilitychange")}} イベントが発生したときに呼び出されるコードを提供する {{domxref("EventListener")}} です。
+
+ +
//startSimulation および pauseSimulation は別途定義される
+function handleVisibilityChange() {
+  if (document.hidden) {
+    pauseSimulation();
+  } else  {
+    startSimulation();
+  }
+}
+
+document.addEventListener("visibilitychange", handleVisibilityChange, false);
+
+ +

仕様書

+ + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('Page Visibility API')}}{{Spec2('Page Visibility API')}}初回定義
+ +

ブラウザーの対応

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
機能ChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
基本対応13 {{property_prefix("webkit")}}
+ 33
{{CompatGeckoDesktop(18)}}[2]1012.10[1]7
onvisibilitychange{{CompatVersionUnknown}}{{CompatGeckoDesktop(56)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Budget-based background timeout throttling57{{CompatGeckoDesktop(58)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
機能AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
基本対応5.0[3]{{CompatGeckoMobile(18)}}[2]1012.10[1]7[4]
onvisibilitychange{{CompatVersionUnknown}}{{CompatGeckoMobile(56)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
Budget-based background timeout throttling{{CompatNo}}{{CompatGeckoMobile(58)}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] ブラウザーウィンドウを最小化しても visibilitychange イベントは発生せず、また hiddentrue に変わりません。

+ +

[2] Firefox 10 から Firefox 51 まで、このプロパティは -moz- 接頭辞を使用することができました。

+ +

[3] Android 4.4 はこの機能に webkit の接頭辞付きで対応しています。

+ +

[4] From iOS 11.0.2 onwards, the values are not correct in standalone mode (when you press "Add to Homescreen") and when the screen is locked (you pressed the power button). The value for hidden is false and visibilityState is visible.

+ +

関連情報

+ + diff --git a/files/ja/web/api/proximity_events/index.html b/files/ja/web/api/proximity_events/index.html new file mode 100644 index 0000000000..633d2a7cfb --- /dev/null +++ b/files/ja/web/api/proximity_events/index.html @@ -0,0 +1,84 @@ +--- +title: Proximity Events +slug: WebAPI/Proximity +tags: + - API + - Experimental + - Proximity Events + - Reference +translation_of: Web/API/Proximity_Events +--- +

{{DefaultAPISidebar("Proximity Events")}}{{ SeeCompatTable }}

+ +

proximity events は、ユーザーが端末の近くにいるときを知るのに便利な手段です。これらのイベントは近接度の変化への対応、例えばユーザーがスマートフォンを耳の近くに持ってきて電話をしているときにスクリーンを休止することを可能にします。

+ +
+

メモ: この API は端末に近接センサーを必要とすることが明らかです。近接センサーは、たいていモバイル端末のみで使用できます。センサーを搭載していない端末もイベントをサポートするかもしれませんが、イベントは発生しません。

+
+ +

Proximity Event

+ +

端末の近接センサーが端末と物体との距離の変化を検出すると、それをブラウザーに通知します。ブラウザーが通知を受けると、あらゆる変化について {{domxref("DeviceProximityEvent")}} イベントが、またよりおおざっぱな変化の場合に {{domxref("UserProximityEvent")}} イベントが発生します。

+ +

このイベントは {{domxref("EventTarget.addEventListener","addEventListener")}} メソッド (イベント名 {{event("deviceproximity")}} または {{event("userproximity")}} を使用) を使用するか、イベントハンドラーを {{domxref("window.ondeviceproximity")}} プロパティまたは {{domxref("window.onuserproximity")}} プロパティに接続することにより、window オブジェクトレベルで取得できます。

+ +

イベントを取得すると、イベントオブジェクトでさまざまな種類の情報にアクセスできます。

+ + + +

+ +
window.addEventListener('userproximity', function(event) {
+  if (event.near) {
+    // スクリーンの電源を切る
+    navigator.mozPower.screenEnabled = false;
+  } else {
+    // スクリーンの電源を入れる
+    navigator.mozPower.screenEnabled = true;
+  }
+});
+ +

仕様書

+ + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('Proximity Events', '', 'Proximity Events')}}{{Spec2('Proximity Events')}}初回定義
+ +

ブラウザーの対応

+ +

DeviceProximityEvent

+ + + +

{{Compat("api.DeviceProximityEvent")}}

+ +

UserProximityEvent

+ + + +

{{Compat("api.UserProximityEvent")}}

+ +

関連情報

+ + diff --git a/files/ja/web/api/randomsource/index.html b/files/ja/web/api/randomsource/index.html deleted file mode 100644 index 5972564d98..0000000000 --- a/files/ja/web/api/randomsource/index.html +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: RandomSource -slug: Web/API/RandomSource -tags: - - API - - Interface - - RandomSource - - Reference - - Web Crypto API -translation_of: Web/API/Crypto/getRandomValues -translation_of_original: Web/API/RandomSource ---- -

{{APIRef("Web Crypto API")}}

- -

RandomSource は、暗号的に安全な乱数値のソースを表します。これは、グローバルオブジェクトの {{domxref("Crypto")}} オブジェクトを通して利用可能です。ウェブページ上では {{domxref("Window.crypto")}}、Worker 内では {{domxref("WorkerGlobalScope.crypto")}} が利用できます。

- -

RandomSource は、インターフェイスでも、作成できるこの種類のオブジェクトでもありません。

- -

プロパティ

- -

RandomSource はどのプロパティも定義または継承しません。

- -
-
- -

メソッド

- -
-
{{ domxref("RandomSource.getRandomValues()") }}
-
渡された {{ domxref("ArrayBufferView") }} を意味不明の乱数値で埋めます。
-
- -

仕様

- - - - - - - - - - - - - - -
仕様書策定状況備考
{{SpecName('Web Crypto API', '#dfn-RandomSource')}}{{Spec2('Web Crypto API')}}初期定義
- -

ブラウザーの実装状況

- -

{{ CompatibilityTable() }}

- -
- - - - - - - - - - - - - - - - - - - - - -
機能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本サポート11.0 {{ webkitbug("22049") }}{{CompatVersionUnknown}}{{CompatGeckoDesktop(21)}} [1]11.015.03.1
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
機能AndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本サポート{{ CompatNo() }}23{{CompatVersionUnknown}}{{CompatGeckoMobile(21)}}{{ CompatNo() }}{{ CompatNo() }}6
-
- -

[1] RandomSource は Firefox 26 からのみ利用可能ですが、機能は Firefox 21 から利用可能でした。

- -

関連情報

- - diff --git a/files/ja/web/api/readablestreamdefaultcontroller/readablestreamdefaultcontroller/index.html b/files/ja/web/api/readablestreamdefaultcontroller/readablestreamdefaultcontroller/index.html deleted file mode 100644 index 16574bebce..0000000000 --- a/files/ja/web/api/readablestreamdefaultcontroller/readablestreamdefaultcontroller/index.html +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: ReadableStreamDefaultController.ReadableStreamDefaultController() -slug: Web/API/ReadableStreamDefaultController/ReadableStreamDefaultController -tags: - - API - - Constructor - - ReadableStreamDefaultController - - Reference - - Streams -translation_of: Web/API/ReadableStreamDefaultController/ReadableStreamDefaultController ---- -
{{APIRef("Streams")}}
- -

ReadableStreamDefaultController() コンストラクターは、ReadableStreamDefaultController オブジェクトのインスタンスを作成して返します。

- -
-

: このコンストラクターを手動で使用することはありません — これは、{{domxref("ReadableStream")}} オブジェクトの構築中に使用されます。

-
- -

構文

- -
var readableStreamDefaultController = new ReadableStreamDefaultController(stream, underlyingSource, size, highWaterMark);
- -

パラメーター

- -
-
stream
-
制御される {{domxref("ReadableStream")}}。
-
underlyingSource
-
構築されたストリームインスタンスの動作を定義するメソッドとプロパティを含むオブジェクト。 詳細については、ReadableStream() コンストラクターのパラメーター定義を参照してください。
-
size
-
 パラメーター chunk を含むメソッド — これは、各チャンクに使用するサイズをバイト単位で示します。
-
highWaterMark
-
負でない整数 — これは、バックプレッシャーが適用される前に内部キューに含めることができるチャンクの総数を定義します。
-
- -

戻り値

- -

{{domxref("ReadableStreamDefaultController")}} オブジェクトのインスタンス。

- -

例外

- -
-
TypeError
-
指定された stream パラメーターは {{domxref("ReadableStream")}} ではないか、既にコントローラーが関連付けられています。
-
- -

- -

次の単純な例では、コンストラクターを使用してカスタムの ReadableStream を作成します(完全なコードについては、単純なランダムストリームの例を参照)。 start() 関数は、1秒ごとにテキストのランダムな文字列を生成し、それをストリームのキューに入れます。 {{domxref("ReadableStream.cancel()")}} が何らかの理由で呼び出された場合、生成を停止するための cancel() 関数も提供します。

- -

{{domxref("ReadableStreamDefaultController")}} オブジェクトは、start() 関数および pull() 関数のパラメーターとして提供されることに注意してください。

- -

ボタンが押されると、生成を停止し、{{domxref("ReadableStreamDefaultController.close()")}} を使用してストリームを閉じ、ストリームからデータを読み取る別の関数を実行します。

- -
const stream = new ReadableStream({
-  start(controller) {
-    interval = setInterval(() => {
-      let string = randomChars();
-
-      // ストリームに文字列を追加
-      controller.enqueue(string);
-
-      // それを画面に表示
-      let listItem = document.createElement('li');
-      listItem.textContent = string;
-      list1.appendChild(listItem);
-    }, 1000);
-
-    button.addEventListener('click', function() {
-      clearInterval(interval);
-      fetchStream();
-      controller.close();
-    })
-  },
-  pull(controller) {
-    // この例では実際には pull は必要ありません
-  },
-  cancel() {
-    // リーダーがキャンセルされた場合に呼び出されるため、
-    // 文字列の生成を停止する必要があります
-    clearInterval(interval);
-  }
-});
- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName("Streams","#rs-default-controller-constructor","ReadableStreamDefaultController()")}}{{Spec2('Streams')}}初期定義
- -

ブラウザーの互換性

- - - -

{{Compat("api.ReadableStreamDefaultController.ReadableStreamDefaultController")}}

diff --git a/files/ja/web/api/slotable/index.html b/files/ja/web/api/slotable/index.html deleted file mode 100644 index 859be5e107..0000000000 --- a/files/ja/web/api/slotable/index.html +++ /dev/null @@ -1,50 +0,0 @@ ---- -title: Slotable -slug: Web/API/Slotable -tags: - - API - - Interface - - Reference - - Slotable - - Web Components - - shadow dom -translation_of: Web/API/Slottable -translation_of_original: Web/API/Slotable ---- -

{{APIRef("Shadow DOM")}}

- -

Slotable mixin は、ノードを {{htmlelement("slot")}} 要素のコンテンツにする機能を定義します。— 次の機能が {{domxref("Element")}} と {{domxref("Text")}} の両方に含まれています。

- -

プロパティ

- -
-
{{domxref("Slotable.assignedSlot")}} {{readonlyInline}}
-
ノードが挿入されている {{htmlelement("slot")}} を返します。
-
- -

メソッド

- -

なし。

- -

仕様

- - - - - - - - - - - - - - -
仕様書策定状況コメント
{{SpecName('DOM WHATWG','#slotable','Slotable')}}{{Spec2('DOM WHATWG')}}初期定義
- -

ブラウザー実装状況

- - - -

{{Compat("api.Slotable")}}

diff --git a/files/ja/web/api/vibration_api/index.html b/files/ja/web/api/vibration_api/index.html new file mode 100644 index 0000000000..49ab486128 --- /dev/null +++ b/files/ja/web/api/vibration_api/index.html @@ -0,0 +1,101 @@ +--- +title: Vibration API +slug: Web/Guide/API/Vibration +tags: + - API + - Beginner + - Mobile + - Vibration +translation_of: Web/API/Vibration_API +--- +
{{DefaultAPISidebar("Vibration API")}}
+ +

現代のモバイル端末は、たいていバイブレーションハードウェアを内蔵しており、ソフトウェアのコードが端末を振動させることによりユーザーに物理的なフィードバックを与えることができます。 Vibration API はウェブアプリに、このハードウェアが存在すればアクセスすることができるようにし、端末が対応していない場合は何もしません。

+ +

バイブレーションの表現

+ +

バイブレーションはオン・オフのパルスのパターンで表され、様々な長さになることがあります。パターンは振動するミリ秒数を示す整数 1 つ、あるいはバイブレーションと休止時間のパターンを示す整数の配列で構成します。バイブレーションは {{domxref("Navigator.vibrate()")}} という単一のメソッドで制御します。

+ +

1 回のバイブレーション

+ +

1 個の値、または 1 個だけの値で構成される配列を指定することにより、バイブレーションハードウェアを 1 回振動させることができます:

+ +
window.navigator.vibrate(200);
+window.navigator.vibrate([200]);
+
+ +

どちらの例も、デバイスを 200 ミリ秒間振動させます。

+ +

バイブレーションパターン

+ +

値の配列は、デバイスが振動する時間と振動しない時間を交互に示します。配列内の各値は整数値に変換されて、デバイスを振動させるミリ秒数および振動させないミリ秒数として交互に解釈されます。例えば以下のようにします。

+ +
window.navigator.vibrate([200, 100, 200]);
+
+ +

これはデバイスを 200 ミリ秒間振動させて、その後再び 200 ミリ秒間振動させる前に 100 ミリ秒間振動を止めます。

+ +

バイブレーション/休止のペアは好きなだけ多く指定でき、またエントリ数は偶数・奇数のどちらでも可能です。各バイブレーション時間の終端で自動的にバイブレーションを止めますので、休止時間を最後のエントリとして与えなくてもよいことは注目に値します。

+ +

実行中のバイブレーションを取り消す

+ +

0、空の配列、あるいはすべての値が 0 の配列 を指定して {{domxref("Navigator.vibrate()")}} を呼び出すと、現在進行中のバイブレーションパターンを取り消します。

+ +

継続的なバイブレーション

+ +

基本的な setInterval および clearInterval のアクションにより、継続的なバイブレーションを生成できます:

+ +
var vibrateInterval;
+
+// 渡されたレベルでバイブレーションを開始
+function startVibrate(duration) {
+    navigator.vibrate(duration);
+}
+
+// バイブレーションを停止
+function stopVibrate() {
+    // インターバルをクリアして継続的なバイブレーションを停止
+    if(vibrateInterval) clearInterval(vibrateInterval);
+    navigator.vibrate(0);
+}
+
+// 与えられた時間とインターバルによる継続的なバイブレーションを開始
+// 数値が与えられるものとする
+function startPersistentVibrate(duration, interval) {
+    vibrateInterval = setInterval(function() {
+        startVibrate(duration);
+    }, interval);
+}
+ +

当然ながら、上記のコードスニペットは配列によるバイブレーションを考慮していません。配列に基づく継続的なバイブレーションでは、配列のアイテムの総数を計算して、その値を基にしてインターバル (おそらく、遅延時間を付加して) を作成することが必要でしょう。

+ +

仕様書

+ + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName("Vibration API")}}{{Spec2("Vibration API")}}リンク先は最新の編集者草稿です。 W3C 版は勧告になりました。
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.Navigator.vibrate")}}

+ +

関連情報

+ + diff --git a/files/ja/web/api/vrdevice/cancelanimationframe/index.html b/files/ja/web/api/vrdevice/cancelanimationframe/index.html deleted file mode 100644 index 51d0f31164..0000000000 --- a/files/ja/web/api/vrdevice/cancelanimationframe/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: VRDisplay.cancelAnimationFrame() -slug: Web/API/VRDevice/cancelAnimationFrame -translation_of: Web/API/VRDisplay/cancelAnimationFrame ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの cancelAnimationFrame() メソッドは, {{domxref("Window.cancelAnimationFrame")}} の特別な実装で, {{domxref("VRDisplay.requestAnimationFrame()")}} で登録したコールバックを登録解除します.

- -

シンタックス

- -
vrDisplayInstance.cancelAnimationFrame(handle);
-
- -

パラメータ

- -
-
handle
-
登録解除したいハンドルを与えます.ハンドルは {{domxref("VRDisplay.requestAnimationFrame()")}} を呼出した時に戻り値として取得できます.
-
- -

戻り値

- -

void.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-cancelanimationframe', 'cancelAnimationFrame()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/capabilities/index.html b/files/ja/web/api/vrdevice/capabilities/index.html deleted file mode 100644 index 8aa2d49549..0000000000 --- a/files/ja/web/api/vrdevice/capabilities/index.html +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: VRDisplay.capabilities -slug: Web/API/VRDevice/capabilities -tags: - - API - - Experimental - - Property - - Reference - - VR - - VRDisplay - - Virtual Reality - - WebVR - - capabilities -translation_of: Web/API/VRDisplay/capabilities ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの capabilities 読取専用プロパティは,VRDisplay の様々な利用可能な機能を示す {{domxref("VRDisplayCapabilities")}} オブジェクトを返します。

- -

構文

- -
var myCapabilities = vrDisplayInstance.capabilities;
- -

- -

{{domxref("VRDisplayCapabilities")}} オブジェクト。

- -

- -

{{page("/Web/API/VRDisplayCapabilities", "Examples")}}

- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-capabilities', 'capabilities')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{Compat("api.VRDisplay.capabilities")}}

- -
- -
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/depthfar/index.html b/files/ja/web/api/vrdevice/depthfar/index.html deleted file mode 100644 index dc1c8a44e2..0000000000 --- a/files/ja/web/api/vrdevice/depthfar/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: VRDisplay.depthFar -slug: Web/API/VRDevice/depthFar -translation_of: Web/API/VRDisplay/depthFar ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの depthFar プロパティは,eye view frustum(ビューフラスタム;つまりシーンの可視領域の境界) のfar平面を定義しているz-depthの取得と設定を行います.

- -

シンタックス

- -
var mydepthFar = vrDisplayInstance.depthFar;
-
-vrDisplayInstance.depthFar = 7500.0;
-
- -

- -

z-depth をメートル単位で表すdouble値; 初期値は 10000.0 です.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-depthfar', 'depthFar')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/depthnear/index.html b/files/ja/web/api/vrdevice/depthnear/index.html deleted file mode 100644 index bbb4e9f739..0000000000 --- a/files/ja/web/api/vrdevice/depthnear/index.html +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: VRDisplay.depthNear -slug: Web/API/VRDevice/depthNear -translation_of: Web/API/VRDisplay/depthNear ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの depthNear プロパティは, eye view frustum(ビューフラスタム;つまりシーンの可視領域の境界) のnear平面を定義しているz-depthの取得と設定を行います.

- -

シンタックス

- -
var mydepthNear = vrDisplayInstance.depthNear;
-
-vrDisplayInstance.depthNear = 1.0;
-
- -

- -

z-depth をメートル単位で表すdouble値; 初期値は 0.01 です.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-depthnear', 'depthNear')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/displayid/index.html b/files/ja/web/api/vrdevice/displayid/index.html deleted file mode 100644 index 8b1dd9b244..0000000000 --- a/files/ja/web/api/vrdevice/displayid/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: VRDisplay.displayId -slug: Web/API/VRDevice/displayId -tags: - - API - - Experimental - - Property - - Reference - - VR - - VRDisplay - - Virtual Reality - - WebVR - - displayId -translation_of: Web/API/VRDisplay/displayId ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの displayId 読み取り専用プロパティは、この特定の VRDisplay の識別子を返します。これは、 Gamepad API の関連付けポイントとしても使用されます( {{domxref("Gamepad.displayId")}} を参照)。

- -

構文

- -
var myDisplayID = vrDisplayInstance.displayId;
- -

- -

特定の VRDisplay のIDを表す番号。

- -

- -

{{page("/Web/API/VRDisplayCapabilities", "Examples")}}

- -

仕様

- - - - - - - - - - - - - - -
仕様ステータス備考
{{SpecName('WebVR 1.1', '#dom-vrdisplay-displayid', 'displayId')}}{{Spec2('WebVR 1.1')}}初回定義
- -

ブラウザー実装状況

- -

{{Compat("api.VRDisplay.displayId")}}

- -

関連項目

- - diff --git a/files/ja/web/api/vrdevice/geteyeparameters/index.html b/files/ja/web/api/vrdevice/geteyeparameters/index.html deleted file mode 100644 index 1f7240d523..0000000000 --- a/files/ja/web/api/vrdevice/geteyeparameters/index.html +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: VRDisplay.getEyeParameters() -slug: Web/API/VRDevice/getEyeParameters -translation_of: Web/API/VRDisplay/getEyeParameters ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの getEyeParameters() メソッドは,指定下側の眼のeyeパラメータを持っている {{domxref("VREyeParameters")}} オブジェクトを返します.

- -

シンタックス

- -
var myEyeParameters = vrDisplayInstance.getEyeParameters(whichEye);
-
- -

パラメータ

- -
-
whichEye
-
取得したい側のeyeパラメータの眼を表す {{domxref("DOMString")}} です.指定できる値は (VREye enum で定義されている) leftright です.
-
- -

戻り値

- -

 {{domxref("VREyeParameters")}} オブジェクトか,VRコンテンツを表示できない場合(例えば {{domxref("VRDisplayCapabilities.canPresent")}} が false を返す場合)は null です.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-geteyeparameters', 'getEyeParameters()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/getimmediatepose/index.html b/files/ja/web/api/vrdevice/getimmediatepose/index.html deleted file mode 100644 index c0a11c9363..0000000000 --- a/files/ja/web/api/vrdevice/getimmediatepose/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: VRDisplay.getImmediatePose() -slug: Web/API/VRDevice/getImmediatePose -translation_of: Web/API/VRDisplay/getImmediatePose ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの getImmediatePose() メソッドは,予測が適用されていない状態の VRDisplay の現在のポーズを決める  {{domxref("VRPose")}} オブジェクトを返します.

- -

シンタックス

- -
var myImmediatePose = vrDisplayInstance.getImmediatePose();
-
- -

パラメータ

- -

なし.

- -

戻り値

- -

{{domxref("VRPose")}} オブジェクト.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-getimmediatepose', 'getImmediatePose()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/getlayers/index.html b/files/ja/web/api/vrdevice/getlayers/index.html deleted file mode 100644 index 01062a2e52..0000000000 --- a/files/ja/web/api/vrdevice/getlayers/index.html +++ /dev/null @@ -1,53 +0,0 @@ ---- -title: VRDisplay.getLayers() -slug: Web/API/VRDevice/getLayers -translation_of: Web/API/VRDisplay/getLayers ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの getLayers() メソッドは,VRDisplay で現在表示されているレイヤを返します.

- -

シンタックス

- -
var myLayers = vrDisplayInstance.getLayers();
-
- -

パラメータ

- -

なし.

- -

戻り値

- -

{{domxref("VRLayer")}} オブジェクトの配列.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-getlayers', 'getLayers()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{Compat("api.VRDisplay.getLayers")}}

- -

参照

- - diff --git a/files/ja/web/api/vrdevice/getpose/index.html b/files/ja/web/api/vrdevice/getpose/index.html deleted file mode 100644 index d0457edd10..0000000000 --- a/files/ja/web/api/vrdevice/getpose/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: VRDisplay.getPose() -slug: Web/API/VRDevice/getPose -translation_of: Web/API/VRDisplay/getPose ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの getPose() メソッドは,現在のフレームが実際に描画される時点の未来の VRDisplay の予測ポーズを決める {{domxref("VRPose")}} オブジェクトを返します.

- -

シンタックス

- -
var myPose = vrDisplayInstance.getPose();
-
- -

パラメータ

- -

なし.

- -

戻り値

- -

{{domxref("VRPose")}} オブジェクト.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-getpose', 'getPose()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/index.html b/files/ja/web/api/vrdevice/index.html deleted file mode 100644 index 7bf154bccf..0000000000 --- a/files/ja/web/api/vrdevice/index.html +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: VRDisplay -slug: Web/API/VRDevice -tags: - - API - - DOM - - Experimental - - Interface - - Media - - Reference - - VR - - VRDisplay - - Virtual Reality - - WebVR -translation_of: Web/API/VRDisplay ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

WebVR API の VRDisplay インターフェイスは,このAPIがサポートしているVRデバイスを現します.VRDisplayにはデバイスIDやデスクリプションのような汎用的な情報が含まれていて,VRシーンの表示を開始するためのメソッドや,目のパラメータやディスプレイの備える機能の取得,その他の重要な機能を含んでいます。

- -

{{domxref("Navigator.getVRDisplays()")}} を呼び出すことで,すべての接続されているVRのデバイスの配列が返されます。

- -

プロパティ

- -
-
{{domxref("VRDisplay.capabilities")}} {{readonlyInline}}
-
VRDisplayの備える機能を示す {{domxref("VRDisplayCapabilities")}} オブジェクトを返します.
-
{{domxref("VRDisplay.depthFar")}}
-
eye view frustum(ビューフラスタム;つまりシーンの可視領域の境界) のfar平面を定義しているz-depthの取得と設定を行います.
-
{{domxref("VRDisplay.depthNear")}}
-
eye view frustum(ビューフラスタム;つまりシーンの可視領域の境界) のnear平面を定義しているz-depthの取得と設定を行います.
-
{{domxref("VRDisplay.displayId")}} {{readonlyInline}}
-
このVRDisplay固有のIDを返します.このIDはGamepad API (参照 {{domxref("Gamepad.displayId")}}) の関連付けのために使用されます.
-
{{domxref("VRDisplay.displayName")}} {{readonlyInline}}
-
VRDisplayを識別するための人間が読める形式の名前を返します.
-
{{domxref("VRDisplay.isConnected")}} {{readonlyInline}}
-
VRDisplayがコンピュータに接続されているか否かを示す {{domxref("Boolean")}} を返します.
-
{{domxref("VRDisplay.isPresenting")}} {{readonlyInline}}
-
VRDisplayが現在コンテンツを表示中であるか否かを示す {{domxref("Boolean")}} を返します.
-
{{domxref("VRDisplay.stageParameters")}} {{readonlyInline}}
-
VRDisplayがルームスケール体験をサポートしている場合に,ルームスケールパラメータを含んだ {{domxref("VRStageParameters")}} オブジェクトを返します.
-
- -

メソッド

- -
-
{{domxref("VRDisplay.getEyeParameters()")}}
-
指定した側の眼のパラメータを含む {{domxref("VREyeParameters")}} オブジェクトを返します.
-
{{domxref("VRDisplay.getLayers()")}}
-
VRDisplay に表示中のレイヤーを返します.
-
{{domxref("VRDisplay.getPose()")}}
-
現在のフレームが実際に描画される時点の未来の VRDisplay の予測ポーズを決める {{domxref("VRPose")}} オブジェクトを返します.
-
{{domxref("VRDisplay.getImmediatePose()")}}
-
(予測なしの)VRDisplay のポーズを決める {{domxref("VRPose")}} オブジェクトを返します.
-
{{domxref("VRDisplay.resetPose()")}}
-
現在の {{domxref("VRPose.position")}} と {{domxref("VRPose.orientation")}} を"原点/ゼロ"位置の値として扱うように,VRDisplay のポーズをリセットします.
-
{{domxref("VRDisplay.cancelAnimationFrame()")}}
-
{{domxref("Window.cancelAnimationFrame")}} の特別な実装で,{{domxref("VRDisplay.requestAnimationFrame()")}} を未登録状態にすることをコールバック可能にしています.
-
{{domxref("VRDisplay.requestAnimationFrame()")}}
-
{{domxref("Window.requestAnimationFrame")}} の特別な実装で,VRDisplayの新しいフレームが描画される際に毎回呼出されるコールバック関数を持っています.
-
{{domxref("VRDisplay.requestPresent()")}}
-
VRDisplay へのシーン描画を開始します.
-
{{domxref("VRDisplay.exitPresent()")}}
-
VRDisplay のシーン描画を停止します.
-
{{domxref("VRDisplay.submitFrame()")}}
-
{{domxref("VRLayer")}} の現在の状態をキャプチャし,VRDisplay 上にそれを表示します.
-
-

非推奨のメソッド

-
-
{{domxref("VRDisplay.getPose()")}} {{deprecated_inline}}
-
Returns a {{domxref("VRPose")}} object defining the future predicted pose of the VRDisplay as it will be when the current frame is actually presented. This method is deprecated — instead, you should use {{domxref("VRDisplay.getFrameData()")}}, which also provides a {{domxref("VRPose")}} object.
-
-

廃止されたメソッド

-
-
{{domxref("VRDisplay.getImmediatePose()")}} {{obsolete_inline}}
-
Returns a {{domxref("VRPose")}} object defining the current pose of the VRDisplay, with no prediction applied. This is no longer needed, and has been removed from the spec.
-
{{domxref("VRDisplay.hardwareUnitId")}} {{obsolete_inline}}
-
Returns a {{domxref("DOMString")}} defining the shared ID of the display, and any other devices that are part of that hardware set (e.g. controllers). This is no longer needed, and has been removed from the spec. Displays now use {{domxref("VRDisplay.displayId")}}, and corresponsing controllers will now return the same ID under {{domxref("Gamepad.displayId")}}.
-
- -

- -
if(navigator.getVRDisplays) {
-  console.log('WebVR 1.1 supported');
-  // Then get the displays attached to the computer
-  navigator.getVRDisplays().then(function(displays) {
-    // If a display is available, use it to present the scene
-    if(displays.length > 0) {
-      vrDisplay = displays[0];
-      // Now we have our VRDisplay object and can do what we want with it
-    }
-  });
-}
- -
-

Note: この完全なコードは raw-webgl-example で確認できます。

-
- -

仕様

- - - - - - - - - - - - - - -
仕様ステータス備考
{{SpecName('WebVR', '#interface-vrdisplay', 'VRDisplay')}}{{Spec2('WebVR')}}初回定義
- -

ブラウザー実装状況

- -

{{Compat("api.VRDisplay")}}

- - - -
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/isconnected/index.html b/files/ja/web/api/vrdevice/isconnected/index.html deleted file mode 100644 index c8739dc720..0000000000 --- a/files/ja/web/api/vrdevice/isconnected/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: VRdisplay.isConnected -slug: Web/API/VRDevice/isConnected -translation_of: Web/API/VRDisplay/isConnected ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの isConnected 読取専用プロパティは, VRDisplay がコンピュータに接続されているかどうかを示す {{domxref("Boolean")}} を返します.

- -

シンタックス

- -
var isItConnected = vrDisplayInstance.isConnected;
-
- -

- -

{{domxref("Boolean")}}; true の場合はディスプレイが接続されていることを意味します;  それ以外は false.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-isconnected', 'isConnected')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/ispresenting/index.html b/files/ja/web/api/vrdevice/ispresenting/index.html deleted file mode 100644 index 4fe6132069..0000000000 --- a/files/ja/web/api/vrdevice/ispresenting/index.html +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: VRDisplay.isPresenting -slug: Web/API/VRDevice/isPresenting -translation_of: Web/API/VRDisplay/isPresenting ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの isPresenting 読取専用プロパティは, VRDisplay が現在コンテンツを表示中かどうかを示します.

- -

シンタックス

- -
var isItPresenting = vrDisplayInstance.isPresenting;
-
- -

- -

{{domxref("Boolean")}}; true の場合はそのディスプレイが表示中であることを意味します;  false は表示されていないことを意味します.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-ispresenting', 'isPresenting')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/requestanimationframe/index.html b/files/ja/web/api/vrdevice/requestanimationframe/index.html deleted file mode 100644 index 0865966016..0000000000 --- a/files/ja/web/api/vrdevice/requestanimationframe/index.html +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: VRDisplay.requestAnimationFrame() -slug: Web/API/VRDevice/requestAnimationFrame -translation_of: Web/API/VRDisplay/requestAnimationFrame ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの requestAnimationFrame() メソッドは,{{domxref("Window.requestAnimationFrame")}} の特別な実装です.このメソッドは VRDisplay がレンダリングされている間,新しいフレーム毎に呼出されるコールバック関数を持ちます:

- - - -

シンタックス

- -
var handle = vrDisplayInstance.requestAnimationFrame(callback);
-
- -

パラメータ

- -
-
callback
-
描画されている VRDisplay の新しいフレーム描画の度に呼出されるコールバック関数.
-
- -

戻り値

- -

requestAnimationFrame()呼出しのハンドルを表す long値.この値は,コールバックを登録解除するために {{domxref("VRDisplay.cancelAnimationFrame()")}} 呼出しへ渡すのに使えます.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-requestanimationframe', 'requestAnimationFrame()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/requestpresent/index.html b/files/ja/web/api/vrdevice/requestpresent/index.html deleted file mode 100644 index 3429a3e6a8..0000000000 --- a/files/ja/web/api/vrdevice/requestpresent/index.html +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: VRDisplay.requestPresent() -slug: Web/API/VRDevice/requestPresent -tags: - - API - - Experimental -translation_of: Web/API/VRDisplay/requestPresent ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの requestPresent() メソッドは,VRDisplay へのシーン表示を開始します.

- -

シンタックス

- -
vrDisplayInstance.requestPresent(layers).then(function() {
-  // Do something after the presentation has begun
-});
-
- -

パラメータ

- -
-
layers
-
表示したいシーンを表す {{domxref("VRLayer")}} オブジェクトの配列.なお現時点では,指定できるのは最小0要素,最大1要素です.
-
- -

戻り値

- -

表示が開始されたかを解決するpromise.

- -
-

注記: {{domxref("VRDisplayCapabilities.canPresent")}} が false,あるいは VRLayer 配列数が {{domxref("VRDisplayCapabilities.maxLayers")}} レイヤより多い場合, promiseはリジェクトされます.

-
- -
-

注記:   requestPresent() を呼出した時にVRDisplay が表示中の場合,VRDisplay は表示する VRLayer 配列を更新します.VRDisplayが表示中で requestPresent() がリジェクトされたら,VRDisplay は表示を終了します.

-
- -

- -
if(navigator.getVRDisplays) {
-  console.log('WebVR 1.1 supported');
-  // Then get the displays attached to the computer
-  navigator.getVRDisplays().then(function(displays) {
-    // If a display is available, use it to present the scene
-    if(displays.length > 0) {
-      vrDisplay = displays[0];
-      console.log('Display found');
-      // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
-      btn.addEventListener('click', function() {
-        if(btn.textContent === 'Start VR display') {
-          vrDisplay.requestPresent([{ source: canvas }]).then(function() {
-            console.log('Presenting to WebVR display');
-
-            // Set the canvas size to the size of the vrDisplay viewport
-
-            var leftEye = vrDisplay.getEyeParameters('left');
-            var rightEye = vrDisplay.getEyeParameters('right');
-
-            canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
-            canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);
-
-            // stop the normal presentation, and start the vr presentation
-            window.cancelAnimationFrame(normalSceneFrame);
-            drawVRScene();
-
-            btn.textContent = 'Exit VR display';
-          });
-        } else {
-          vrDisplay.exitPresent();
-          console.log('Stopped presenting to WebVR display');
-
-          btn.textContent = 'Start VR display';
-
-          // Stop the VR presentation, and start the normal presentation
-          vrDisplay.cancelAnimationFrame(vrSceneFrame);
-          drawScene();
-        }
-      });
-    }
-  });
-}
- -
-

Note: You can see this complete code at raw-webgl-example.

-
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-requestpresent', 'requestPresent()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/resetpose/index.html b/files/ja/web/api/vrdevice/resetpose/index.html deleted file mode 100644 index ae067cf0db..0000000000 --- a/files/ja/web/api/vrdevice/resetpose/index.html +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: VRDevice.resetPose() -slug: Web/API/VRDevice/resetPose -translation_of: Web/API/VRDisplay/resetPose ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの resetPose() メソッドは,VRDisplay のポーズをリセットして,現在の {{domxref("VRPose.position")}} と {{domxref("VRPose.orientation")}} を "原点/ゼロ位置" の値として扱います.

- -

resetPost() を呼出した後は, {{domxref("VRDisplay.getPose()")}}/{{domxref("VRDisplay.getImmediatePose()")}}  から返された未来予測ポーズは,resetPose() が最後に呼び出された時点からの相対的な VRDisplay の位置になります.また,resetPose() が最後に呼び出された時点のVRディスプレイのヨー(yaw)を前方として扱います.

- -

重力の方向に対して決まるので,resetPose() が呼び出されたとしてもVRDisplayのレポートするロール(roll)とピッチ(pitch)は変更されません.resetPose() の呼出しによって {{domxref("VRStageParameters.sittingToStandingTransform")}} 行列が変化する場合があります.

- -

シンタックス

- -
vrDisplayInstance.resetPose();
-
- -

パラメータ

- -

なし.

- -

戻り値

- -

void.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-resetpose', 'resetPose()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdevice/stageparameters/index.html b/files/ja/web/api/vrdevice/stageparameters/index.html deleted file mode 100644 index dcd10d86b6..0000000000 --- a/files/ja/web/api/vrdevice/stageparameters/index.html +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: VRDisplay.stageParameters -slug: Web/API/VRDevice/stageParameters -translation_of: Web/API/VRDisplay/stageParameters ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの stageParameters 読取専用プロパティは, VRDisplay がルームスケール体験をサポートしている場合に,ルームスケールパラメータを持つ {{domxref("VRStageParameters")}} オブジェクトを返します. 

- -

シンタックス

- -
var myStageParameters = vrDisplayInstance.stageParameters;
-
- -

- -

VRDisplay のルームスケールパラメータを持つ {{domxref("VRStageParameters")}} オブジェクトです.ルームスケール体験をサポートしていないVRDisplayでは null です.

- -

- -

{{page("/Web/API/VRStageParameters", "Examples")}}

- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR 1.1', '#dom-vrdisplay-stageparameters', 'stageParameters')}}{{Spec2('WebVR 1.1')}}Initial definition
- -

ブラウザの互換性

- -

{{Compat("api.VRDisplay.stageParameters")}}

- -

参照

- - diff --git a/files/ja/web/api/vrdevice/submitframe/index.html b/files/ja/web/api/vrdevice/submitframe/index.html deleted file mode 100644 index 28eea26910..0000000000 --- a/files/ja/web/api/vrdevice/submitframe/index.html +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: VRDisplay.submitFrame() -slug: Web/API/VRDevice/submitFrame -translation_of: Web/API/VRDisplay/submitFrame ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRDisplay")}} インターフェイスの submitFrame() メソッドは,VRDisplay 内に現在表示中の {{domxref("VRLayer")}} の現在の状態をキャプチャします.

- -

オプションとして,{{domxref("VRLayer")}} をレンダリングするのに使うポーズの表す {{domxref("VRPose")}} を提供することもできます.この{{domxref("VRLayer")}} は,ブラウザが遅延を低減するためにレイヤコンテンツの操作に使われます. VRPose を与えない場合は, {{domxref("VRDisplay.getPose()")}} で最後に返されたポーズが代わりに使われます.

- -

シンタックス

- -
vrDisplayInstance.submitFrame(pose);
-
- -

引数

- -
-
pose {{optional_inline()}}
-
A {{domxref("VRPose")}} オブジェクト.これはレイヤ操作や遅延の低減のためにブラウザによって使用されます.
-
- -

戻り値

- -

Void.

- -

- -
TBD.
- -

仕様

- - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-submitframe', 'submitFrame()')}}{{Spec2('WebVR')}}Initial definition
- -

ブラウザの互換性

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -
- - - - - - - - - - - - - - - - - - - - - -
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
-
- -

参照

- - diff --git a/files/ja/web/api/vrdisplay/cancelanimationframe/index.html b/files/ja/web/api/vrdisplay/cancelanimationframe/index.html new file mode 100644 index 0000000000..51d0f31164 --- /dev/null +++ b/files/ja/web/api/vrdisplay/cancelanimationframe/index.html @@ -0,0 +1,104 @@ +--- +title: VRDisplay.cancelAnimationFrame() +slug: Web/API/VRDevice/cancelAnimationFrame +translation_of: Web/API/VRDisplay/cancelAnimationFrame +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの cancelAnimationFrame() メソッドは, {{domxref("Window.cancelAnimationFrame")}} の特別な実装で, {{domxref("VRDisplay.requestAnimationFrame()")}} で登録したコールバックを登録解除します.

+ +

シンタックス

+ +
vrDisplayInstance.cancelAnimationFrame(handle);
+
+ +

パラメータ

+ +
+
handle
+
登録解除したいハンドルを与えます.ハンドルは {{domxref("VRDisplay.requestAnimationFrame()")}} を呼出した時に戻り値として取得できます.
+
+ +

戻り値

+ +

void.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-cancelanimationframe', 'cancelAnimationFrame()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/capabilities/index.html b/files/ja/web/api/vrdisplay/capabilities/index.html new file mode 100644 index 0000000000..8aa2d49549 --- /dev/null +++ b/files/ja/web/api/vrdisplay/capabilities/index.html @@ -0,0 +1,62 @@ +--- +title: VRDisplay.capabilities +slug: Web/API/VRDevice/capabilities +tags: + - API + - Experimental + - Property + - Reference + - VR + - VRDisplay + - Virtual Reality + - WebVR + - capabilities +translation_of: Web/API/VRDisplay/capabilities +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの capabilities 読取専用プロパティは,VRDisplay の様々な利用可能な機能を示す {{domxref("VRDisplayCapabilities")}} オブジェクトを返します。

+ +

構文

+ +
var myCapabilities = vrDisplayInstance.capabilities;
+ +

+ +

{{domxref("VRDisplayCapabilities")}} オブジェクト。

+ +

+ +

{{page("/Web/API/VRDisplayCapabilities", "Examples")}}

+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-capabilities', 'capabilities')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{Compat("api.VRDisplay.capabilities")}}

+ +
+ +
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/depthfar/index.html b/files/ja/web/api/vrdisplay/depthfar/index.html new file mode 100644 index 0000000000..dc1c8a44e2 --- /dev/null +++ b/files/ja/web/api/vrdisplay/depthfar/index.html @@ -0,0 +1,99 @@ +--- +title: VRDisplay.depthFar +slug: Web/API/VRDevice/depthFar +translation_of: Web/API/VRDisplay/depthFar +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの depthFar プロパティは,eye view frustum(ビューフラスタム;つまりシーンの可視領域の境界) のfar平面を定義しているz-depthの取得と設定を行います.

+ +

シンタックス

+ +
var mydepthFar = vrDisplayInstance.depthFar;
+
+vrDisplayInstance.depthFar = 7500.0;
+
+ +

+ +

z-depth をメートル単位で表すdouble値; 初期値は 10000.0 です.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-depthfar', 'depthFar')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/depthnear/index.html b/files/ja/web/api/vrdisplay/depthnear/index.html new file mode 100644 index 0000000000..bbb4e9f739 --- /dev/null +++ b/files/ja/web/api/vrdisplay/depthnear/index.html @@ -0,0 +1,99 @@ +--- +title: VRDisplay.depthNear +slug: Web/API/VRDevice/depthNear +translation_of: Web/API/VRDisplay/depthNear +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの depthNear プロパティは, eye view frustum(ビューフラスタム;つまりシーンの可視領域の境界) のnear平面を定義しているz-depthの取得と設定を行います.

+ +

シンタックス

+ +
var mydepthNear = vrDisplayInstance.depthNear;
+
+vrDisplayInstance.depthNear = 1.0;
+
+ +

+ +

z-depth をメートル単位で表すdouble値; 初期値は 0.01 です.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-depthnear', 'depthNear')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/displayid/index.html b/files/ja/web/api/vrdisplay/displayid/index.html new file mode 100644 index 0000000000..8b1dd9b244 --- /dev/null +++ b/files/ja/web/api/vrdisplay/displayid/index.html @@ -0,0 +1,58 @@ +--- +title: VRDisplay.displayId +slug: Web/API/VRDevice/displayId +tags: + - API + - Experimental + - Property + - Reference + - VR + - VRDisplay + - Virtual Reality + - WebVR + - displayId +translation_of: Web/API/VRDisplay/displayId +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの displayId 読み取り専用プロパティは、この特定の VRDisplay の識別子を返します。これは、 Gamepad API の関連付けポイントとしても使用されます( {{domxref("Gamepad.displayId")}} を参照)。

+ +

構文

+ +
var myDisplayID = vrDisplayInstance.displayId;
+ +

+ +

特定の VRDisplay のIDを表す番号。

+ +

+ +

{{page("/Web/API/VRDisplayCapabilities", "Examples")}}

+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータス備考
{{SpecName('WebVR 1.1', '#dom-vrdisplay-displayid', 'displayId')}}{{Spec2('WebVR 1.1')}}初回定義
+ +

ブラウザー実装状況

+ +

{{Compat("api.VRDisplay.displayId")}}

+ +

関連項目

+ + diff --git a/files/ja/web/api/vrdisplay/geteyeparameters/index.html b/files/ja/web/api/vrdisplay/geteyeparameters/index.html new file mode 100644 index 0000000000..1f7240d523 --- /dev/null +++ b/files/ja/web/api/vrdisplay/geteyeparameters/index.html @@ -0,0 +1,104 @@ +--- +title: VRDisplay.getEyeParameters() +slug: Web/API/VRDevice/getEyeParameters +translation_of: Web/API/VRDisplay/getEyeParameters +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの getEyeParameters() メソッドは,指定下側の眼のeyeパラメータを持っている {{domxref("VREyeParameters")}} オブジェクトを返します.

+ +

シンタックス

+ +
var myEyeParameters = vrDisplayInstance.getEyeParameters(whichEye);
+
+ +

パラメータ

+ +
+
whichEye
+
取得したい側のeyeパラメータの眼を表す {{domxref("DOMString")}} です.指定できる値は (VREye enum で定義されている) leftright です.
+
+ +

戻り値

+ +

 {{domxref("VREyeParameters")}} オブジェクトか,VRコンテンツを表示できない場合(例えば {{domxref("VRDisplayCapabilities.canPresent")}} が false を返す場合)は null です.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-geteyeparameters', 'getEyeParameters()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/getimmediatepose/index.html b/files/ja/web/api/vrdisplay/getimmediatepose/index.html new file mode 100644 index 0000000000..c0a11c9363 --- /dev/null +++ b/files/ja/web/api/vrdisplay/getimmediatepose/index.html @@ -0,0 +1,101 @@ +--- +title: VRDisplay.getImmediatePose() +slug: Web/API/VRDevice/getImmediatePose +translation_of: Web/API/VRDisplay/getImmediatePose +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの getImmediatePose() メソッドは,予測が適用されていない状態の VRDisplay の現在のポーズを決める  {{domxref("VRPose")}} オブジェクトを返します.

+ +

シンタックス

+ +
var myImmediatePose = vrDisplayInstance.getImmediatePose();
+
+ +

パラメータ

+ +

なし.

+ +

戻り値

+ +

{{domxref("VRPose")}} オブジェクト.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-getimmediatepose', 'getImmediatePose()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/getlayers/index.html b/files/ja/web/api/vrdisplay/getlayers/index.html new file mode 100644 index 0000000000..01062a2e52 --- /dev/null +++ b/files/ja/web/api/vrdisplay/getlayers/index.html @@ -0,0 +1,53 @@ +--- +title: VRDisplay.getLayers() +slug: Web/API/VRDevice/getLayers +translation_of: Web/API/VRDisplay/getLayers +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの getLayers() メソッドは,VRDisplay で現在表示されているレイヤを返します.

+ +

シンタックス

+ +
var myLayers = vrDisplayInstance.getLayers();
+
+ +

パラメータ

+ +

なし.

+ +

戻り値

+ +

{{domxref("VRLayer")}} オブジェクトの配列.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-getlayers', 'getLayers()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{Compat("api.VRDisplay.getLayers")}}

+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/getpose/index.html b/files/ja/web/api/vrdisplay/getpose/index.html new file mode 100644 index 0000000000..d0457edd10 --- /dev/null +++ b/files/ja/web/api/vrdisplay/getpose/index.html @@ -0,0 +1,101 @@ +--- +title: VRDisplay.getPose() +slug: Web/API/VRDevice/getPose +translation_of: Web/API/VRDisplay/getPose +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの getPose() メソッドは,現在のフレームが実際に描画される時点の未来の VRDisplay の予測ポーズを決める {{domxref("VRPose")}} オブジェクトを返します.

+ +

シンタックス

+ +
var myPose = vrDisplayInstance.getPose();
+
+ +

パラメータ

+ +

なし.

+ +

戻り値

+ +

{{domxref("VRPose")}} オブジェクト.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-getpose', 'getPose()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/index.html b/files/ja/web/api/vrdisplay/index.html new file mode 100644 index 0000000000..7bf154bccf --- /dev/null +++ b/files/ja/web/api/vrdisplay/index.html @@ -0,0 +1,129 @@ +--- +title: VRDisplay +slug: Web/API/VRDevice +tags: + - API + - DOM + - Experimental + - Interface + - Media + - Reference + - VR + - VRDisplay + - Virtual Reality + - WebVR +translation_of: Web/API/VRDisplay +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

WebVR API の VRDisplay インターフェイスは,このAPIがサポートしているVRデバイスを現します.VRDisplayにはデバイスIDやデスクリプションのような汎用的な情報が含まれていて,VRシーンの表示を開始するためのメソッドや,目のパラメータやディスプレイの備える機能の取得,その他の重要な機能を含んでいます。

+ +

{{domxref("Navigator.getVRDisplays()")}} を呼び出すことで,すべての接続されているVRのデバイスの配列が返されます。

+ +

プロパティ

+ +
+
{{domxref("VRDisplay.capabilities")}} {{readonlyInline}}
+
VRDisplayの備える機能を示す {{domxref("VRDisplayCapabilities")}} オブジェクトを返します.
+
{{domxref("VRDisplay.depthFar")}}
+
eye view frustum(ビューフラスタム;つまりシーンの可視領域の境界) のfar平面を定義しているz-depthの取得と設定を行います.
+
{{domxref("VRDisplay.depthNear")}}
+
eye view frustum(ビューフラスタム;つまりシーンの可視領域の境界) のnear平面を定義しているz-depthの取得と設定を行います.
+
{{domxref("VRDisplay.displayId")}} {{readonlyInline}}
+
このVRDisplay固有のIDを返します.このIDはGamepad API (参照 {{domxref("Gamepad.displayId")}}) の関連付けのために使用されます.
+
{{domxref("VRDisplay.displayName")}} {{readonlyInline}}
+
VRDisplayを識別するための人間が読める形式の名前を返します.
+
{{domxref("VRDisplay.isConnected")}} {{readonlyInline}}
+
VRDisplayがコンピュータに接続されているか否かを示す {{domxref("Boolean")}} を返します.
+
{{domxref("VRDisplay.isPresenting")}} {{readonlyInline}}
+
VRDisplayが現在コンテンツを表示中であるか否かを示す {{domxref("Boolean")}} を返します.
+
{{domxref("VRDisplay.stageParameters")}} {{readonlyInline}}
+
VRDisplayがルームスケール体験をサポートしている場合に,ルームスケールパラメータを含んだ {{domxref("VRStageParameters")}} オブジェクトを返します.
+
+ +

メソッド

+ +
+
{{domxref("VRDisplay.getEyeParameters()")}}
+
指定した側の眼のパラメータを含む {{domxref("VREyeParameters")}} オブジェクトを返します.
+
{{domxref("VRDisplay.getLayers()")}}
+
VRDisplay に表示中のレイヤーを返します.
+
{{domxref("VRDisplay.getPose()")}}
+
現在のフレームが実際に描画される時点の未来の VRDisplay の予測ポーズを決める {{domxref("VRPose")}} オブジェクトを返します.
+
{{domxref("VRDisplay.getImmediatePose()")}}
+
(予測なしの)VRDisplay のポーズを決める {{domxref("VRPose")}} オブジェクトを返します.
+
{{domxref("VRDisplay.resetPose()")}}
+
現在の {{domxref("VRPose.position")}} と {{domxref("VRPose.orientation")}} を"原点/ゼロ"位置の値として扱うように,VRDisplay のポーズをリセットします.
+
{{domxref("VRDisplay.cancelAnimationFrame()")}}
+
{{domxref("Window.cancelAnimationFrame")}} の特別な実装で,{{domxref("VRDisplay.requestAnimationFrame()")}} を未登録状態にすることをコールバック可能にしています.
+
{{domxref("VRDisplay.requestAnimationFrame()")}}
+
{{domxref("Window.requestAnimationFrame")}} の特別な実装で,VRDisplayの新しいフレームが描画される際に毎回呼出されるコールバック関数を持っています.
+
{{domxref("VRDisplay.requestPresent()")}}
+
VRDisplay へのシーン描画を開始します.
+
{{domxref("VRDisplay.exitPresent()")}}
+
VRDisplay のシーン描画を停止します.
+
{{domxref("VRDisplay.submitFrame()")}}
+
{{domxref("VRLayer")}} の現在の状態をキャプチャし,VRDisplay 上にそれを表示します.
+
+

非推奨のメソッド

+
+
{{domxref("VRDisplay.getPose()")}} {{deprecated_inline}}
+
Returns a {{domxref("VRPose")}} object defining the future predicted pose of the VRDisplay as it will be when the current frame is actually presented. This method is deprecated — instead, you should use {{domxref("VRDisplay.getFrameData()")}}, which also provides a {{domxref("VRPose")}} object.
+
+

廃止されたメソッド

+
+
{{domxref("VRDisplay.getImmediatePose()")}} {{obsolete_inline}}
+
Returns a {{domxref("VRPose")}} object defining the current pose of the VRDisplay, with no prediction applied. This is no longer needed, and has been removed from the spec.
+
{{domxref("VRDisplay.hardwareUnitId")}} {{obsolete_inline}}
+
Returns a {{domxref("DOMString")}} defining the shared ID of the display, and any other devices that are part of that hardware set (e.g. controllers). This is no longer needed, and has been removed from the spec. Displays now use {{domxref("VRDisplay.displayId")}}, and corresponsing controllers will now return the same ID under {{domxref("Gamepad.displayId")}}.
+
+ +

+ +
if(navigator.getVRDisplays) {
+  console.log('WebVR 1.1 supported');
+  // Then get the displays attached to the computer
+  navigator.getVRDisplays().then(function(displays) {
+    // If a display is available, use it to present the scene
+    if(displays.length > 0) {
+      vrDisplay = displays[0];
+      // Now we have our VRDisplay object and can do what we want with it
+    }
+  });
+}
+ +
+

Note: この完全なコードは raw-webgl-example で確認できます。

+
+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータス備考
{{SpecName('WebVR', '#interface-vrdisplay', 'VRDisplay')}}{{Spec2('WebVR')}}初回定義
+ +

ブラウザー実装状況

+ +

{{Compat("api.VRDisplay")}}

+ + + +
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/isconnected/index.html b/files/ja/web/api/vrdisplay/isconnected/index.html new file mode 100644 index 0000000000..c8739dc720 --- /dev/null +++ b/files/ja/web/api/vrdisplay/isconnected/index.html @@ -0,0 +1,97 @@ +--- +title: VRdisplay.isConnected +slug: Web/API/VRDevice/isConnected +translation_of: Web/API/VRDisplay/isConnected +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの isConnected 読取専用プロパティは, VRDisplay がコンピュータに接続されているかどうかを示す {{domxref("Boolean")}} を返します.

+ +

シンタックス

+ +
var isItConnected = vrDisplayInstance.isConnected;
+
+ +

+ +

{{domxref("Boolean")}}; true の場合はディスプレイが接続されていることを意味します;  それ以外は false.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-isconnected', 'isConnected')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/ispresenting/index.html b/files/ja/web/api/vrdisplay/ispresenting/index.html new file mode 100644 index 0000000000..4fe6132069 --- /dev/null +++ b/files/ja/web/api/vrdisplay/ispresenting/index.html @@ -0,0 +1,97 @@ +--- +title: VRDisplay.isPresenting +slug: Web/API/VRDevice/isPresenting +translation_of: Web/API/VRDisplay/isPresenting +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの isPresenting 読取専用プロパティは, VRDisplay が現在コンテンツを表示中かどうかを示します.

+ +

シンタックス

+ +
var isItPresenting = vrDisplayInstance.isPresenting;
+
+ +

+ +

{{domxref("Boolean")}}; true の場合はそのディスプレイが表示中であることを意味します;  false は表示されていないことを意味します.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-ispresenting', 'isPresenting')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/requestanimationframe/index.html b/files/ja/web/api/vrdisplay/requestanimationframe/index.html new file mode 100644 index 0000000000..0865966016 --- /dev/null +++ b/files/ja/web/api/vrdisplay/requestanimationframe/index.html @@ -0,0 +1,109 @@ +--- +title: VRDisplay.requestAnimationFrame() +slug: Web/API/VRDevice/requestAnimationFrame +translation_of: Web/API/VRDisplay/requestAnimationFrame +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの requestAnimationFrame() メソッドは,{{domxref("Window.requestAnimationFrame")}} の特別な実装です.このメソッドは VRDisplay がレンダリングされている間,新しいフレーム毎に呼出されるコールバック関数を持ちます:

+ + + +

シンタックス

+ +
var handle = vrDisplayInstance.requestAnimationFrame(callback);
+
+ +

パラメータ

+ +
+
callback
+
描画されている VRDisplay の新しいフレーム描画の度に呼出されるコールバック関数.
+
+ +

戻り値

+ +

requestAnimationFrame()呼出しのハンドルを表す long値.この値は,コールバックを登録解除するために {{domxref("VRDisplay.cancelAnimationFrame()")}} 呼出しへ渡すのに使えます.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-requestanimationframe', 'requestAnimationFrame()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/requestpresent/index.html b/files/ja/web/api/vrdisplay/requestpresent/index.html new file mode 100644 index 0000000000..3429a3e6a8 --- /dev/null +++ b/files/ja/web/api/vrdisplay/requestpresent/index.html @@ -0,0 +1,162 @@ +--- +title: VRDisplay.requestPresent() +slug: Web/API/VRDevice/requestPresent +tags: + - API + - Experimental +translation_of: Web/API/VRDisplay/requestPresent +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの requestPresent() メソッドは,VRDisplay へのシーン表示を開始します.

+ +

シンタックス

+ +
vrDisplayInstance.requestPresent(layers).then(function() {
+  // Do something after the presentation has begun
+});
+
+ +

パラメータ

+ +
+
layers
+
表示したいシーンを表す {{domxref("VRLayer")}} オブジェクトの配列.なお現時点では,指定できるのは最小0要素,最大1要素です.
+
+ +

戻り値

+ +

表示が開始されたかを解決するpromise.

+ +
+

注記: {{domxref("VRDisplayCapabilities.canPresent")}} が false,あるいは VRLayer 配列数が {{domxref("VRDisplayCapabilities.maxLayers")}} レイヤより多い場合, promiseはリジェクトされます.

+
+ +
+

注記:   requestPresent() を呼出した時にVRDisplay が表示中の場合,VRDisplay は表示する VRLayer 配列を更新します.VRDisplayが表示中で requestPresent() がリジェクトされたら,VRDisplay は表示を終了します.

+
+ +

+ +
if(navigator.getVRDisplays) {
+  console.log('WebVR 1.1 supported');
+  // Then get the displays attached to the computer
+  navigator.getVRDisplays().then(function(displays) {
+    // If a display is available, use it to present the scene
+    if(displays.length > 0) {
+      vrDisplay = displays[0];
+      console.log('Display found');
+      // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
+      btn.addEventListener('click', function() {
+        if(btn.textContent === 'Start VR display') {
+          vrDisplay.requestPresent([{ source: canvas }]).then(function() {
+            console.log('Presenting to WebVR display');
+
+            // Set the canvas size to the size of the vrDisplay viewport
+
+            var leftEye = vrDisplay.getEyeParameters('left');
+            var rightEye = vrDisplay.getEyeParameters('right');
+
+            canvas.width = Math.max(leftEye.renderWidth, rightEye.renderWidth) * 2;
+            canvas.height = Math.max(leftEye.renderHeight, rightEye.renderHeight);
+
+            // stop the normal presentation, and start the vr presentation
+            window.cancelAnimationFrame(normalSceneFrame);
+            drawVRScene();
+
+            btn.textContent = 'Exit VR display';
+          });
+        } else {
+          vrDisplay.exitPresent();
+          console.log('Stopped presenting to WebVR display');
+
+          btn.textContent = 'Start VR display';
+
+          // Stop the VR presentation, and start the normal presentation
+          vrDisplay.cancelAnimationFrame(vrSceneFrame);
+          drawScene();
+        }
+      });
+    }
+  });
+}
+ +
+

Note: You can see this complete code at raw-webgl-example.

+
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-requestpresent', 'requestPresent()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/resetpose/index.html b/files/ja/web/api/vrdisplay/resetpose/index.html new file mode 100644 index 0000000000..ae067cf0db --- /dev/null +++ b/files/ja/web/api/vrdisplay/resetpose/index.html @@ -0,0 +1,105 @@ +--- +title: VRDevice.resetPose() +slug: Web/API/VRDevice/resetPose +translation_of: Web/API/VRDisplay/resetPose +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの resetPose() メソッドは,VRDisplay のポーズをリセットして,現在の {{domxref("VRPose.position")}} と {{domxref("VRPose.orientation")}} を "原点/ゼロ位置" の値として扱います.

+ +

resetPost() を呼出した後は, {{domxref("VRDisplay.getPose()")}}/{{domxref("VRDisplay.getImmediatePose()")}}  から返された未来予測ポーズは,resetPose() が最後に呼び出された時点からの相対的な VRDisplay の位置になります.また,resetPose() が最後に呼び出された時点のVRディスプレイのヨー(yaw)を前方として扱います.

+ +

重力の方向に対して決まるので,resetPose() が呼び出されたとしてもVRDisplayのレポートするロール(roll)とピッチ(pitch)は変更されません.resetPose() の呼出しによって {{domxref("VRStageParameters.sittingToStandingTransform")}} 行列が変化する場合があります.

+ +

シンタックス

+ +
vrDisplayInstance.resetPose();
+
+ +

パラメータ

+ +

なし.

+ +

戻り値

+ +

void.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-resetpose', 'resetPose()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/stageparameters/index.html b/files/ja/web/api/vrdisplay/stageparameters/index.html new file mode 100644 index 0000000000..dcd10d86b6 --- /dev/null +++ b/files/ja/web/api/vrdisplay/stageparameters/index.html @@ -0,0 +1,49 @@ +--- +title: VRDisplay.stageParameters +slug: Web/API/VRDevice/stageParameters +translation_of: Web/API/VRDisplay/stageParameters +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの stageParameters 読取専用プロパティは, VRDisplay がルームスケール体験をサポートしている場合に,ルームスケールパラメータを持つ {{domxref("VRStageParameters")}} オブジェクトを返します. 

+ +

シンタックス

+ +
var myStageParameters = vrDisplayInstance.stageParameters;
+
+ +

+ +

VRDisplay のルームスケールパラメータを持つ {{domxref("VRStageParameters")}} オブジェクトです.ルームスケール体験をサポートしていないVRDisplayでは null です.

+ +

+ +

{{page("/Web/API/VRStageParameters", "Examples")}}

+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR 1.1', '#dom-vrdisplay-stageparameters', 'stageParameters')}}{{Spec2('WebVR 1.1')}}Initial definition
+ +

ブラウザの互換性

+ +

{{Compat("api.VRDisplay.stageParameters")}}

+ +

参照

+ + diff --git a/files/ja/web/api/vrdisplay/submitframe/index.html b/files/ja/web/api/vrdisplay/submitframe/index.html new file mode 100644 index 0000000000..28eea26910 --- /dev/null +++ b/files/ja/web/api/vrdisplay/submitframe/index.html @@ -0,0 +1,106 @@ +--- +title: VRDisplay.submitFrame() +slug: Web/API/VRDevice/submitFrame +translation_of: Web/API/VRDisplay/submitFrame +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRDisplay")}} インターフェイスの submitFrame() メソッドは,VRDisplay 内に現在表示中の {{domxref("VRLayer")}} の現在の状態をキャプチャします.

+ +

オプションとして,{{domxref("VRLayer")}} をレンダリングするのに使うポーズの表す {{domxref("VRPose")}} を提供することもできます.この{{domxref("VRLayer")}} は,ブラウザが遅延を低減するためにレイヤコンテンツの操作に使われます. VRPose を与えない場合は, {{domxref("VRDisplay.getPose()")}} で最後に返されたポーズが代わりに使われます.

+ +

シンタックス

+ +
vrDisplayInstance.submitFrame(pose);
+
+ +

引数

+ +
+
pose {{optional_inline()}}
+
A {{domxref("VRPose")}} オブジェクト.これはレイヤ操作や遅延の低減のためにブラウザによって使用されます.
+
+ +

戻り値

+ +

Void.

+ +

+ +
TBD.
+ +

仕様

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('WebVR', '#dom-vrdisplay-submitframe', 'submitFrame()')}}{{Spec2('WebVR')}}Initial definition
+ +

ブラウザの互換性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

参照

+ + diff --git a/files/ja/web/api/vrlayer/index.html b/files/ja/web/api/vrlayer/index.html deleted file mode 100644 index b0edd0d577..0000000000 --- a/files/ja/web/api/vrlayer/index.html +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: VRLayer -slug: Web/API/VRLayer -translation_of: Web/API/VRLayerInit ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

WebVR API の VRLayer インターフェイス (ディクショナリ)は,VRHMDへ表示したいコンテンツレイヤー( {{domxref("HTMLCanvasElement")}} または {{domxref("OffscreenCanvas")}})を表します。

- -

{{domxref("VRDisplay.requestPresent()")}} メソッドを使うことでレイヤーを表示することができます。

- -

プロパティ

- -
-
{{domxref("VRLayer.leftBounds")}}
-
{{domxref("VRDisplay")}} に表示されるキャンバスの左側テクスチャ境界を定義します。
-
{{domxref("VRLayer.rightBounds")}}
-
{{domxref("VRDisplay")}} に表示されるキャンバスの右側テクスチャ境界を定義します。
-
{{domxref("VRLayer.source")}}
-
{{domxref("VRDisplay")}} に表示されるコンテンツの対象となるキャンバスを定義します。
-
- -

- -
// currently returns an empty array
-var layers = vrDisplay.getLayers();
-
-if(navigator.getVRDisplays) {
-  console.log('WebVR 1.1 supported');
-  // Then get the displays attached to the computer
-  navigator.getVRDisplays().then(function(displays) {
-    // If a display is available, use it to present the scene
-    if(displays.length > 0) {
-      vrDisplay = displays[0];
-      console.log('Display found');
-      // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
-      btn.addEventListener('click', function() {
-        vrDisplay.requestPresent([{ source: canvas }]).then(function() {
-          console.log('Presenting to WebVR display');
-
-          // Here it returns an array of VRLayerInit objects
-          var layers = vrDisplay.getLayers();
-
-          ...
-        });
-      });
-    }
-  });
-}
- -

{{domxref("VRLayerInit")}} objects look something like this:

- -
{
-  leftBounds : [ ... ],
-  rightBounds: [ ... ],
-  source: canvasReference
-}
- -
-

Note: The canvasReference refers to the {{htmlelement("canvas")}} element itself, not the WebGL context associated with the canvas. The other two members are arrays

-
- -

仕様

- - - - - - - - - - - - - - -
仕様ステータス備考
{{SpecName('WebVR', '#interface-vrlayer', 'VRLayer')}}{{Spec2('WebVR')}}初回定義
- -

ブラウザの互換性

- -

{{Compat("api.VRLayerInit")}}

- -
- -

参照

- - diff --git a/files/ja/web/api/vrlayer/rightbounds/index.html b/files/ja/web/api/vrlayer/rightbounds/index.html deleted file mode 100644 index 944013d6d7..0000000000 --- a/files/ja/web/api/vrlayer/rightbounds/index.html +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: VRLayerInit.rightBounds -slug: Web/API/VRLayer/rightBounds -tags: - - API - - Experimental - - Property - - Refe - - VR - - VRLayerInit - - Virtual Reality - - WebVR - - rightBounds -translation_of: Web/API/VRLayerInit/rightBounds ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRLayerInit")}} インターフェイス (辞書) の rightBounds プロパティは、 {{domxref("VRDisplay")}} によってコンテンツが表示されるキャンバスの右のテクスチャ境界を定義します。

- -

構文

- -
var myVRLayerInit = { };
-myVRLayerInit.rightBounds = [0.5, 0.0, 0.5, 1.0];
- -

- -

4つの浮動小数点値の配列で 0.0–1.0 の値を取ることができます:

- -
    -
  1. 境界の左オフセット。
  2. -
  3. 境界の上オフセット。
  4. -
  5. 境界の幅。
  6. -
  7. 境界の高さ。
  8. -
- -

辞書で leftBounds が指定されていない場合、使用されるデフォルト値は [0.5, 0.0, 0.5, 1.0] です。

- -

- -

{{page("/Web/API/VRLayerInit", "Examples")}}

- -

仕様

- - - - - - - - - - - - - - -
仕様ステータス備考
{{SpecName('WebVR 1.1', '#dom-vrlayerinit-rightbounds', 'rightBounds')}}{{Spec2('WebVR 1.1')}}初回定義
- -

ブラウザー実装状況

- -

{{Compat("api.VRLayerInit.rightBounds")}}

- -

関連項目

- - diff --git a/files/ja/web/api/vrlayer/source/index.html b/files/ja/web/api/vrlayer/source/index.html deleted file mode 100644 index 94ab4eaa39..0000000000 --- a/files/ja/web/api/vrlayer/source/index.html +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: VRLayerInit.source -slug: Web/API/VRLayer/source -tags: - - API - - Experimental - - Property - - Reference - - VR - - VRLayerInit - - Virtual Reality - - WebVR - - source -translation_of: Web/API/VRLayerInit/source ---- -
{{APIRef("WebVR API")}}{{SeeCompatTable}}
- -

{{domxref("VRLayerInit")}} インターフェイス(ディクショナリ)の source プロパティは、 {{domxref("VRDisplay")}} によってコンテンツが表示されるキャンバスを定義します。

- -

構文

- -
var myVRLayerInit = { };
-myVRLayerInit.source = myCanvas;
- -

- -

{{domxref("HTMLCanvasElement")}} または {{domxref("OffscreenCanvas")}} オブジェクト。

- -

- -

{{page("/Web/API/VRLayerInit", "Examples")}}

- -

仕様

- - - - - - - - - - - - - - -
仕様ステータス備考
{{SpecName('WebVR 1.1', '#dom-vrlayerinit-source', 'source')}}{{Spec2('WebVR 1.1')}}初回定義
- -

ブラウザー実装状況

- -

{{Compat("api.VRLayerInit.source")}}

- -

関連項目

- - diff --git a/files/ja/web/api/vrlayerinit/index.html b/files/ja/web/api/vrlayerinit/index.html new file mode 100644 index 0000000000..b0edd0d577 --- /dev/null +++ b/files/ja/web/api/vrlayerinit/index.html @@ -0,0 +1,91 @@ +--- +title: VRLayer +slug: Web/API/VRLayer +translation_of: Web/API/VRLayerInit +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

WebVR API の VRLayer インターフェイス (ディクショナリ)は,VRHMDへ表示したいコンテンツレイヤー( {{domxref("HTMLCanvasElement")}} または {{domxref("OffscreenCanvas")}})を表します。

+ +

{{domxref("VRDisplay.requestPresent()")}} メソッドを使うことでレイヤーを表示することができます。

+ +

プロパティ

+ +
+
{{domxref("VRLayer.leftBounds")}}
+
{{domxref("VRDisplay")}} に表示されるキャンバスの左側テクスチャ境界を定義します。
+
{{domxref("VRLayer.rightBounds")}}
+
{{domxref("VRDisplay")}} に表示されるキャンバスの右側テクスチャ境界を定義します。
+
{{domxref("VRLayer.source")}}
+
{{domxref("VRDisplay")}} に表示されるコンテンツの対象となるキャンバスを定義します。
+
+ +

+ +
// currently returns an empty array
+var layers = vrDisplay.getLayers();
+
+if(navigator.getVRDisplays) {
+  console.log('WebVR 1.1 supported');
+  // Then get the displays attached to the computer
+  navigator.getVRDisplays().then(function(displays) {
+    // If a display is available, use it to present the scene
+    if(displays.length > 0) {
+      vrDisplay = displays[0];
+      console.log('Display found');
+      // Starting the presentation when the button is clicked: It can only be called in response to a user gesture
+      btn.addEventListener('click', function() {
+        vrDisplay.requestPresent([{ source: canvas }]).then(function() {
+          console.log('Presenting to WebVR display');
+
+          // Here it returns an array of VRLayerInit objects
+          var layers = vrDisplay.getLayers();
+
+          ...
+        });
+      });
+    }
+  });
+}
+ +

{{domxref("VRLayerInit")}} objects look something like this:

+ +
{
+  leftBounds : [ ... ],
+  rightBounds: [ ... ],
+  source: canvasReference
+}
+ +
+

Note: The canvasReference refers to the {{htmlelement("canvas")}} element itself, not the WebGL context associated with the canvas. The other two members are arrays

+
+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータス備考
{{SpecName('WebVR', '#interface-vrlayer', 'VRLayer')}}{{Spec2('WebVR')}}初回定義
+ +

ブラウザの互換性

+ +

{{Compat("api.VRLayerInit")}}

+ +
+ +

参照

+ + diff --git a/files/ja/web/api/vrlayerinit/rightbounds/index.html b/files/ja/web/api/vrlayerinit/rightbounds/index.html new file mode 100644 index 0000000000..944013d6d7 --- /dev/null +++ b/files/ja/web/api/vrlayerinit/rightbounds/index.html @@ -0,0 +1,68 @@ +--- +title: VRLayerInit.rightBounds +slug: Web/API/VRLayer/rightBounds +tags: + - API + - Experimental + - Property + - Refe + - VR + - VRLayerInit + - Virtual Reality + - WebVR + - rightBounds +translation_of: Web/API/VRLayerInit/rightBounds +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRLayerInit")}} インターフェイス (辞書) の rightBounds プロパティは、 {{domxref("VRDisplay")}} によってコンテンツが表示されるキャンバスの右のテクスチャ境界を定義します。

+ +

構文

+ +
var myVRLayerInit = { };
+myVRLayerInit.rightBounds = [0.5, 0.0, 0.5, 1.0];
+ +

+ +

4つの浮動小数点値の配列で 0.0–1.0 の値を取ることができます:

+ +
    +
  1. 境界の左オフセット。
  2. +
  3. 境界の上オフセット。
  4. +
  5. 境界の幅。
  6. +
  7. 境界の高さ。
  8. +
+ +

辞書で leftBounds が指定されていない場合、使用されるデフォルト値は [0.5, 0.0, 0.5, 1.0] です。

+ +

+ +

{{page("/Web/API/VRLayerInit", "Examples")}}

+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータス備考
{{SpecName('WebVR 1.1', '#dom-vrlayerinit-rightbounds', 'rightBounds')}}{{Spec2('WebVR 1.1')}}初回定義
+ +

ブラウザー実装状況

+ +

{{Compat("api.VRLayerInit.rightBounds")}}

+ +

関連項目

+ + diff --git a/files/ja/web/api/vrlayerinit/source/index.html b/files/ja/web/api/vrlayerinit/source/index.html new file mode 100644 index 0000000000..94ab4eaa39 --- /dev/null +++ b/files/ja/web/api/vrlayerinit/source/index.html @@ -0,0 +1,59 @@ +--- +title: VRLayerInit.source +slug: Web/API/VRLayer/source +tags: + - API + - Experimental + - Property + - Reference + - VR + - VRLayerInit + - Virtual Reality + - WebVR + - source +translation_of: Web/API/VRLayerInit/source +--- +
{{APIRef("WebVR API")}}{{SeeCompatTable}}
+ +

{{domxref("VRLayerInit")}} インターフェイス(ディクショナリ)の source プロパティは、 {{domxref("VRDisplay")}} によってコンテンツが表示されるキャンバスを定義します。

+ +

構文

+ +
var myVRLayerInit = { };
+myVRLayerInit.source = myCanvas;
+ +

+ +

{{domxref("HTMLCanvasElement")}} または {{domxref("OffscreenCanvas")}} オブジェクト。

+ +

+ +

{{page("/Web/API/VRLayerInit", "Examples")}}

+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータス備考
{{SpecName('WebVR 1.1', '#dom-vrlayerinit-source', 'source')}}{{Spec2('WebVR 1.1')}}初回定義
+ +

ブラウザー実装状況

+ +

{{Compat("api.VRLayerInit.source")}}

+ +

関連項目

+ + diff --git a/files/ja/web/api/webgl_api/cross-domain_textures/index.html b/files/ja/web/api/webgl_api/cross-domain_textures/index.html deleted file mode 100644 index 15dcbf30e3..0000000000 --- a/files/ja/web/api/webgl_api/cross-domain_textures/index.html +++ /dev/null @@ -1,16 +0,0 @@ ---- -title: Cross-Domain Textures -slug: Web/API/WebGL_API/Cross-Domain_Textures -translation_of: Web/API/WebGL_API/Tutorial/Using_textures_in_WebGL#Cross-domain_textures -translation_of_original: Web/API/WebGL_API/Cross-Domain_Textures ---- -

WebGL のテクスチャの読み込みは、クロスドメインアクセス制御に従います。コンテンツで他のドメインからテクスチャを読み込むためには、CORS で許可を得る必要があります。CORS について詳しくは、HTTP access control をご覧ください。

-

CORS で許可された画像を WebGL のテクスチャとして使用する方法の説明を こちらの hacks.mozilla.org の記事 に掲載していますので、サンプル と合わせてご覧ください。

-

{{ gecko_callout_heading("8.0") }}

WebGL テクスチャ向けの CORS サポートと、画像要素の crossOrigin 属性が Gecko 8 {{ geckoRelease("8.0") }} で実装されました。

-
-

汚染された (書き込みのみ) 2D canvas を WebGL のテクスチャとして使用することはできません。2D {{ HTMLElement("canvas") }} が汚染されたとは例えば、クロスドメインの画像が canvas 上に描画された状態を指します。

-

{{ gecko_callout_heading("9.0") }}

Canvas 2D drawImage 向けの CORS サポートが Gecko 9 {{ geckoRelease("9.0") }} で実装されました。これは、CORS で許可されたクロスドメインの画像が 2D canvas を汚染しないので、2D canvas を WebGL のテクスチャ素材として使用することが可能であり続けることを意味します。

-
-

{{ gecko_callout_heading("12.0") }}

クロスドメインの動画に対する CORS サポートと、{{ HTMLElement("video") }} 要素のcrossorigin 属性を Gecko 12 {{ geckoRelease("12.0") }} で実装しました。

-
-

{{ languages( { "en": "en/WebGL/Cross-Domain_Textures"} ) }}

diff --git a/files/ja/web/api/websockets_api/websockets_reference/index.html b/files/ja/web/api/websockets_api/websockets_reference/index.html deleted file mode 100644 index d924ac2328..0000000000 --- a/files/ja/web/api/websockets_api/websockets_reference/index.html +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: WebSockets リファレンス -slug: Web/API/WebSockets_API/WebSockets_reference -tags: - - WebSocket - - WebSockets -translation_of: Web/API/WebSockets_API -translation_of_original: Web/API/WebSockets_API/WebSockets_reference ---- -
{{draft}}
-

以下のページは、WebSocket API のインタフェースに関する文書です。

- - -
-
WebSocket
-
WebSocket のサーバに接続し、その接続上でデータを送受信するためのプライマリインターフェイス
- -
CloseEvent
-
接続を閉じる際に WebSocket オブジェクトによって送信されるイベント
- -
MessageEvent
-
サーバからのメッセージの受信時に Websocket オブジェクトによって送出されるイベント
-
diff --git a/files/ja/web/api/window.opener/index.html b/files/ja/web/api/window.opener/index.html deleted file mode 100644 index c1f7152c9c..0000000000 --- a/files/ja/web/api/window.opener/index.html +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: window.opener -slug: Web/API/window.opener -tags: - - DOM - - DOM_0 - - Gecko - - Window -translation_of: Web/API/Window/opener ---- -
{{ApiRef}}
- -

概要

- -

現在のウィンドウを開いたウィンドウへの参照を返します。

- -

構文

- -
objRef = window.opener;
-
- -

- -
if (window.opener != indexWin) {
-  referToTop(window.opener);
-}
-
- -

注記

- -

別のウィンドウから({{domxref("Window.open")}} を使用して)開かれたウィンドウは、主ウィンドウへの参照を window.opener として保持します。現在のウィンドウが別のウィンドウから開かれたものではない場合、このメソッドは NULL を返します。

- -

Windows Phone ブラウザは window.opener をサポートしていません(Edge 25.10586.36.0 でテストしました)。opener が異なるセキュリティゾーンにある場合、IE でもサポートされていません。

diff --git a/files/ja/web/api/window.stop/index.html b/files/ja/web/api/window.stop/index.html deleted file mode 100644 index a32bbd359a..0000000000 --- a/files/ja/web/api/window.stop/index.html +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: window.stop -slug: Web/API/window.stop -tags: - - API - - DOM - - Gecko - - HTML DOM -translation_of: Web/API/Window/stop ---- -
{{ApiRef}}
- -

概要

- -

このメソッドは、ウィンドウの読み込みを停止します。

- -

構文

- -
window.stop()
-
- -

- -
<script>
-stop();
-</script>
-
-<p>このパラグラフは読み込まれないでしょう。</p>​
- -

注記

- -

stop() メソッドは、ブラウザの停止ボタンをクリックすることと全く同じです。スクリプトが読み込まれる順番のために、stop() メソッドは文書の読み込みを停止できない可能性がありますが、巨大な画像、新しいウィンドウなど、読み込みを遅延させるオブジェクトの読み込みを停止することはできるでしょう。

- -

仕様

- - - - - - - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('HTML WHATWG','browsers.html#dom-window-stop','Window.stop()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-stop', 'Window.stop')}}{{Spec2('HTML5 W3C')}}
- -

互換性

- -

stop() メソッドは、Internet Explorer でサポートされません。

diff --git a/files/ja/web/api/window/arguments/index.html b/files/ja/web/api/window/arguments/index.html deleted file mode 100644 index f026024047..0000000000 --- a/files/ja/web/api/window/arguments/index.html +++ /dev/null @@ -1,7 +0,0 @@ ---- -title: window.arguments -slug: Web/API/Window/arguments -translation_of: Working_with_windows_in_chrome_code#Passing_data_between_windows -translation_of_original: Web/API/Window.arguments ---- -

『chrome コードでウィンドウを取り扱う』の頁の『ウィンドウ間でのデータのやり取り』の章をご覧下さい。

diff --git a/files/ja/web/api/window/escape/index.html b/files/ja/web/api/window/escape/index.html deleted file mode 100644 index 48ab4cab3b..0000000000 --- a/files/ja/web/api/window/escape/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: window.escape -slug: Web/API/Window/escape -tags: - - DOM - - DOM_0 - - Gecko - - Gecko DOM Reference - - Window -translation_of: Web/JavaScript/Reference/Global_Objects/escape -translation_of_original: Web/API/Window.escape ---- -
- {{ApiRef}}
-

概要

-

文字列をエンコードし、16 進エスケープシーケンスで表された特定の文字に置換します。

-

構文

-
escaped = escape(regular);
-
- -

-
alert( escape("http://www.cnn.com") ); // 表示結果: http%3A//www.cnn.com
-
-

注記

-

escape() メソッドは、特別な文字(通常のテキストや数字ではない文字)を 16 進文字にエンコードします。これは、特に、クッキーの値を設定するために必要となります。また、GET リクエストや AJAX GET/POST リクエストの URL で - - name=value - のような組のデータを渡すときにも役立ちます。

-

{{domxref("window.unescape")}} 、encodeURIComponent も参照してください。

-

仕様

-

{{DOM0}} 但し、ECMA-262 の非標準化セクションで言及されています。

diff --git a/files/ja/web/api/window/getattention/index.html b/files/ja/web/api/window/getattention/index.html deleted file mode 100644 index 4376715018..0000000000 --- a/files/ja/web/api/window/getattention/index.html +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: window.getAttention -slug: Web/API/Window/getAttention -tags: - - DOM - - DOM_0 - - Gecko - - Gecko DOM Reference - - Window -translation_of: Web/API/Window/getAttention ---- -
- {{ApiRef}}
-

概要

-

ユーザの注意を引きつける動作をします。これがどのような動作になるかは、OS と ウィンドウマネージャー次第で変化します。

-

構文

-
window.getAttention();
-
-

注記

-

Windows では、ウィンドウのタスクバーのボタンが点滅します(ユーザがこれを無効化していない場合)。

-

Linux では、挙動はウィンドウマネージャーによって変化します。タスクバーボタンが点滅するのもあれば、直ちにウィンドウにフォーカスするものもあります。これは調整可能であるかもしれません。

-

Macintosh では、デスクトップの右上端のアイコンが点滅します。

-

この関数は、Web コンテンツでは、無効化されています。Gecko も Internet Explorer も、現在はこの機能を Web コンテンツに対してはサポートしていません。getAttention は、Gecko アプリケーションでの chrome から利用したときには、いまだに動作します。

-

仕様

-

{{DOM0}}

diff --git a/files/ja/web/api/window/onafterprint/index.html b/files/ja/web/api/window/onafterprint/index.html deleted file mode 100644 index 162c81e8c6..0000000000 --- a/files/ja/web/api/window/onafterprint/index.html +++ /dev/null @@ -1,55 +0,0 @@ ---- -title: WindowEventHandlers.onafterprint -slug: Web/API/Window/onafterprint -tags: - - API - - DOM - - Event Handler - - HTML DOM - - Property - - Reference - - WindowEventHandlers - - printing -translation_of: Web/API/WindowEventHandlers/onafterprint ---- -
{{ApiRef}}
- -

{{domxref("WindowEventHandlers")}} ミックスインの onafterprint プロパティは、現在のウィンドウの {{event("afterprint")}} イベントを処理するための {{domxref("EventHandler")}} です。 このイベントは、ユーザーが印刷した後や、ユーザーが印刷ダイアログで中止した場合に発生します。

- -

{{event("beforeprint")}} イベントと afterprint イベントを使用すると、印刷を開始する前にページでコンテンツを変更し(例えば、バナーを削除するなど)、印刷の完了後にそれらの変更を元に戻すことができます。 一般に、@media print CSS @-規則の使用を好むはずですが、場合によってはこれらのイベントを使用する必要があるかもしれません。

- -

構文

- -
window.addEventListener("afterprint", function(event) { ... });
-window.onafterprint = function(event) { ... };
- -

仕様

- - - - - - - - - - - - - - -
仕様状態コメント
{{SpecName('HTML WHATWG', '#handler-window-onafterprint', 'onafterprint')}}{{Spec2('HTML WHATWG')}}
- -

ブラウザーの互換性

- - - -

{{Compat("api.WindowEventHandlers.onafterprint")}}

- -

関連情報

- - diff --git a/files/ja/web/api/window/onappinstalled/index.html b/files/ja/web/api/window/onappinstalled/index.html new file mode 100644 index 0000000000..40c22b7cec --- /dev/null +++ b/files/ja/web/api/window/onappinstalled/index.html @@ -0,0 +1,57 @@ +--- +title: Window.onappinstalled +slug: Web/API/Window/oninstall +tags: + - API + - Event Handler + - Property + - Reference + - Window + - web manifest +translation_of: Web/API/Window/onappinstalled +--- +
{{APIRef}}
+ +

{{domxref("Window")}} オブジェクトの onappinstalled プロパティは、appinstalled イベントのイベントハンドラーとして扱われます。これは、ウェブアプリケーションが プログレッシブウェブアプリ (PWA) としてインストールに成功すると発行されます。この発生したイベントは、{{domxref("Event")}} インターフェイスを実装する「単純なイベント」です。

+ +

構文

+ +
window.onappinstalled = function(event) { ... };
+
+ +

+ +
window.onappinstalled = function(ev) {
+  console.log('アプリケーションがインストールされました。');
+};
+ +

仕様

+ + + + + + + + + + + + + + + + +
仕様書策定状況備考
{{SpecName('Manifest', '#onappinstalled-attribute', 'Window.onappinstalled')}}{{Spec2('Manifest')}}初期定義
+ +

ブラウザー実装状況

+ + + +

{{Compat("api.Window.onappinstalled")}}

+ +

関連項目

+ + diff --git a/files/ja/web/api/window/onclick/index.html b/files/ja/web/api/window/onclick/index.html deleted file mode 100644 index ac36968fa6..0000000000 --- a/files/ja/web/api/window/onclick/index.html +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: window.onclick -slug: Web/API/Window/onclick -tags: - - DOM - - Gecko - - Gecko DOM Reference - - Window -translation_of: Web/API/GlobalEventHandlers/onclick -translation_of_original: Web/API/Window/onclick ---- -
- {{ApiRef}}
-

概要

-

カーソルがウィンドウ内にある時にユーザがマウスボタンをクリックした場合に呼び出されます。このイベントはどのマウスボタンを押下した場合でも発生します。イベントが発生した地点はイベントのプロパティから取得する事が出来ます。

-

構文

-
window.onclick =funcRef;
-
- -

-
<!DOCTYPE html>
-<html>
-<head>
-<meta charset="UTF-8" />
-<title>onclick のテスト</title>
-<script>
-function clickPage () {
-  alert("click event detected!");
-}
-
-window.onclick = clickPage;
-</script>
-</head>
-
-<body>
-
-<p>このページ上でマウスボタンをクリックしてみてください。</p>
-
-</body>
-</html>
-

ユーザが Window 内をクリックすると click イベントが発生します。

-

仕様

-

どの仕様書にも含まれていません。

diff --git a/files/ja/web/api/window/oninstall/index.html b/files/ja/web/api/window/oninstall/index.html deleted file mode 100644 index 40c22b7cec..0000000000 --- a/files/ja/web/api/window/oninstall/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Window.onappinstalled -slug: Web/API/Window/oninstall -tags: - - API - - Event Handler - - Property - - Reference - - Window - - web manifest -translation_of: Web/API/Window/onappinstalled ---- -
{{APIRef}}
- -

{{domxref("Window")}} オブジェクトの onappinstalled プロパティは、appinstalled イベントのイベントハンドラーとして扱われます。これは、ウェブアプリケーションが プログレッシブウェブアプリ (PWA) としてインストールに成功すると発行されます。この発生したイベントは、{{domxref("Event")}} インターフェイスを実装する「単純なイベント」です。

- -

構文

- -
window.onappinstalled = function(event) { ... };
-
- -

- -
window.onappinstalled = function(ev) {
-  console.log('アプリケーションがインストールされました。');
-};
- -

仕様

- - - - - - - - - - - - - - - - -
仕様書策定状況備考
{{SpecName('Manifest', '#onappinstalled-attribute', 'Window.onappinstalled')}}{{Spec2('Manifest')}}初期定義
- -

ブラウザー実装状況

- - - -

{{Compat("api.Window.onappinstalled")}}

- -

関連項目

- - diff --git a/files/ja/web/api/window/onmousedown/index.html b/files/ja/web/api/window/onmousedown/index.html deleted file mode 100644 index b5f947f8be..0000000000 --- a/files/ja/web/api/window/onmousedown/index.html +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: window.onmousedown -slug: Web/API/Window/onmousedown -tags: - - DOM - - Gecko - - Gecko DOM Reference - - Window -translation_of: Web/API/GlobalEventHandlers/onmousedown -translation_of_original: Web/API/Window/onmousedown ---- -
- {{ApiRef}}
-

概要

-

{{domxref("window")}} 上での mousedown イベントに対応するイベントハンドラです。

-

構文

-
window.onmousedown = funcRef;
-
- -

-
window.onmousedown = doFunc;
-
-
<!DOCTYPE html>
-<html lang="ja">
-<head>
-<meta charset="UTF-8" />
-<title>onmousedown のテスト</title>
-
-<script>
-window.onmousedown = mousedown;
-
-function mousedown() {
-  alert("mousedown イベントが発生しました。");
-}
-</script>
-
-</head>
-<body>
-<p>ページ上でのマウスクリック(右クリック、左クリック、中ボタン)で  mousedown イベントが発生します。</p>
-</body>
-</html>
-
-

注記

-

ページ上の任意の場所でマウスボタンをクリックすると mousedown イベントが発生し、アラートを表示する関数が呼び出されます。

-

仕様

-

標準仕様書には含まれていません。

diff --git a/files/ja/web/api/window/onmouseup/index.html b/files/ja/web/api/window/onmouseup/index.html deleted file mode 100644 index f7133126a9..0000000000 --- a/files/ja/web/api/window/onmouseup/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: window.onmouseup -slug: Web/API/Window/onmouseup -tags: - - DOM - - Gecko - - Gecko DOM Reference - - Window -translation_of: Web/API/GlobalEventHandlers/onmouseup -translation_of_original: Web/API/Window/onmouseup ---- -
- {{ApiRef}}
-

概要

-

{{domxref("window")}} 上の mouseup イベントに対応するイベントハンドラです。

-

構文

-
window.onmouseup = funcRef;
-
- -

-
function doFunc() {
-  alert("こんにちは!");
-}
-
-window.onmouseup = doFunc;
-
-
window.onmouseup = function() {
-  alert("こんばんは!");
-};
-
-
<!DOCTYPE html>
-<html lang="ja">
-<head>
-<meta charset="UTF-8" />
-<title>onmouseup のテスト</title>
-
-<script>
-window.onmouseup = mouseup;
-
-function mouseup() {
-  alert("mouseup イベントを検出!");
-}
-</script>
-
-</head>
-<body>
-<p>ページ上をマウスのボタンでクリックし、数秒押し続け、ボタンを放します。
-マウスのボタンを放すことで、 mouseup イベントが発生します。</p>
-</body>
-</html>
-
-

注記

-

mouseup イベントは、ドキュメント内のどこででも、ユーザがマウスの左ボタンを放すことによって発生します。

-

仕様

-

標準仕様書には含まれていません。

diff --git a/files/ja/web/api/window/onreset/index.html b/files/ja/web/api/window/onreset/index.html deleted file mode 100644 index c9862667e8..0000000000 --- a/files/ja/web/api/window/onreset/index.html +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: window.onreset -slug: Web/API/Window/onreset -tags: - - DOM - - Gecko - - Gecko DOM Reference - - Window -translation_of: Web/API/GlobalEventHandlers/onreset ---- -
- {{ApiRef}}
-

概要

-

フォームの reset イベントに対応するイベントハンドラです。

-

構文

-
window.onreset = funcRef;
-
-

引数

- -

-
<!DOCTYPE html>
-<html lang="ja">
-<head>
-<meta charset="UTF-8" />
-<title>onreset のテスト</title>
-
-<script>
-function reg() {
-  window.onreset = hit;
-}
-
-function hit() {
- alert('リセットイベントが発生しました。');
-}
-</script>
-
-</head>
-<body onload="reg();">
-
-<form>
-  <div>
-    <textarea></textarea>
-  </div>
-  <div>
-    <input type="reset" value="reset" />
-  </div>
-</form>
-
-</body>
-</html>
-
-

注記

-

reset イベントは、ユーザがフォーム内のリセットボタン (<input type="reset"/>) をクリックした際に発生します。

-

仕様

-

標準仕様書には含まれていません。

diff --git a/files/ja/web/api/window/onresize/index.html b/files/ja/web/api/window/onresize/index.html deleted file mode 100644 index db2b2bbae9..0000000000 --- a/files/ja/web/api/window/onresize/index.html +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: window.onresize -slug: Web/API/Window/onresize -tags: - - DOM - - Gecko - - Property - - Window -translation_of: Web/API/GlobalEventHandlers/onresize ---- -

{{ ApiRef() }}

- -

GlobalEventHandlers.onresize プロパティは、{{event("resize")}} イベントを受信するとトリガーされる {{domxref("EventHandler")}} を含みます。

- -

構文

- -
window.onresize = funcRef;
-
- -

引数

- - - -

- -
window.onresize = doFunc;
-
- -
<html>
-<head>
-
-<title>onresize test</title>
-
-</head>
-
-<body>
-<p>Resize the browser window to fire the resize event.</p>
-
-<p>Window height: <span id="height"></span></p>
-<p>Window width: <span id="width"></span></p>
-
-<script type="text/javascript">
-  var heightOutput = document.querySelector('#height');
-  var widthOutput = document.querySelector('#width');
-
-  function resize() {
-    heightOutput.textContent = window.innerHeight;
-    widthOutput.textContent = window.innerWidth;
-  }
-
-  window.onresize = resize;
-</script>
-</body>
-</html>
-
- -

注記

- -

ブラウザウィンドウのサイズが変更された後に resize イベントが発生します。

- -

仕様

- - - - - - - - - - - - - - -
使用ステータスコメント
{{SpecName('HTML WHATWG','webappapis.html#handler-onresize','onresize')}}{{Spec2('HTML WHATWG')}} 
diff --git a/files/ja/web/api/window/opener/index.html b/files/ja/web/api/window/opener/index.html new file mode 100644 index 0000000000..c1f7152c9c --- /dev/null +++ b/files/ja/web/api/window/opener/index.html @@ -0,0 +1,33 @@ +--- +title: window.opener +slug: Web/API/window.opener +tags: + - DOM + - DOM_0 + - Gecko + - Window +translation_of: Web/API/Window/opener +--- +
{{ApiRef}}
+ +

概要

+ +

現在のウィンドウを開いたウィンドウへの参照を返します。

+ +

構文

+ +
objRef = window.opener;
+
+ +

+ +
if (window.opener != indexWin) {
+  referToTop(window.opener);
+}
+
+ +

注記

+ +

別のウィンドウから({{domxref("Window.open")}} を使用して)開かれたウィンドウは、主ウィンドウへの参照を window.opener として保持します。現在のウィンドウが別のウィンドウから開かれたものではない場合、このメソッドは NULL を返します。

+ +

Windows Phone ブラウザは window.opener をサポートしていません(Edge 25.10586.36.0 でテストしました)。opener が異なるセキュリティゾーンにある場合、IE でもサポートされていません。

diff --git a/files/ja/web/api/window/restore/index.html b/files/ja/web/api/window/restore/index.html deleted file mode 100644 index 1510d2870e..0000000000 --- a/files/ja/web/api/window/restore/index.html +++ /dev/null @@ -1,11 +0,0 @@ ---- -title: Window.restore() -slug: Web/API/Window/restore -translation_of: Web/API/Window/moveTo -translation_of_original: Web/API/Window/restore ---- -

{{APIRef}}

- -

このメソッドは現在動作していませんが、代わりに次のメソッドを利用することができます:

- -

window.moveTo(window.screenX, window.screenY);

diff --git a/files/ja/web/api/window/stop/index.html b/files/ja/web/api/window/stop/index.html new file mode 100644 index 0000000000..a32bbd359a --- /dev/null +++ b/files/ja/web/api/window/stop/index.html @@ -0,0 +1,58 @@ +--- +title: window.stop +slug: Web/API/window.stop +tags: + - API + - DOM + - Gecko + - HTML DOM +translation_of: Web/API/Window/stop +--- +
{{ApiRef}}
+ +

概要

+ +

このメソッドは、ウィンドウの読み込みを停止します。

+ +

構文

+ +
window.stop()
+
+ +

+ +
<script>
+stop();
+</script>
+
+<p>このパラグラフは読み込まれないでしょう。</p>​
+ +

注記

+ +

stop() メソッドは、ブラウザの停止ボタンをクリックすることと全く同じです。スクリプトが読み込まれる順番のために、stop() メソッドは文書の読み込みを停止できない可能性がありますが、巨大な画像、新しいウィンドウなど、読み込みを遅延させるオブジェクトの読み込みを停止することはできるでしょう。

+ +

仕様

+ + + + + + + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('HTML WHATWG','browsers.html#dom-window-stop','Window.stop()')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'browsers.html#dom-window-stop', 'Window.stop')}}{{Spec2('HTML5 W3C')}}
+ +

互換性

+ +

stop() メソッドは、Internet Explorer でサポートされません。

diff --git a/files/ja/web/api/window/unescape/index.html b/files/ja/web/api/window/unescape/index.html deleted file mode 100644 index 07564a02ee..0000000000 --- a/files/ja/web/api/window/unescape/index.html +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: window.unescape -slug: Web/API/Window/unescape -tags: - - DOM - - DOM_0 - - Gecko - - Gecko DOM Reference - - Window -translation_of: Web/JavaScript/Reference/Global_Objects/unescape -translation_of_original: Web/API/Window.unescape ---- -
- {{ApiRef}}
-

概要

-

16 進でエンコードされた値(例えば、クッキー)をデコードします。

-

構文

-
regular = window.unescape(escaped)
- -

-
alert( unescape("%5C") );  // 表示結果: "\"
-
-alert( unescape("https%3A//developer.mozilla.org") );  // 表示結果: "https://developer.mozilla.org"
-
-

仕様

-

{{DOM0}} 但し、ECMA-262 の非標準化セクションで言及されています。

-

関連情報

- diff --git a/files/ja/web/api/window/url/index.html b/files/ja/web/api/window/url/index.html deleted file mode 100644 index ac758d1b3b..0000000000 --- a/files/ja/web/api/window/url/index.html +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: window.URL -slug: Web/API/Window/URL -tags: - - API - - DOM - - Property - - Reference - - Window -translation_of: Web/API/URL -translation_of_original: Web/API/Window/URL ---- -

{{ApiRef("Window")}}{{SeeCompatTable}}

- -

Window.URL プロパティは、オブジェクト URL の作成や操作に用いる静的なメソッドを提供します。

- -

{{AvailableInWorkers}}

- -

構文

- -

静的なメソッドの呼び出し:

- -
img.src = URL.{{domxref("URL.createObjectURL", "createObjectURL")}}(blob);
- -

新しいオブジェクトの構築:

- -
var url = new {{domxref("URL.URL", "URL")}}("../cats/", "https://www.example.com/dogs/");
- -

仕様

- - - - - - - - - - - - - - -
仕様ステータスコメント
{{SpecName('URL', '#dom-url', 'URL')}}{{Spec2('URL')}}初期定義。
- -

ブラウザー実装状況

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
機能ChromeFirefox (Gecko)Internet ExplorerOperaSafari
基本サポート8.0[2]{{CompatGeckoDesktop("2.0")}}[1]
- {{CompatGeckoDesktop("19.0")}}
10.015.0[2]6.0[2]
- 7.0
-
- -
- - - - - - - - - - - - - - - - - - - -
機能AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本サポート{{CompatVersionUnknown}}[2]{{CompatGeckoMobile("14.0")}}[1]
- {{CompatGeckoMobile("19.0")}}
{{CompatVersionUnknown}}15.0[2]6.0[2]
-
- -

[1] Gecko 2 (Firefox 4) から Gecko 18 まで、Gecko は非標準の nsIDOMMozURLProperty 内部型を返していました。 実際には、何の違いもありません。

- -

[2] 非標準の webkitURL という名前で実装されています。

diff --git a/files/ja/web/api/windowbase64/atob/index.html b/files/ja/web/api/windowbase64/atob/index.html deleted file mode 100644 index e36c89b054..0000000000 --- a/files/ja/web/api/windowbase64/atob/index.html +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: WindowOrWorkerGlobalScope.atob() -slug: Web/API/WindowBase64/atob -tags: - - API - - HTML DOM - - Method - - Reference - - WindowOrWorkerGlobalScope - - atob -translation_of: Web/API/WindowOrWorkerGlobalScope/atob ---- -

{{APIRef("HTML DOM")}}

- -

WindowOrWorkerGlobalScope.atob() 関数は、 {{glossary("Base64")}} エンコーディングでエンコードされたデータの文字列をデコードします。 {{domxref("WindowOrWorkerGlobalScope.btoa","btoa()")}} メソッドを使用して、通信に問題が発生する可能性のあるデータをエンコードして送信し、送信した後に atob() メソッドを使用して再度デコードすることができます。例えば、ASCII の 0 から 31 までのコードような制御文字をエンコードして送信し、デコードすることができます。

- -

Unicode や UTF-8 文字列の使用については、 {{domxref("WindowOrWorkerGlobalScope.btoa", "btoa()")}} の「Uncode 文字列」の節を参照してください。

- -

構文

- -
var decodedData = scope.atob(encodedData);
- -

引数

- -
-
encodedData
-
エンコードされたデータが入っているバイナリ文字列です。
-
- -

返値

- -

encodedData をデコードしたデータを含む ASCII 文字列です。

- -

例外

- -
-
{{domxref("DOMException")}} (name: InvalidCharacterError)
-
encodedData が妥当な base64 ではない場合に発行されます。
-
- -

- -
const encodedData = window.btoa('Hello, world'); // 文字列をエンコード
-const decodedData = window.atob(encodedData); // 文字列をデコード
- -

ポリフィル

- -

対応していないブラウザーでは、 https://github.com/MaxArt2501/base64-js/blob/master/base64.js のポリフィルを利用することができます。

- -

仕様書

- - - - - - - - - - - - - - - - - - - - - - - - - - -
仕様書状態備考
{{SpecName('HTML WHATWG', '#dom-atob', 'WindowOrWorkerGlobalScope.atob()')}}{{Spec2('HTML WHATWG')}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}{{SpecName("HTML WHATWG")}} のスナップショット、変更なし。
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}{{SpecName("HTML WHATWG")}} のスナップショット。 WindowBase64 の作成 (以前の対象だったプロパティ)。
- -

ブラウザーの互換性

- -
- - -

{{Compat("api.WindowOrWorkerGlobalScope.atob")}}

-
- -

関連情報

- - diff --git a/files/ja/web/api/windowbase64/base64_encoding_and_decoding/index.html b/files/ja/web/api/windowbase64/base64_encoding_and_decoding/index.html deleted file mode 100644 index 6e0e4f28db..0000000000 --- a/files/ja/web/api/windowbase64/base64_encoding_and_decoding/index.html +++ /dev/null @@ -1,558 +0,0 @@ ---- -title: Base64 のエンコードとデコード -slug: Web/API/WindowBase64/Base64_encoding_and_decoding -tags: - - Advanced - - Base64 - - JavaScript - - Typed Arrays - - URI - - URL - - Unicode Problem - - atob() - - btoa() -translation_of: Glossary/Base64 ---- -

Base64 とは、バイナリーからテキストへの符号化を行う手法のグループであり、64 を基数とする表現に変換することで、バイナリーデータを ASCII 文字列で表すことができます。Base64 という呼び方は、MIME の Content-Transfer-Encoding における特定の符号化方式の名前に由来します。

- -

Base64 符号化方式がよく使われるのは、テキストデータを扱うよう設計されたメディア上で、バイナリーデータを格納または転送する必要がある場合です。Base64 符号化により、転送中に変換されることなく、バイナリーデータがそのままであることを保証できます。Base64 は、MIME による電子メールや XML における複合型データの格納など、多くのアプリケーションで幅広く使われています。

- -

JavaScript には、Base64 文字列のエンコードとデコードのそれぞれに対応した、次の 2 つの関数があります。

- - - -

atob() 関数は、Base64 符号化方式によりエンコードされている文字列をデコードしてバイナリー文字列を作ります。逆に btoa() 関数は、バイナリー文字列から Base64 でエンコードされた ASCII 文字列を作ります。

- -

atob()btoa() のどちらも、文字列に対して動作します。もし ArrayBuffer に対して動作させたい場合は、この段落 を読んでください。

- -

符号化によるサイズ増加

- -

Base64 の 1 文字はデータのちょうど 6 ビット分を表します。そのため、入力される文字列やバイナリーファイルに含まれる 3 バイト (3×8 ビット = 24 ビット) は、4 桁の Base64 で表されます (4×6 = 24 ビット)。

- -

このことにより、Base64 で表された文字列またはファイルは、元のサイズの 133% の大きさになると言えます (33% の増加)。エンコードされるデータが小さい場合は、さらに増加幅が大きくなります。例えば、length === 1 である文字列 "a" は、エンコードされて length === 4 の文字列 "YQ==" になり、これは 300% の増加です。

- - - - - - - - -
-

参考文書

- -
-
データ URL
-
データ URL は、RFC 2397 により定義されており、 これにより文書中に小さなファイルを埋め込むことができます。
-
Base64
-
ウィキペディアの Base64 符号化方式に関する記事です。
-
WindowOrWorkerGlobalScope ミックスイン
-
atobbtoa を規定し、これらは RFC 4648 により規定された Base64 にエンコードすると定めています。
-
RFC 4648
-
セクション 4 で Base64 のアルゴリズムを規定し、またセクション 5 で URL 向けの "base64url" アルゴリズム (こちらは atobbtoa では使われない) も定義しています。
-
{{domxref("WindowBase64.atob","atob()")}}
-
Base64 によりエンコードされている ASCII 文字列をデコードして、バイナリー文字列を作ります。
-
{{domxref("WindowBase64.btoa","btoa()")}}
-
バイナリー文字列から、Base64 によりエンコードされた ASCII 文字列を作ります。
-
あの「Unicode の問題」
-
ほとんどのブラウザーでは、Unicode 文字列を使って btoa() を実行すると、Character Out Of Range 例外が発生します。この段落では、これに対するいくつかの対策を説明しています。
-
URIScheme
-
Mozilla のサポートした URI スキームのリスト
-
StringView
-
この記事では、次を狙いとしたライブラリーを公開しています -
    -
  • 文字列に対する C 言語に似たインターフェイス (すなわち文字のコードの配列であり、JavaScript では ArrayBufferView) を JavaScript の ArrayBuffer インターフェイスを使って作ること
  • -
  • 文字列に似たオブジェクト (これからは stringView) 向けの、不変である JavaScript 文字列に対してではなく必ず数値の配列に対して働く、メソッドのコレクションを作ること
  • -
  • JavaScript デフォルトである UTF-16 の DOMString 以外の Unicode でも動作すること
  • -
-
-
- -

全て表示...

-
-

ツール

- - - -

全て表示...

- - - - -
- -

あの「Unicode の問題」

- -

DOMString は 16 ビットで符号化された文字列であるので、Unicode 文字列を使って window.btoa を実行すると、8 ビットの範囲 (0x00~0xFF) を超えた文字がある場合に、ほとんどのブラウザーで Character Out Of Range 例外が発生します。以下は、この問題を解決するための 5 つの方法です。

- - - -

方法 1 – JavaScript の UTF-16 => Base64

- -

Unicode 問題を解決する、非常に高速で幅広く使われている方法は、JavaScript のネイティブ UTF-16 文字列を直接 Base64 にエンコードすることです。デモのために URL data:text/plain;charset=utf-16;base64,OCY5JjomOyY8Jj4mPyY= を開いてください (このデータ URL をコピーし、新しいタブを開き、データ URL をアドレスバーに貼り付け、エンターをを押す)。この方法は、文字列を配列に割り当てるところを除き、どのような種類の変換も必要としないため、特に効率的です。次のコードは、Base64 文字列から ArrayBuffer に変換したり、その逆変換をするのにも便利です (下記参照)。

- -
"use strict";
-
-/*\
-|*|
-|*|  Base64 / binary data / UTF-8 strings utilities (#1)
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
-|*|
-|*|  Author: madmurphy
-|*|
-\*/
-
-/* Array of bytes to base64 string decoding */
-
-function b64ToUint6 (nChr) {
-
-  return nChr > 64 && nChr < 91 ?
-      nChr - 65
-    : nChr > 96 && nChr < 123 ?
-      nChr - 71
-    : nChr > 47 && nChr < 58 ?
-      nChr + 4
-    : nChr === 43 ?
-      62
-    : nChr === 47 ?
-      63
-    :
-      0;
-
-}
-
-function base64DecToArr (sBase64, nBlockSize) {
-
-  var
-    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
-    nOutLen = nBlockSize ? Math.ceil((nInLen * 3 + 1 >>> 2) / nBlockSize) * nBlockSize : nInLen * 3 + 1 >>> 2, aBytes = new Uint8Array(nOutLen);
-
-  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
-    nMod4 = nInIdx & 3;
-    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
-    if (nMod4 === 3 || nInLen - nInIdx === 1) {
-      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
-        aBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
-      }
-      nUint24 = 0;
-    }
-  }
-
-  return aBytes;
-}
-
-/* Base64 string to array encoding */
-
-function uint6ToB64 (nUint6) {
-
-  return nUint6 < 26 ?
-      nUint6 + 65
-    : nUint6 < 52 ?
-      nUint6 + 71
-    : nUint6 < 62 ?
-      nUint6 - 4
-    : nUint6 === 62 ?
-      43
-    : nUint6 === 63 ?
-      47
-    :
-      65;
-
-}
-
-function base64EncArr (aBytes) {
-
-  var eqLen = (3 - (aBytes.length % 3)) % 3, sB64Enc = "";
-
-  for (var nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
-    nMod3 = nIdx % 3;
-    /* Uncomment the following line in order to split the output in lines 76-character long: */
-    /*
-    if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
-    */
-    nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
-    if (nMod3 === 2 || aBytes.length - nIdx === 1) {
-      sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63));
-      nUint24 = 0;
-    }
-  }
-
-  return  eqLen === 0 ?
-      sB64Enc
-    :
-      sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? "=" : "==");
-
-}
-
- -

テスト

- -
var myString = "☸☹☺☻☼☾☿";
-
-/* Part 1: `myString` をネイティブの UTF-16 を使って Base64 にエンコードする */
-
-var aUTF16CodeUnits = new Uint16Array(myString.length);
-Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) { arr[idx] = myString.charCodeAt(idx); });
-var sUTF16Base64 = base64EncArr(new Uint8Array(aUTF16CodeUnits.buffer));
-
-/* 出力を表示する */
-
-alert(sUTF16Base64); // "OCY5JjomOyY8Jj4mPyY="
-
-/* Part 2: `sUTF16Base64` を UTF-16 にデコードする */
-
-var sDecodedString = String.fromCharCode.apply(null, new Uint16Array(base64DecToArr(sUTF16Base64, 2).buffer));
-
-/* 出力を表示する */
-
-alert(sDecodedString); // "☸☹☺☻☼☾☿"
- -

生成された Base64 文字列はどこでも使えますが、UTF-16 で表現されています。もし UTF-8 を望む場合は次の方法を参照してください。

- -

方法 1 に対する補足: Base64 文字列を Uint8ArrayArrayBuffer にデコードする

- -

上記の関数を使って、Base64 でエンコードされた文字列から Uint8ArrayArrayBuffer を作ることもできます。

- -
var myArray = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw=="); // "Base 64 \u2014 Mozilla Developer Network" (as UTF-8)
-
-var myBuffer = base64DecToArr("QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw==").buffer; // "Base 64 \u2014 Mozilla Developer Network" (as UTF-8)
-
-alert(myBuffer.byteLength);
- -
注意: 関数 base64DecToArr(sBase64[, nBlockSize]) は、8 ビットの Uint8Array を返します。もし 16 ビット / 32 ビット / 64 ビットの生データのバッファを作ることが目的であれば、引数 nBlockSize を使ってください。これはバイト数であり、Uint8Array.buffer.bytesLength プロパティはその倍数になります (1 や省略された場合は ASCII、バイナリーデータ、バイナリー文字列、UTF-8 文字列向けです。2 は UTF-16 文字列向け、4 は UTF-32 文字列向けです)。
- -

完全なライブラリーは StringView – 型付き配列に基づく C 言語に似た文字列表現 を参照してください (ソースコードは GitHub で利用できます)。

- -

方法 2 – JavaScript の UTF-16 => UTF-8 => Base64

- -

この方法は、JavaScript ネイティブの UTF-16 文字列を UTF-8 文字列に変換し、それを Base64 でエンコードします。これにより、純粋な ASCII 文字列から Base64 への変換は、ネイティブの btoa() のように、常に同じ結果を出力します。

- -
"use strict";
-
-/*\
-|*|
-|*|  Base64 / binary data / UTF-8 strings utilities (#2)
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
-|*|
-|*|  Author: madmurphy
-|*|
-\*/
-
-/* Array of bytes to base64 string decoding */
-
-function b64ToUint6 (nChr) {
-
-  return nChr > 64 && nChr < 91 ?
-      nChr - 65
-    : nChr > 96 && nChr < 123 ?
-      nChr - 71
-    : nChr > 47 && nChr < 58 ?
-      nChr + 4
-    : nChr === 43 ?
-      62
-    : nChr === 47 ?
-      63
-    :
-      0;
-
-}
-
-function base64DecToArr (sBase64, nBlockSize) {
-
-  var
-    sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""), nInLen = sB64Enc.length,
-    nOutLen = nBlockSize ? Math.ceil((nInLen * 3 + 1 >>> 2) / nBlockSize) * nBlockSize : nInLen * 3 + 1 >>> 2, aBytes = new Uint8Array(nOutLen);
-
-  for (var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0; nInIdx < nInLen; nInIdx++) {
-    nMod4 = nInIdx & 3;
-    nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << 18 - 6 * nMod4;
-    if (nMod4 === 3 || nInLen - nInIdx === 1) {
-      for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
-        aBytes[nOutIdx] = nUint24 >>> (16 >>> nMod3 & 24) & 255;
-      }
-      nUint24 = 0;
-    }
-  }
-
-  return aBytes;
-}
-
-/* Base64 string to array encoding */
-
-function uint6ToB64 (nUint6) {
-
-  return nUint6 < 26 ?
-      nUint6 + 65
-    : nUint6 < 52 ?
-      nUint6 + 71
-    : nUint6 < 62 ?
-      nUint6 - 4
-    : nUint6 === 62 ?
-      43
-    : nUint6 === 63 ?
-      47
-    :
-      65;
-
-}
-
-function base64EncArr (aBytes) {
-
-  var eqLen = (3 - (aBytes.length % 3)) % 3, sB64Enc = "";
-
-  for (var nMod3, nLen = aBytes.length, nUint24 = 0, nIdx = 0; nIdx < nLen; nIdx++) {
-    nMod3 = nIdx % 3;
-    /* Uncomment the following line in order to split the output in lines 76-character long: */
-    /*
-    if (nIdx > 0 && (nIdx * 4 / 3) % 76 === 0) { sB64Enc += "\r\n"; }
-    */
-    nUint24 |= aBytes[nIdx] << (16 >>> nMod3 & 24);
-    if (nMod3 === 2 || aBytes.length - nIdx === 1) {
-      sB64Enc += String.fromCharCode(uint6ToB64(nUint24 >>> 18 & 63), uint6ToB64(nUint24 >>> 12 & 63), uint6ToB64(nUint24 >>> 6 & 63), uint6ToB64(nUint24 & 63));
-      nUint24 = 0;
-    }
-  }
-
-  return  eqLen === 0 ?
-      sB64Enc
-    :
-      sB64Enc.substring(0, sB64Enc.length - eqLen) + (eqLen === 1 ? "=" : "==");
-
-}
-
-/* UTF-8 array to DOMString and vice versa */
-
-function UTF8ArrToStr (aBytes) {
-
-  var sView = "";
-
-  for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {
-    nPart = aBytes[nIdx];
-    sView += String.fromCharCode(
-      nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */
-        /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */
-        (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
-      : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */
-        (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
-      : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */
-        (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
-      : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */
-        (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128
-      : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */
-        (nPart - 192 << 6) + aBytes[++nIdx] - 128
-      : /* nPart < 127 ? */ /* one byte */
-        nPart
-    );
-  }
-
-  return sView;
-
-}
-
-function strToUTF8Arr (sDOMStr) {
-
-  var aBytes, nChr, nStrLen = sDOMStr.length, nArrLen = 0;
-
-  /* mapping... */
-
-  for (var nMapIdx = 0; nMapIdx < nStrLen; nMapIdx++) {
-    nChr = sDOMStr.charCodeAt(nMapIdx);
-    nArrLen += nChr < 0x80 ? 1 : nChr < 0x800 ? 2 : nChr < 0x10000 ? 3 : nChr < 0x200000 ? 4 : nChr < 0x4000000 ? 5 : 6;
-  }
-
-  aBytes = new Uint8Array(nArrLen);
-
-  /* transcription... */
-
-  for (var nIdx = 0, nChrIdx = 0; nIdx < nArrLen; nChrIdx++) {
-    nChr = sDOMStr.charCodeAt(nChrIdx);
-    if (nChr < 128) {
-      /* one byte */
-      aBytes[nIdx++] = nChr;
-    } else if (nChr < 0x800) {
-      /* two bytes */
-      aBytes[nIdx++] = 192 + (nChr >>> 6);
-      aBytes[nIdx++] = 128 + (nChr & 63);
-    } else if (nChr < 0x10000) {
-      /* three bytes */
-      aBytes[nIdx++] = 224 + (nChr >>> 12);
-      aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
-      aBytes[nIdx++] = 128 + (nChr & 63);
-    } else if (nChr < 0x200000) {
-      /* four bytes */
-      aBytes[nIdx++] = 240 + (nChr >>> 18);
-      aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
-      aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
-      aBytes[nIdx++] = 128 + (nChr & 63);
-    } else if (nChr < 0x4000000) {
-      /* five bytes */
-      aBytes[nIdx++] = 248 + (nChr >>> 24);
-      aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
-      aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
-      aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
-      aBytes[nIdx++] = 128 + (nChr & 63);
-    } else /* if (nChr <= 0x7fffffff) */ {
-      /* six bytes */
-      aBytes[nIdx++] = 252 + (nChr >>> 30);
-      aBytes[nIdx++] = 128 + (nChr >>> 24 & 63);
-      aBytes[nIdx++] = 128 + (nChr >>> 18 & 63);
-      aBytes[nIdx++] = 128 + (nChr >>> 12 & 63);
-      aBytes[nIdx++] = 128 + (nChr >>> 6 & 63);
-      aBytes[nIdx++] = 128 + (nChr & 63);
-    }
-  }
-
-  return aBytes;
-
-}
- -

テスト

- -
/* テスト */
-
-var sMyInput = "Base 64 \u2014 Mozilla Developer Network";
-
-var aMyUTF8Input = strToUTF8Arr(sMyInput);
-
-var sMyBase64 = base64EncArr(aMyUTF8Input);
-
-alert(sMyBase64); // "QmFzZSA2NCDigJQgTW96aWxsYSBEZXZlbG9wZXIgTmV0d29yaw=="
-
-var aMyUTF8Output = base64DecToArr(sMyBase64);
-
-var sMyOutput = UTF8ArrToStr(aMyUTF8Output);
-
-alert(sMyOutput); // "Base 64 — Mozilla Developer Network"
- -

方法 3 – JavaScript の UTF-16 => バイナリー文字列 => Base64

- -

これは、最も速く最もコンパクトな方法です。出力は方法 1 (UTF-16 ででエンコードされた文字列) のものと全く同じですが、{{domxref("WindowBase64.atob","atob()")}} と {{domxref("WindowBase64.btoa","btoa()")}} を書き直すのではなく、ネイティブのものを使います。この方法はエンコードまたはデコードの入力として、型付き配列の代わりに、中間フォーマットであるバイナリー文字列を使います。方法 1 (バイナリー文字列 は灰色の領域です) に比べると、これは「汚い」回避策ではありますが、問題なく動作し、必要なコードはわずか数行です。

- -
"use strict";
-
-/*\
-|*|
-|*|  Base64 / binary data / UTF-8 strings utilities (#3)
-|*|
-|*|  https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
-|*|
-|*|  Author: madmurphy
-|*|
-\*/
-
-function btoaUTF16 (sString) {
-
-	var aUTF16CodeUnits = new Uint16Array(sString.length);
-	Array.prototype.forEach.call(aUTF16CodeUnits, function (el, idx, arr) { arr[idx] = sString.charCodeAt(idx); });
-	return btoa(String.fromCharCode.apply(null, new Uint8Array(aUTF16CodeUnits.buffer)));
-
-}
-
-function atobUTF16 (sBase64) {
-
-	var sBinaryString = atob(sBase64), aBinaryView = new Uint8Array(sBinaryString.length);
-	Array.prototype.forEach.call(aBinaryView, function (el, idx, arr) { arr[idx] = sBinaryString.charCodeAt(idx); });
-	return String.fromCharCode.apply(null, new Uint16Array(aBinaryView.buffer));
-
-}
- -

テスト

- -
var myString = "☸☹☺☻☼☾☿";
-
-/* Part 1: `myString` をネイティブの UTF-16 を使って Base64 にエンコードする */
-
-var sUTF16Base64 = btoaUTF16(myString);
-
-/* 出力を表示する */
-
-alert(sUTF16Base64); // "OCY5JjomOyY8Jj4mPyY="
-
-/* Part 2: `sUTF16Base64` を UTF-16 にデコードする */
-
-var sDecodedString = atobUTF16(sUTF16Base64);
-
-/* 出力を表示する */
-
-alert(sDecodedString); // "☸☹☺☻☼☾☿"
-
- -

バイナリー文字列の代わりに型付き配列を使う、よりクリーンな方法については、方法 1方法 2 を参照してください。

- -

方法 4 – エンコード前に文字列をエスケープ処理する

- -
function b64EncodeUnicode(str) {
-    // 最初に encodeURIComponent を使って "%" でエンコードされた UTF-8 文字列を取得し、
-    // 次に "%" でエンコードされた文字列をバイナリー文字列に変換し、
-    // それを btoa に与えます。
-    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
-        function toSolidBytes(match, p1) {
-            return String.fromCharCode('0x' + p1);
-    }));
-}
-
-b64EncodeUnicode('✓ à la mode'); // "4pyTIMOgIGxhIG1vZGU="
-b64EncodeUnicode('\n'); // "Cg=="
-
- -

Base64 でエンコードされた値を元の文字列に戻すには、次のようにします。

- -
function b64DecodeUnicode(str) {
-    // 逆変換: バイナリー文字列から "%" エンコードへ、そしてオリジナルの文字列へ。
-    return decodeURIComponent(atob(str).split('').map(function(c) {
-        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
-    }).join(''));
-}
-
-b64DecodeUnicode('4pyTIMOgIGxhIG1vZGU='); // "✓ à la mode"
-b64DecodeUnicode('Cg=='); // "\n"
-
- -

Unibabel は、この方法を使った共通の変換を実装しています。

- -

方法 5 – DOM の atob()btoa() を JavaScript の TypedArray と UTF-8 を使って書き換える

- -

TextEncoder のポリフィル、例えば TextEncoding (レガシーの Windows、Mac、ISO のエンコーディングも含む) や TextEncoderLite を、モダンブラウザーと Node.js の両方で使える Buffer または base64-jsTypeScript 版の base64-js のような Base64 実装とを、組み合わせて使います。

- -

ネイティブの TextEncoder 実装がない場合、最も軽量な方法は 方法 3 でしょう。なぜなら、とても高速であることに加え、方法 3 は標準状態の IE9 でも動作するからです。 もう一つの方法は、TextEncoderLitebase64-js を使うことです。可能な場合はブラウザーの実装を使ってください。

- -

次の関数は、この考えを実装したものです。これは、base64-js が <script type="text/javascript" src="base64js.min.js"/> のようにインポートされていることを前提にしています。TextEncoderLite は UTF-8 でのみ機能することに注意してください。

- -
function Base64Encode(str, encoding = 'utf-8') {
-    var bytes = new (typeof TextEncoder === "undefined" ? TextEncoderLite : TextEncoder)(encoding).encode(str);
-    return base64js.fromByteArray(bytes);
-}
-
-function Base64Decode(str, encoding = 'utf-8') {
-    var bytes = base64js.toByteArray(str);
-    return new (typeof TextDecoder === "undefined" ? TextDecoderLite : TextDecoder)(encoding).decode(bytes);
-}
-
- -

Note: TextEncoderLite は、4 バイトの UTF-8 文字、つまり '\uD842\uDFB7' や '\u{20BB7}' のような文字を誤って解釈します。この Issue を参照してください。
- あるいは、代わりに text-encoding を使ってください。

- -

いくつかの場合には、UTF-8 に変換した後 Base64 にする上記の方法は、記憶領域に対してとても非効率的です。U+0800 から U+FFFF の範囲にある文字は、UTF-8 では 3 バイトにエンコードされますが UTF-16 では 2 バイトであり、これらがテキストの大部分を占める場合、UTF-8 の出力長は UTF-16 よりも長くなります。均等に分散した UTF-16 コードポイントを含む JavaScript 文字列の場合、Base64 の変換の前のエンコードを UTF-8 ではなく UTF-16 にすることで、サイズを 40% 減少できます。

diff --git a/files/ja/web/api/windowbase64/index.html b/files/ja/web/api/windowbase64/index.html deleted file mode 100644 index 760541b9c5..0000000000 --- a/files/ja/web/api/windowbase64/index.html +++ /dev/null @@ -1,116 +0,0 @@ ---- -title: WindowBase64 -slug: Web/API/WindowBase64 -tags: - - API -translation_of: Web/API/WindowOrWorkerGlobalScope -translation_of_original: Web/API/WindowBase64 ---- -

{{APIRef("HTML DOM")}}

- -

The WindowBase64 helper contains utility methods to convert data to and from base64, a binary-to-text encoding scheme. For example it is used in data URIs.

- -

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

- -

Properties

- -

This helper neither defines nor inherits any properties.

- -

Methods

- -

This helper does not inherit any methods.

- -
-
{{domxref("WindowBase64.atob()")}}
-
Decodes a string of data which has been encoded using base-64 encoding.
-
{{domxref("WindowBase64.btoa()")}}
-
Creates a base-64 encoded ASCII string from a string of binary data.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowbase64', 'WindowBase64')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowbase64", "WindowBase64")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}} [1]{{CompatVersionUnknown}}10.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

[1]  atob() is also available to XPCOM components implemented in JavaScript, even though {{domxref("Window")}} is not the global object in components.

- -

See also

- - diff --git a/files/ja/web/api/windoweventhandlers/onafterprint/index.html b/files/ja/web/api/windoweventhandlers/onafterprint/index.html new file mode 100644 index 0000000000..162c81e8c6 --- /dev/null +++ b/files/ja/web/api/windoweventhandlers/onafterprint/index.html @@ -0,0 +1,55 @@ +--- +title: WindowEventHandlers.onafterprint +slug: Web/API/Window/onafterprint +tags: + - API + - DOM + - Event Handler + - HTML DOM + - Property + - Reference + - WindowEventHandlers + - printing +translation_of: Web/API/WindowEventHandlers/onafterprint +--- +
{{ApiRef}}
+ +

{{domxref("WindowEventHandlers")}} ミックスインの onafterprint プロパティは、現在のウィンドウの {{event("afterprint")}} イベントを処理するための {{domxref("EventHandler")}} です。 このイベントは、ユーザーが印刷した後や、ユーザーが印刷ダイアログで中止した場合に発生します。

+ +

{{event("beforeprint")}} イベントと afterprint イベントを使用すると、印刷を開始する前にページでコンテンツを変更し(例えば、バナーを削除するなど)、印刷の完了後にそれらの変更を元に戻すことができます。 一般に、@media print CSS @-規則の使用を好むはずですが、場合によってはこれらのイベントを使用する必要があるかもしれません。

+ +

構文

+ +
window.addEventListener("afterprint", function(event) { ... });
+window.onafterprint = function(event) { ... };
+ +

仕様

+ + + + + + + + + + + + + + +
仕様状態コメント
{{SpecName('HTML WHATWG', '#handler-window-onafterprint', 'onafterprint')}}{{Spec2('HTML WHATWG')}}
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.WindowEventHandlers.onafterprint")}}

+ +

関連情報

+ + diff --git a/files/ja/web/api/windoworworkerglobalscope/atob/index.html b/files/ja/web/api/windoworworkerglobalscope/atob/index.html new file mode 100644 index 0000000000..e36c89b054 --- /dev/null +++ b/files/ja/web/api/windoworworkerglobalscope/atob/index.html @@ -0,0 +1,93 @@ +--- +title: WindowOrWorkerGlobalScope.atob() +slug: Web/API/WindowBase64/atob +tags: + - API + - HTML DOM + - Method + - Reference + - WindowOrWorkerGlobalScope + - atob +translation_of: Web/API/WindowOrWorkerGlobalScope/atob +--- +

{{APIRef("HTML DOM")}}

+ +

WindowOrWorkerGlobalScope.atob() 関数は、 {{glossary("Base64")}} エンコーディングでエンコードされたデータの文字列をデコードします。 {{domxref("WindowOrWorkerGlobalScope.btoa","btoa()")}} メソッドを使用して、通信に問題が発生する可能性のあるデータをエンコードして送信し、送信した後に atob() メソッドを使用して再度デコードすることができます。例えば、ASCII の 0 から 31 までのコードような制御文字をエンコードして送信し、デコードすることができます。

+ +

Unicode や UTF-8 文字列の使用については、 {{domxref("WindowOrWorkerGlobalScope.btoa", "btoa()")}} の「Uncode 文字列」の節を参照してください。

+ +

構文

+ +
var decodedData = scope.atob(encodedData);
+ +

引数

+ +
+
encodedData
+
エンコードされたデータが入っているバイナリ文字列です。
+
+ +

返値

+ +

encodedData をデコードしたデータを含む ASCII 文字列です。

+ +

例外

+ +
+
{{domxref("DOMException")}} (name: InvalidCharacterError)
+
encodedData が妥当な base64 ではない場合に発行されます。
+
+ +

+ +
const encodedData = window.btoa('Hello, world'); // 文字列をエンコード
+const decodedData = window.atob(encodedData); // 文字列をデコード
+ +

ポリフィル

+ +

対応していないブラウザーでは、 https://github.com/MaxArt2501/base64-js/blob/master/base64.js のポリフィルを利用することができます。

+ +

仕様書

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
仕様書状態備考
{{SpecName('HTML WHATWG', '#dom-atob', 'WindowOrWorkerGlobalScope.atob()')}}{{Spec2('HTML WHATWG')}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName('HTML5.1', '#dom-windowbase64-atob', 'WindowBase64.atob()')}}{{Spec2('HTML5.1')}}{{SpecName("HTML WHATWG")}} のスナップショット、変更なし。
{{SpecName("HTML5 W3C", "#dom-windowbase64-atob", "WindowBase64.atob()")}}{{Spec2('HTML5 W3C')}}{{SpecName("HTML WHATWG")}} のスナップショット。 WindowBase64 の作成 (以前の対象だったプロパティ)。
+ +

ブラウザーの互換性

+ +
+ + +

{{Compat("api.WindowOrWorkerGlobalScope.atob")}}

+
+ +

関連情報

+ + diff --git a/files/ja/web/api/windoworworkerglobalscope/caches/index.html b/files/ja/web/api/windoworworkerglobalscope/caches/index.html new file mode 100644 index 0000000000..5d4002bd19 --- /dev/null +++ b/files/ja/web/api/windoworworkerglobalscope/caches/index.html @@ -0,0 +1,82 @@ +--- +title: WorkerGlobalScope.caches +slug: Web/API/WorkerGlobalScope/caches +tags: + - API + - Experimental + - Property + - Read-only + - Reference + - Service Workers + - Web Workers + - Window + - WindowOrWorkerGlobalScope +translation_of: Web/API/WindowOrWorkerGlobalScope/caches +--- +
{{APIRef()}}{{SeeCompatTable}}
+ +

{{domxref("WindowOrWorkerGlobalScope")}} インターフェイスの caches 読み取り専用プロパティは、現在のワーカーコンテキストに関連する {{domxref("CacheStorage")}} オブジェクトを返します。このオブジェクトにより、オフライン利用のために資産 (assets、アセット) を保存したり、リクエストに対するカスタムレスポンスを生成したりするなどの機能を使用できます。

+ +

構文

+ +
var myCacheStorage = self.caches; // または単に caches
+
+ +

+ +

{{domxref("CacheStorage")}}。

+ +

+ +

次の例では、アセットをオフラインで利用できるようにするために、ServiceWorker コンテキストでキャッシュを使う方法を示しています。

+ +
this.addEventListener('install', function(event) {
+  event.waitUntil(
+    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'
+      );
+    })
+  );
+});
+ +

仕様

+ + + + + + + + + + + + + + +
仕様ステータスコメント
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}初期定義。
+ +

ブラウザー実装状況

+ + + +

{{Compat("api.WindowOrWorkerGlobalScope.caches")}}

+ +

関連項目

+ + diff --git a/files/ja/web/api/windoworworkerglobalscope/clearinterval/index.html b/files/ja/web/api/windoworworkerglobalscope/clearinterval/index.html new file mode 100644 index 0000000000..ceb7c2ebbe --- /dev/null +++ b/files/ja/web/api/windoworworkerglobalscope/clearinterval/index.html @@ -0,0 +1,122 @@ +--- +title: window.clearInterval +slug: Web/API/WindowTimers/clearInterval +tags: + - DOM + - DOM_0 + - Gecko + - JavaScript timers + - Window +translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval +--- +
{{ApiRef}}
+ +

概要

+ +

{{domxref("window.setInterval", "setInterval")}} を使用して設定された繰り返し動作をキャンセルします。

+ +

構文

+ +
window.clearInterval(intervalID)
+
+ + + +

+ +

{{domxref("window.setInterval", "setInterval()", "example")}} の例を参照して下さい。

+ +

仕様

+ + + + + + + + + + + + + + + + + + + +
仕様書策定状況コメント
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setInterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName("HTML WHATWG", "webappapis.html#dom-setInterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}} 
+ +

ブラウザー実装状況

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + +
機能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本サポート1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}
+ {{CompatGeckoDesktop("52")}}[1]
4.04.01.0
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
機能AndroidAndroid 版 ChromeEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本サポート1.01.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}
+ {{CompatGeckoMobile("52")}}[1]
6.06.01.0
+
+ +

[1] clearInterval() は現在継承され{{domxref("WindowOrWorkerGlobalScope")}}に定義されています.

+ +

関連情報

+ + diff --git a/files/ja/web/api/windowtimers/clearinterval/index.html b/files/ja/web/api/windowtimers/clearinterval/index.html deleted file mode 100644 index ceb7c2ebbe..0000000000 --- a/files/ja/web/api/windowtimers/clearinterval/index.html +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: window.clearInterval -slug: Web/API/WindowTimers/clearInterval -tags: - - DOM - - DOM_0 - - Gecko - - JavaScript timers - - Window -translation_of: Web/API/WindowOrWorkerGlobalScope/clearInterval ---- -
{{ApiRef}}
- -

概要

- -

{{domxref("window.setInterval", "setInterval")}} を使用して設定された繰り返し動作をキャンセルします。

- -

構文

- -
window.clearInterval(intervalID)
-
- - - -

- -

{{domxref("window.setInterval", "setInterval()", "example")}} の例を参照して下さい。

- -

仕様

- - - - - - - - - - - - - - - - - - - -
仕様書策定状況コメント
{{SpecName('HTML WHATWG', 'webappapis.html#dom-setInterval', 'WindowOrWorkerGlobalScope.clearInterval()')}}{{Spec2("HTML WHATWG")}}最新の仕様で、メソッドを WindowOrWorkerGlobalScope ミックスインに移動。
{{SpecName("HTML WHATWG", "webappapis.html#dom-setInterval", "WindowTimers.setInterval()")}}{{Spec2("HTML WHATWG")}} 
- -

ブラウザー実装状況

- -
{{CompatibilityTable}}
- -
- - - - - - - - - - - - - - - - - - - - - -
機能ChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
基本サポート1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}
- {{CompatGeckoDesktop("52")}}[1]
4.04.01.0
-
- -
- - - - - - - - - - - - - - - - - - - - - - - -
機能AndroidAndroid 版 ChromeEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
基本サポート1.01.0{{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}
- {{CompatGeckoMobile("52")}}[1]
6.06.01.0
-
- -

[1] clearInterval() は現在継承され{{domxref("WindowOrWorkerGlobalScope")}}に定義されています.

- -

関連情報

- - diff --git a/files/ja/web/api/windowtimers/index.html b/files/ja/web/api/windowtimers/index.html deleted file mode 100644 index 549969232f..0000000000 --- a/files/ja/web/api/windowtimers/index.html +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: WindowTimers -slug: Web/API/WindowTimers -tags: - - API -translation_of: Web/API/WindowOrWorkerGlobalScope -translation_of_original: Web/API/WindowTimers ---- -
{{APIRef("HTML DOM")}}
- -

WindowTimers contains utility methods to set and clear timers.

- -

There is no object of this type, though the context object, either the {{domxref("Window")}} for regular browsing scope, or the {{domxref("WorkerGlobalScope")}}  for workers, implements it.

- -

Properties

- -

This interface do not define any property, nor inherit any.

- -

Methods

- -

This interface do not inherit any method.

- -
-
{{domxref("WindowTimers.clearInterval()")}}
-
Cancels the repeated execution set using {{domxref("WindowTimers.setInterval()")}}.
-
{{domxref("WindowTimers.clearTimeout()")}}
-
Cancels the repeated execution set using {{domxref("WindowTimers.setTimeout()")}}.
-
{{domxref("WindowTimers.setInterval()")}}
-
Schedules the execution of a function each X milliseconds.
-
{{domxref("WindowTimers.setTimeout()")}}
-
Sets a delay for executing a function.
-
- -

Specifications

- - - - - - - - - - - - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML WHATWG')}}No change since the latest snapshot, {{SpecName("HTML5.1")}}.
{{SpecName('HTML5.1', '#windowtimers', 'WindowTimers')}}{{Spec2('HTML5.1')}}Snapshot of {{SpecName("HTML WHATWG")}}. No change.
{{SpecName("HTML5 W3C", "#windowtimers", "WindowTimers")}}{{Spec2('HTML5 W3C')}}Snapshot of {{SpecName("HTML WHATWG")}}. Creation of WindowBase64 (properties where on the target before it).
- -

Browser compatibility

- -

{{CompatibilityTable}}

- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox (Gecko)ChromeInternet ExplorerOperaSafari
Basic support{{CompatGeckoDesktop(1)}}1.04.04.01.0
-
- -
- - - - - - - - - - - - - - - - - - - -
FeatureFirefox Mobile (Gecko)AndroidIE MobileOpera MobileSafari Mobile
Basic support{{CompatGeckoMobile(1)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
-
- -

 

- -

See also

- - diff --git a/files/ja/web/api/workerglobalscope/caches/index.html b/files/ja/web/api/workerglobalscope/caches/index.html deleted file mode 100644 index 5d4002bd19..0000000000 --- a/files/ja/web/api/workerglobalscope/caches/index.html +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: WorkerGlobalScope.caches -slug: Web/API/WorkerGlobalScope/caches -tags: - - API - - Experimental - - Property - - Read-only - - Reference - - Service Workers - - Web Workers - - Window - - WindowOrWorkerGlobalScope -translation_of: Web/API/WindowOrWorkerGlobalScope/caches ---- -
{{APIRef()}}{{SeeCompatTable}}
- -

{{domxref("WindowOrWorkerGlobalScope")}} インターフェイスの caches 読み取り専用プロパティは、現在のワーカーコンテキストに関連する {{domxref("CacheStorage")}} オブジェクトを返します。このオブジェクトにより、オフライン利用のために資産 (assets、アセット) を保存したり、リクエストに対するカスタムレスポンスを生成したりするなどの機能を使用できます。

- -

構文

- -
var myCacheStorage = self.caches; // または単に caches
-
- -

- -

{{domxref("CacheStorage")}}。

- -

- -

次の例では、アセットをオフラインで利用できるようにするために、ServiceWorker コンテキストでキャッシュを使う方法を示しています。

- -
this.addEventListener('install', function(event) {
-  event.waitUntil(
-    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'
-      );
-    })
-  );
-});
- -

仕様

- - - - - - - - - - - - - - -
仕様ステータスコメント
{{SpecName('Service Workers')}}{{Spec2('Service Workers')}}初期定義。
- -

ブラウザー実装状況

- - - -

{{Compat("api.WindowOrWorkerGlobalScope.caches")}}

- -

関連項目

- - diff --git a/files/ja/web/api/xmldocument/async/index.html b/files/ja/web/api/xmldocument/async/index.html new file mode 100644 index 0000000000..00d0b0724c --- /dev/null +++ b/files/ja/web/api/xmldocument/async/index.html @@ -0,0 +1,45 @@ +--- +title: XMLDocument.async +slug: Web/API/Document/async +tags: + - API + - DOM + - DOM Reference + - Deprecated + - Document + - Non-standard + - Property + - Reference + - async +translation_of: Web/API/XMLDocument/async +--- +

{{APIRef("DOM")}}{{Non-standard_header}}{{Deprecated_header}}

+ +

document.async は、 {{DOMxRef("XMLDocument.load()")}} の呼び出しを同期で行うか、または非同期で行うかの指示を真偽値で設定します。 true が初期値であり、これは文書を非同期的に読み込むよう要求するものです。

+ +

(1.4 アルファから、同期的に文書を読み込めるようになりました。)

+ +

+ +
function loadXMLData(e) {
+  alert(new XMLSerializer().serializeToString(e.target)); // querydata.xml の内容を文字列として取得
+}
+
+var xmlDoc = document.implementation.createDocument("", "test", null);
+
+xmlDoc.async = false;
+xmlDoc.onload = loadXMLData;
+xmlDoc.load('querydata.xml');
+ +

ブラウザーの互換性

+ + + +

{{Compat("api.XMLDocument.async")}}

+ +

関連情報

+ + diff --git a/files/ja/web/api/xmlserializer/index.html b/files/ja/web/api/xmlserializer/index.html new file mode 100644 index 0000000000..685fdcc100 --- /dev/null +++ b/files/ja/web/api/xmlserializer/index.html @@ -0,0 +1,101 @@ +--- +title: XMLSerializer +slug: XMLSerializer +tags: + - Converting + - DOM Parsing + - Interface + - Parsing + - Reference + - Serialization + - Serializing + - XML + - XML Serializer + - conversion +translation_of: Web/API/XMLSerializer +--- +
{{APIRef("XMLSerializer")}}
+ +

XMLSerializer インターフェースは、{{Glossary("DOM")}} ツリーを表す XML 文字列を構築するための {{domxref("XMLSerializer.serializeToString", "serializeToString()")}} メソッドを提供します。

+ +

メソッド

+ +
+
{{domxref("XMLSerializer.serializeToString", "serializeToString()")}}
+
文字列の形にシリアライズされたサブツリーを返します。
+
{{domxref("XMLSerializer.serializeToStream", "serializeToStream()")}} {{ non-standard_inline }}{{ deprecated_inline }}
+
指定した要素をルートとするサブツリーが、指定した文字セットを使ったバイトストリームにシリアライズされます。
+
+ +

+ +

XML を文字列にシリアライズ

+ +

最初の基本的な例は、ドキュメント全体を XML を含む文字列にシリアライズするだけです。

+ +
 var s = new XMLSerializer();
+ var d = document;
+ var str = s.serializeToString(d);
+ saveXML(str);
+ +

このコードは、新しい XMLSerializer オブジェクトを作成し、シリアライズされる {{domxref("Document")}} を {{domxref("XMLSerializer.serializeToString", "serializeToString()")}} に渡します。これは、渡した document と同等の XML を返します。

+ +

XML を基にした DOM にノードを挿入する

+ +

この例は、{{domxref("Element.insertAdjacentHTML()")}} メソッドを使用して新しい DOM {{domxref("Node")}} を {{domxref("Document")}} の body に挿入します。これは、{{domxref("Element")}} オブジェクトをシリアライズすることにより作成された XML を基にしています。

+ +
+

注記: 実際は、{{domxref("Document.importNode", "importNode()")}} メソッドを呼び出して新しいノードを DOM に挿入する代わりに、以下のいずれかのメソッドを呼び出して DOM ツリーに追加することになるでしょう:

+ + +
+ +

insertAdjacentHTML() は文字列を受け入れるが、2 番目の引数として Node を受け入れないため、XMLSerializer を使用して先にノードを文字列に変換します。

+ +
var inp = document.createElement('input');
+var XMLS = new XMLSerializer();
+var inp_xmls = XMLS.serializeToString(inp); // まず DOM ノードを文字列に変換
+
+// 新たに作成されたノードを document の body に挿入
+document.body.insertAdjacentHTML('afterbegin', inp_xmls);
+ +

このコードは、{{domxref("Document.createElement()")}} を呼び出して新しい {{HTMLElement("input")}} 要素を作成し、{{domxref("XMLSerializer.serializeToString", "serializeToString()")}} を使用して XML にシリアライズします。

+ +

完了したら、insertAdjacentHTML() を使用して <input> 要素を DOM に挿入します。

+ +

仕様

+ + + + + + + + + + + + + + +
仕様書策定状況備考
{{SpecName('DOM Parsing', '#the-xmlserializer-interface', 'XMLSerializer')}}{{Spec2('DOM Parsing')}}
+ +

ブラウザーの実装状況

+ +
+ + +

{{Compat("api.XMLSerializer")}}

+
+ +

関連項目

+ + -- cgit v1.2.3-54-g00ecf