From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- files/ko/web/html/applying_color/index.html | 510 ++++++++++++ .../ko/web/html/attributes/autocomplete/index.html | 247 ++++++ .../ko/web/html/attributes/crossorigin/index.html | 96 +++ files/ko/web/html/attributes/index.html | 733 +++++++++++++++++ files/ko/web/html/block-level_elements/index.html | 127 +++ files/ko/web/html/canvas/index.html | 135 ++++ .../manipulating_video_using_canvas/index.html | 164 ++++ .../canvas/tutorial/advanced_animations/index.html | 376 +++++++++ .../tutorial/applying_styles_and_colors/index.html | 732 +++++++++++++++++ .../canvas/tutorial/basic_animations/index.html | 310 ++++++++ .../html/canvas/tutorial/basic_usage/index.html | 154 ++++ .../canvas/tutorial/compositing/example/index.html | 293 +++++++ .../html/canvas/tutorial/compositing/index.html | 106 +++ .../html/canvas/tutorial/drawing_shapes/index.html | 577 ++++++++++++++ .../ko/web/html/canvas/tutorial/finale/index.html | 51 ++ .../hit_regions_and_accessibility/index.html | 97 +++ files/ko/web/html/canvas/tutorial/index.html | 62 ++ .../canvas/tutorial/optimizing_canvas/index.html | 110 +++ .../html/canvas/tutorial/using_images/index.html | 347 +++++++++ .../tutorial/\353\263\200\355\230\225/index.html" | 286 +++++++ files/ko/web/html/cors_enabled_image/index.html | 112 +++ files/ko/web/html/element/a/index.html | 489 ++++++++++++ files/ko/web/html/element/abbr/index.html | 194 +++++ files/ko/web/html/element/address/index.html | 128 +++ files/ko/web/html/element/applet/index.html | 115 +++ files/ko/web/html/element/area/index.html | 184 +++++ files/ko/web/html/element/article/index.html | 137 ++++ files/ko/web/html/element/aside/index.html | 122 +++ files/ko/web/html/element/audio/index.html | 417 ++++++++++ files/ko/web/html/element/b/index.html | 121 +++ files/ko/web/html/element/base/index.html | 136 ++++ files/ko/web/html/element/bdo/index.html | 111 +++ files/ko/web/html/element/blockquote/index.html | 131 ++++ files/ko/web/html/element/body/index.html | 166 ++++ files/ko/web/html/element/br/index.html | 130 ++++ files/ko/web/html/element/button/index.html | 293 +++++++ files/ko/web/html/element/canvas/index.html | 194 +++++ files/ko/web/html/element/caption/index.html | 153 ++++ files/ko/web/html/element/center/index.html | 51 ++ files/ko/web/html/element/cite/index.html | 143 ++++ files/ko/web/html/element/code/index.html | 109 +++ files/ko/web/html/element/col/index.html | 159 ++++ files/ko/web/html/element/colgroup/index.html | 142 ++++ files/ko/web/html/element/command/index.html | 111 +++ files/ko/web/html/element/content/index.html | 101 +++ files/ko/web/html/element/data/index.html | 104 +++ files/ko/web/html/element/datalist/index.html | 115 +++ files/ko/web/html/element/dd/index.html | 111 +++ files/ko/web/html/element/del/index.html | 140 ++++ files/ko/web/html/element/details/index.html | 284 +++++++ files/ko/web/html/element/dfn/index.html | 196 +++++ files/ko/web/html/element/dialog/index.html | 180 +++++ files/ko/web/html/element/div/index.html | 147 ++++ files/ko/web/html/element/dl/index.html | 223 ++++++ files/ko/web/html/element/dt/index.html | 99 +++ files/ko/web/html/element/element/index.html | 57 ++ files/ko/web/html/element/em/index.html | 124 +++ files/ko/web/html/element/embed/index.html | 81 ++ files/ko/web/html/element/fieldset/index.html | 151 ++++ files/ko/web/html/element/figcaption/index.html | 88 +++ files/ko/web/html/element/figure/index.html | 175 +++++ files/ko/web/html/element/font/index.html | 48 ++ files/ko/web/html/element/footer/index.html | 109 +++ files/ko/web/html/element/form/index.html | 186 +++++ files/ko/web/html/element/frame/index.html | 56 ++ files/ko/web/html/element/frameset/index.html | 39 + files/ko/web/html/element/head/index.html | 129 +++ files/ko/web/html/element/header/index.html | 109 +++ .../web/html/element/heading_elements/index.html | 242 ++++++ files/ko/web/html/element/hgroup/index.html | 105 +++ files/ko/web/html/element/hr/index.html | 131 ++++ files/ko/web/html/element/html/index.html | 123 +++ files/ko/web/html/element/i/index.html | 119 +++ files/ko/web/html/element/iframe/index.html | 253 ++++++ files/ko/web/html/element/img/index.html | 389 +++++++++ files/ko/web/html/element/index.html | 102 +++ files/ko/web/html/element/input/button/index.html | 343 ++++++++ files/ko/web/html/element/input/date/index.html | 497 ++++++++++++ files/ko/web/html/element/input/file/index.html | 509 ++++++++++++ files/ko/web/html/element/input/index.html | 865 +++++++++++++++++++++ files/ko/web/html/element/input/radio/index.html | 367 +++++++++ files/ko/web/html/element/ins/index.html | 137 ++++ files/ko/web/html/element/kbd/index.html | 208 +++++ files/ko/web/html/element/keygen/index.html | 122 +++ files/ko/web/html/element/label/index.html | 189 +++++ files/ko/web/html/element/legend/index.html | 91 +++ files/ko/web/html/element/li/index.html | 154 ++++ files/ko/web/html/element/link/index.html | 365 +++++++++ files/ko/web/html/element/main/index.html | 172 ++++ files/ko/web/html/element/map/index.html | 121 +++ files/ko/web/html/element/mark/index.html | 161 ++++ files/ko/web/html/element/menu/index.html | 132 ++++ files/ko/web/html/element/meta/index.html | 151 ++++ files/ko/web/html/element/meta/name/index.html | 312 ++++++++ files/ko/web/html/element/meter/index.html | 142 ++++ files/ko/web/html/element/nav/index.html | 101 +++ files/ko/web/html/element/noscript/index.html | 113 +++ files/ko/web/html/element/object/index.html | 117 +++ files/ko/web/html/element/ol/index.html | 207 +++++ files/ko/web/html/element/optgroup/index.html | 120 +++ files/ko/web/html/element/option/index.html | 101 +++ files/ko/web/html/element/output/index.html | 104 +++ files/ko/web/html/element/p/index.html | 175 +++++ files/ko/web/html/element/param/index.html | 116 +++ files/ko/web/html/element/pre/index.html | 150 ++++ files/ko/web/html/element/progress/index.html | 122 +++ files/ko/web/html/element/q/index.html | 111 +++ files/ko/web/html/element/rb/index.html | 150 ++++ files/ko/web/html/element/rp/index.html | 134 ++++ files/ko/web/html/element/rt/index.html | 129 +++ files/ko/web/html/element/rtc/index.html | 121 +++ files/ko/web/html/element/ruby/index.html | 110 +++ files/ko/web/html/element/s/index.html | 126 +++ files/ko/web/html/element/samp/index.html | 156 ++++ files/ko/web/html/element/script/index.html | 220 ++++++ files/ko/web/html/element/section/index.html | 123 +++ files/ko/web/html/element/select/index.html | 210 +++++ files/ko/web/html/element/slot/index.html | 122 +++ files/ko/web/html/element/small/index.html | 117 +++ files/ko/web/html/element/span/index.html | 125 +++ files/ko/web/html/element/strong/index.html | 135 ++++ files/ko/web/html/element/style/index.html | 201 +++++ files/ko/web/html/element/sub/index.html | 137 ++++ files/ko/web/html/element/summary/index.html | 151 ++++ files/ko/web/html/element/sup/index.html | 142 ++++ files/ko/web/html/element/table/index.html | 370 +++++++++ files/ko/web/html/element/tbody/index.html | 320 ++++++++ files/ko/web/html/element/td/index.html | 213 +++++ files/ko/web/html/element/template/index.html | 165 ++++ files/ko/web/html/element/textarea/index.html | 158 ++++ files/ko/web/html/element/th/index.html | 226 ++++++ files/ko/web/html/element/thead/index.html | 270 +++++++ files/ko/web/html/element/time/index.html | 169 ++++ files/ko/web/html/element/title/index.html | 134 ++++ files/ko/web/html/element/tr/index.html | 217 ++++++ files/ko/web/html/element/track/index.html | 175 +++++ files/ko/web/html/element/u/index.html | 206 +++++ files/ko/web/html/element/ul/index.html | 188 +++++ files/ko/web/html/element/var/index.html | 116 +++ files/ko/web/html/element/video/index.html | 145 ++++ files/ko/web/html/element/wbr/index.html | 111 +++ .../html/global_attributes/accesskey/index.html | 139 ++++ .../global_attributes/autocapitalize/index.html | 47 ++ .../global_attributes/contenteditable/index.html | 76 ++ .../html/global_attributes/contextmenu/index.html | 121 +++ .../html/global_attributes/data-_star_/index.html | 79 ++ files/ko/web/html/global_attributes/dir/index.html | 89 +++ .../html/global_attributes/draggable/index.html | 66 ++ .../web/html/global_attributes/dropzone/index.html | 53 ++ .../web/html/global_attributes/hidden/index.html | 69 ++ files/ko/web/html/global_attributes/id/index.html | 72 ++ files/ko/web/html/global_attributes/index.html | 166 ++++ .../html/global_attributes/inputmode/index.html | 64 ++ files/ko/web/html/global_attributes/is/index.html | 64 ++ .../web/html/global_attributes/itemid/index.html | 105 +++ .../web/html/global_attributes/itemprop/index.html | 472 +++++++++++ .../web/html/global_attributes/itemref/index.html | 95 +++ .../html/global_attributes/itemscope/index.html | 284 +++++++ .../ko/web/html/global_attributes/lang/index.html | 90 +++ .../ko/web/html/global_attributes/part/index.html | 43 + .../ko/web/html/global_attributes/slot/index.html | 48 ++ .../html/global_attributes/spellcheck/index.html | 67 ++ .../ko/web/html/global_attributes/style/index.html | 69 ++ .../web/html/global_attributes/tabindex/index.html | 92 +++ .../ko/web/html/global_attributes/title/index.html | 125 +++ .../html/global_attributes/translate/index.html | 64 ++ .../index.html" | 64 ++ files/ko/web/html/html5/index.html | 122 +++ .../html/html5/introduction_to_html5/index.html | 40 + .../index.html" | 367 +++++++++ files/ko/web/html/index.html | 117 +++ files/ko/web/html/index/index.html | 10 + files/ko/web/html/inline_elements/index.html | 169 ++++ files/ko/web/html/link_types/index.html | 332 ++++++++ files/ko/web/html/preloading_content/index.html | 233 ++++++ .../html/quirks_mode_and_standards_mode/index.html | 46 ++ files/ko/web/html/reference/index.html | 32 + .../html/using_the_application_cache/index.html | 338 ++++++++ 178 files changed, 30973 insertions(+) create mode 100644 files/ko/web/html/applying_color/index.html create mode 100644 files/ko/web/html/attributes/autocomplete/index.html create mode 100644 files/ko/web/html/attributes/crossorigin/index.html create mode 100644 files/ko/web/html/attributes/index.html create mode 100644 files/ko/web/html/block-level_elements/index.html create mode 100644 files/ko/web/html/canvas/index.html create mode 100644 files/ko/web/html/canvas/manipulating_video_using_canvas/index.html create mode 100644 files/ko/web/html/canvas/tutorial/advanced_animations/index.html create mode 100644 files/ko/web/html/canvas/tutorial/applying_styles_and_colors/index.html create mode 100644 files/ko/web/html/canvas/tutorial/basic_animations/index.html create mode 100644 files/ko/web/html/canvas/tutorial/basic_usage/index.html create mode 100644 files/ko/web/html/canvas/tutorial/compositing/example/index.html create mode 100644 files/ko/web/html/canvas/tutorial/compositing/index.html create mode 100644 files/ko/web/html/canvas/tutorial/drawing_shapes/index.html create mode 100644 files/ko/web/html/canvas/tutorial/finale/index.html create mode 100644 files/ko/web/html/canvas/tutorial/hit_regions_and_accessibility/index.html create mode 100644 files/ko/web/html/canvas/tutorial/index.html create mode 100644 files/ko/web/html/canvas/tutorial/optimizing_canvas/index.html create mode 100644 files/ko/web/html/canvas/tutorial/using_images/index.html create mode 100644 "files/ko/web/html/canvas/tutorial/\353\263\200\355\230\225/index.html" create mode 100644 files/ko/web/html/cors_enabled_image/index.html create mode 100644 files/ko/web/html/element/a/index.html create mode 100644 files/ko/web/html/element/abbr/index.html create mode 100644 files/ko/web/html/element/address/index.html create mode 100644 files/ko/web/html/element/applet/index.html create mode 100644 files/ko/web/html/element/area/index.html create mode 100644 files/ko/web/html/element/article/index.html create mode 100644 files/ko/web/html/element/aside/index.html create mode 100644 files/ko/web/html/element/audio/index.html create mode 100644 files/ko/web/html/element/b/index.html create mode 100644 files/ko/web/html/element/base/index.html create mode 100644 files/ko/web/html/element/bdo/index.html create mode 100644 files/ko/web/html/element/blockquote/index.html create mode 100644 files/ko/web/html/element/body/index.html create mode 100644 files/ko/web/html/element/br/index.html create mode 100644 files/ko/web/html/element/button/index.html create mode 100644 files/ko/web/html/element/canvas/index.html create mode 100644 files/ko/web/html/element/caption/index.html create mode 100644 files/ko/web/html/element/center/index.html create mode 100644 files/ko/web/html/element/cite/index.html create mode 100644 files/ko/web/html/element/code/index.html create mode 100644 files/ko/web/html/element/col/index.html create mode 100644 files/ko/web/html/element/colgroup/index.html create mode 100644 files/ko/web/html/element/command/index.html create mode 100644 files/ko/web/html/element/content/index.html create mode 100644 files/ko/web/html/element/data/index.html create mode 100644 files/ko/web/html/element/datalist/index.html create mode 100644 files/ko/web/html/element/dd/index.html create mode 100644 files/ko/web/html/element/del/index.html create mode 100644 files/ko/web/html/element/details/index.html create mode 100644 files/ko/web/html/element/dfn/index.html create mode 100644 files/ko/web/html/element/dialog/index.html create mode 100644 files/ko/web/html/element/div/index.html create mode 100644 files/ko/web/html/element/dl/index.html create mode 100644 files/ko/web/html/element/dt/index.html create mode 100644 files/ko/web/html/element/element/index.html create mode 100644 files/ko/web/html/element/em/index.html create mode 100644 files/ko/web/html/element/embed/index.html create mode 100644 files/ko/web/html/element/fieldset/index.html create mode 100644 files/ko/web/html/element/figcaption/index.html create mode 100644 files/ko/web/html/element/figure/index.html create mode 100644 files/ko/web/html/element/font/index.html create mode 100644 files/ko/web/html/element/footer/index.html create mode 100644 files/ko/web/html/element/form/index.html create mode 100644 files/ko/web/html/element/frame/index.html create mode 100644 files/ko/web/html/element/frameset/index.html create mode 100644 files/ko/web/html/element/head/index.html create mode 100644 files/ko/web/html/element/header/index.html create mode 100644 files/ko/web/html/element/heading_elements/index.html create mode 100644 files/ko/web/html/element/hgroup/index.html create mode 100644 files/ko/web/html/element/hr/index.html create mode 100644 files/ko/web/html/element/html/index.html create mode 100644 files/ko/web/html/element/i/index.html create mode 100644 files/ko/web/html/element/iframe/index.html create mode 100644 files/ko/web/html/element/img/index.html create mode 100644 files/ko/web/html/element/index.html create mode 100644 files/ko/web/html/element/input/button/index.html create mode 100644 files/ko/web/html/element/input/date/index.html create mode 100644 files/ko/web/html/element/input/file/index.html create mode 100644 files/ko/web/html/element/input/index.html create mode 100644 files/ko/web/html/element/input/radio/index.html create mode 100644 files/ko/web/html/element/ins/index.html create mode 100644 files/ko/web/html/element/kbd/index.html create mode 100644 files/ko/web/html/element/keygen/index.html create mode 100644 files/ko/web/html/element/label/index.html create mode 100644 files/ko/web/html/element/legend/index.html create mode 100644 files/ko/web/html/element/li/index.html create mode 100644 files/ko/web/html/element/link/index.html create mode 100644 files/ko/web/html/element/main/index.html create mode 100644 files/ko/web/html/element/map/index.html create mode 100644 files/ko/web/html/element/mark/index.html create mode 100644 files/ko/web/html/element/menu/index.html create mode 100644 files/ko/web/html/element/meta/index.html create mode 100644 files/ko/web/html/element/meta/name/index.html create mode 100644 files/ko/web/html/element/meter/index.html create mode 100644 files/ko/web/html/element/nav/index.html create mode 100644 files/ko/web/html/element/noscript/index.html create mode 100644 files/ko/web/html/element/object/index.html create mode 100644 files/ko/web/html/element/ol/index.html create mode 100644 files/ko/web/html/element/optgroup/index.html create mode 100644 files/ko/web/html/element/option/index.html create mode 100644 files/ko/web/html/element/output/index.html create mode 100644 files/ko/web/html/element/p/index.html create mode 100644 files/ko/web/html/element/param/index.html create mode 100644 files/ko/web/html/element/pre/index.html create mode 100644 files/ko/web/html/element/progress/index.html create mode 100644 files/ko/web/html/element/q/index.html create mode 100644 files/ko/web/html/element/rb/index.html create mode 100644 files/ko/web/html/element/rp/index.html create mode 100644 files/ko/web/html/element/rt/index.html create mode 100644 files/ko/web/html/element/rtc/index.html create mode 100644 files/ko/web/html/element/ruby/index.html create mode 100644 files/ko/web/html/element/s/index.html create mode 100644 files/ko/web/html/element/samp/index.html create mode 100644 files/ko/web/html/element/script/index.html create mode 100644 files/ko/web/html/element/section/index.html create mode 100644 files/ko/web/html/element/select/index.html create mode 100644 files/ko/web/html/element/slot/index.html create mode 100644 files/ko/web/html/element/small/index.html create mode 100644 files/ko/web/html/element/span/index.html create mode 100644 files/ko/web/html/element/strong/index.html create mode 100644 files/ko/web/html/element/style/index.html create mode 100644 files/ko/web/html/element/sub/index.html create mode 100644 files/ko/web/html/element/summary/index.html create mode 100644 files/ko/web/html/element/sup/index.html create mode 100644 files/ko/web/html/element/table/index.html create mode 100644 files/ko/web/html/element/tbody/index.html create mode 100644 files/ko/web/html/element/td/index.html create mode 100644 files/ko/web/html/element/template/index.html create mode 100644 files/ko/web/html/element/textarea/index.html create mode 100644 files/ko/web/html/element/th/index.html create mode 100644 files/ko/web/html/element/thead/index.html create mode 100644 files/ko/web/html/element/time/index.html create mode 100644 files/ko/web/html/element/title/index.html create mode 100644 files/ko/web/html/element/tr/index.html create mode 100644 files/ko/web/html/element/track/index.html create mode 100644 files/ko/web/html/element/u/index.html create mode 100644 files/ko/web/html/element/ul/index.html create mode 100644 files/ko/web/html/element/var/index.html create mode 100644 files/ko/web/html/element/video/index.html create mode 100644 files/ko/web/html/element/wbr/index.html create mode 100644 files/ko/web/html/global_attributes/accesskey/index.html create mode 100644 files/ko/web/html/global_attributes/autocapitalize/index.html create mode 100644 files/ko/web/html/global_attributes/contenteditable/index.html create mode 100644 files/ko/web/html/global_attributes/contextmenu/index.html create mode 100644 files/ko/web/html/global_attributes/data-_star_/index.html create mode 100644 files/ko/web/html/global_attributes/dir/index.html create mode 100644 files/ko/web/html/global_attributes/draggable/index.html create mode 100644 files/ko/web/html/global_attributes/dropzone/index.html create mode 100644 files/ko/web/html/global_attributes/hidden/index.html create mode 100644 files/ko/web/html/global_attributes/id/index.html create mode 100644 files/ko/web/html/global_attributes/index.html create mode 100644 files/ko/web/html/global_attributes/inputmode/index.html create mode 100644 files/ko/web/html/global_attributes/is/index.html create mode 100644 files/ko/web/html/global_attributes/itemid/index.html create mode 100644 files/ko/web/html/global_attributes/itemprop/index.html create mode 100644 files/ko/web/html/global_attributes/itemref/index.html create mode 100644 files/ko/web/html/global_attributes/itemscope/index.html create mode 100644 files/ko/web/html/global_attributes/lang/index.html create mode 100644 files/ko/web/html/global_attributes/part/index.html create mode 100644 files/ko/web/html/global_attributes/slot/index.html create mode 100644 files/ko/web/html/global_attributes/spellcheck/index.html create mode 100644 files/ko/web/html/global_attributes/style/index.html create mode 100644 files/ko/web/html/global_attributes/tabindex/index.html create mode 100644 files/ko/web/html/global_attributes/title/index.html create mode 100644 files/ko/web/html/global_attributes/translate/index.html create mode 100644 "files/ko/web/html/global_attributes/\355\201\264\353\236\230\354\212\244/index.html" create mode 100644 files/ko/web/html/html5/index.html create mode 100644 files/ko/web/html/html5/introduction_to_html5/index.html create mode 100644 "files/ko/web/html/html5_\353\254\270\354\204\234\354\235\230_\354\204\271\354\205\230\352\263\274_\354\234\244\352\263\275/index.html" create mode 100644 files/ko/web/html/index.html create mode 100644 files/ko/web/html/index/index.html create mode 100644 files/ko/web/html/inline_elements/index.html create mode 100644 files/ko/web/html/link_types/index.html create mode 100644 files/ko/web/html/preloading_content/index.html create mode 100644 files/ko/web/html/quirks_mode_and_standards_mode/index.html create mode 100644 files/ko/web/html/reference/index.html create mode 100644 files/ko/web/html/using_the_application_cache/index.html (limited to 'files/ko/web/html') diff --git a/files/ko/web/html/applying_color/index.html b/files/ko/web/html/applying_color/index.html new file mode 100644 index 0000000000..7fd7836e35 --- /dev/null +++ b/files/ko/web/html/applying_color/index.html @@ -0,0 +1,510 @@ +--- +title: CSS로 HTML 요소에 색 입히기 +slug: Web/HTML/Applying_color +tags: + - Beginner + - CSS + - CSS Colors + - Guide + - HTML + - HTML Colors + - color + - 색 +translation_of: Web/HTML/Applying_color +--- +
{{HTMLRef}}
+ +

색은 인간의 감정을 표현하는 기본적인 형태입니다. 아이들은 뭔가 그릴 수 있는 민첩성을 갖추기도 전에 색을 가지고 놉니다. 사람들이 웹 사이트를 개발할 때 보통 색을 제일 먼저 입혀보고 싶어 하는 건 이런 이유일지도 모릅니다. CSS와 함께라면 무궁무진한 방법으로 여러분의 HTML 요소에 색을 넣어 원하는 모습을 만들 수 있습니다. 이 글은 CSS 색을 HTML에 적용하는 기초를 소개합니다.

+ +

다행히도 HTML에 색을 추가하는 건 정말 쉽고 거의 모든 곳에 할 수 있는 일입니다.

+ +

{{anch("색을 입힐 수 있는 것", "색을 입힐 수 있는 목록, 그때 사용할 CSS 속성")}}, {{anch("색을 나타내는 법", "색을 나타내는 법")}}, {{anch("색 사용하기", "실제로 색 사용하기")}} 등 색을 쓸 때 알아야 할 주제는 대부분 짚고 가겠습니다. {{anch("사용자의 색 선택", "사용자가 색을 선택")}}할 수 있는 방법도 확인해보겠습니다.

+ +

마지막으로는 적절한 색을 고르고, 서로 다른 시각적 조건을 가진 사람들을 고려하는 등 {{anch("현명하게 색 고르기", "현명한 색 선택")}}에 대해 간단히 알아보겠습니다.

+ +

색을 입힐 수 있는 것

+ +

요소 차원에서 보자면 HTML의 모든 것에 색을 입힐 수 있습니다. 대신에 글씨와 테두리처럼, 요소 안에 그려지는 것의 종류에 따라 알아보겠습니다. 각각의 종류에 적용할 수 있는 CSS 속성의 목록도 보겠습니다.

+ +

가장 기초적인 단계로는 {{cssxref("color")}} 속성이 HTML 요소의 콘텐츠 전경색을 지정하고, {{cssxref("background-color")}} 속성이 요소의 배경색을 지정합니다. 두 속성은 거의 모든 요소에 사용할 수 있습니다.

+ +

글씨

+ +

요소를 렌더링할 때 글씨, 글씨 배경과 기타 꾸미기 효과의 색은 아래에 나열한 속성이 결정합니다.

+ +
+
{{cssxref("color")}}
+
글씨와 글씨 장식(밑줄, 윗줄, 취소선 등)을 그릴 때 사용할 색입니다.
+
{{cssxref("background-color")}}
+
글씨의 배경색입니다.
+
{{cssxref("text-shadow")}}
+
글씨의 그림자 효과를 설정합니다. 여러 옵션 중에서 그림자 색을 정할 수 있습니다. (이후 다른 옵션에 따라 흐려지고 배경과 섞입니다)
+
{{cssxref("text-decoration-color")}}
+
기본 설정에서 글씨 장식(밑줄, 윗줄, 취소선 등)은 color 속성의 값을 색으로 사용합니다. 그러나 text-decoration-color 속성을 지정하면 다른 색으로 바꿀 수 있습니다.
+
{{cssxref("text-emphasis-color")}}
+
글씨 위에 표시할 강조 표시의 색입니다.
+
{{cssxref("caret-color")}}
+
요소의 {{Glossary("caret", "캐럿")}}(글씨 입력 커서) 색입니다. {{HTMLElement("input")}}이나 {{HTMLElement("textarea")}}, HTML {{htmlattrxref("contenteditable")}} 속성을 설정한 요소처럼 편집 가능한 경우에만 유용합니다.
+
+ +

박스

+ +

모든 요소는 모종의 콘텐츠를 가진 박스로, 콘텐츠 외에도 배경과 테두리를 가질 수 있습니다.

+ +
+
{{anch("테두리")}}
+
{{anch("테두리")}} 항목에서 박스 테두리에 사용할 수 있는 CSS 속성의 목록을 확인하세요.
+
{{cssxref("background-color")}}
+
전경 콘텐츠가 없는 곳에 표시할 배경색입니다.
+
{{cssxref("column-rule-color")}}
+
긴 글씨를 여러 단으로 나눌 때 그릴 구분선의 색입니다.
+
{{cssxref("outline-color")}}
+
요소의 바깥에 외곽선을 그릴 때 사용할 색입니다. 외곽선은 문서에서 공간을 차지하지 않아서 다른 요소를 가릴 수 있다는 점에서 테두리와 다릅니다. 보통 현재 선택돼 입력 이벤트를 받을 수 있는 요소를 강조할 때 사용합니다.
+
+ +

테두리

+ +

모든 요소는 주위에 테두리를 가질 수 있습니다. 기본적인 테두리는 요소 콘텐츠의 모서리를 따라 그리는 선입니다.

+ +

{{cssxref("border")}} 단축 속성을 사용하면 색은 물론 너비스타일(실선, 점선 등)같은 속성을 한 번에 설정할 수 있습니다.

+ +
+
{{cssxref("border-color")}}
+
모든 면의 테두리가 사용할 단색입니다.
+
{{cssxref("border-left-color")}}, {{cssxref("border-right-color")}}, {{cssxref("border-top-color")}}, {{cssxref("border-bottom-color")}}
+
테두리 색을 방향에 따라 다르게 설정할 수 있습니다.
+
{{cssxref("border-block-start-color")}}, {{cssxref("border-block-end-color")}}
+
With these, you can set the color used to draw the borders which are closest to the start and end of the block the border surrounds. In a left-to-right writing mode (such as the way English is written), the block start border is the top edge and the block end is the bottom. This differs from the inline start and end, which are the left and right edges (corresponding to where each line of text in the box begins and ends).
+
{{cssxref("border-inline-start-color")}}, {{cssxref("border-inline-end-color")}}
+
These let you color the edges of the border closest to to the beginning and the end of the start of lines of text within the box. Which side this is will vary depending on the {{cssxref("writing-mode")}}, {{cssxref("direction")}}, and {{cssxref("text-orientation")}} properties, which are typically (but not always) used to adjust text directionality based on the language being displayed. For example, if the box's text is being rendered right-to-left, then the border-inline-start-color is applied to the right side of the border.
+
+ +

다른 방법

+ +

웹 기술에서 CSS만 색을 지원하는건 아닙니다. 웹에서 사용할 수 있는 다른 그래픽 기술에서도 색을 지원합니다.

+ +
+
HTML Canvas API
+
{{HTMLElement("canvas")}} 요소로 2D 비트맵 그래픽을 그릴 수 있습니다. 캔버스 자습서를 방문해 더 알아보세요.
+
SVG (Scalable Vector Graphics)
+
선, 패턴, 특정 모양의 형태를 그리는 명령어를 사용해 이미지를 그릴 수 있습니다. SVG 명령어는 XML 형식을 따르며, 웹 페이지에 바로 삽입할 수도 있고, 다른 이미지처럼 {{HTMLElement("img")}} 요소에 넣을 수도 있습니다.
+
WebGL
+
Web Graphics Library는 OpenGL ES 기반의 API로, 웹에서 고성능 2D 및 3D 그래픽을 그릴 수 있습니다. WebGL 자습서를 방문해 더 알아보세요.
+
+ +

색을 나타내는 법

+ +

CSS에서 색을 나타내려면 우선 "색"이라는 개념을, 원색이나 밝기 등 구성 요소를 분리해 수치로 표기하는 등 컴퓨터가 이해할 수 있는 디지털 형태로 변환해야 합니다. 변환 방법이 여러 가지이듯 CSS가 색을 표현하는 방법도 여러 가지입니다.

+ +

각각의 형태에 대한 더 자세한 내용은 CSS {{cssxref("<color>")}} 단위 문서를 참고하세요.

+ +

키워드

+ +

CSS 표준은 다수의 색 키워드를 사전에 정의하고 있으므로, 원하는 색을 가리키는 키워드가 있다면 숫자형 표현 대신 사용할 수 있습니다. 색 키워드는 원색과 2차색(red, blue, orange 등), 단계별 무채색(black에서 white까지, darkgraylightgrey 등) 외에도 lightseagreen, cornflowerblue, rebeccapurple처럼 다양한 종류의 혼합색을 포함하고 있습니다.

+ +

사용할 수 있는 모든 색 키워드의 목록은 <color>의 색상 키워드 항목을 참고하세요.

+ +

RGB 값

+ +

RGB 색은 세 가지 방법으로 표현할 수 있습니다.

+ +

16진수 문자열 표기법

+ +

16진수 문자열 표기법은 색의 구성요소(빨강, 초록, 파랑)를 16진수 숫자로 표현합니다. 네 번째 구성 요소로 알파 채널(불투명도)을 포함할 수도 있습니다. 하나의 구성 요소는 0에서 255 사이(0x00에서 0xFF)를 숫자 두 개로, 또는 0에서 15 사이(0x0에서 0xF)를 숫자 한 개로 표기합니다. 단, 모든 구성 요소는 같은 수의 문자로 표기해야 합니다. 한 자릿수(0~F)로 표기한다면, 구성 요소의 최종 값은 자신의 문자를 두 번씩 사용해 계산합니다. 즉, "#D"의 값은 "#DD"입니다.

+ +

16진수 문자열 표기법은 항상 "#"으로 시작해야 하고, 16진수 숫자는 그 후에 위치합니다. 문자열은 대소문자를 구분하지 않습니다.

+ +
+
"#rrggbb"
+
완전히 불투명한 색을 지정합니다. 구성 요소 중 빨강은 16진수 0xrr, 초록은 0xgg, 파랑은 0xbb입니다.
+
"#rrggbbaa"
+
구성 요소 중 빨강은 16진수 0xrr, 초록은 0xgg, 파랑은 0xbb인 색을 지정합니다. 알파 채널의 값은 0xaa로, 값이 낮을 수록 색은 더 투명해집니다.
+
"#rgb"
+
완전히 불투명한 색을 지정합니다. 구성 요소 중 빨강은 16진수 0xrr, 초록은 0xgg, 파랑은 0xbb입니다.
+
"#rgba"
+
구성 요소 중 빨강은 16진수 0xrr, 초록은 0xgg, 파랑은 0xbb인 색을 지정합니다. 알파 채널의 값은 0xaa로, 값이 낮을 수록 색은 더 투명해집니다.
+
+ +

예를 하나 들자면 불투명한 파랑은 "#0000ff"이나 "#00f"로 표현할 수 있습니다. 25%만 불투명한 파랑으로 만들 땐 "#0000ff44" 또는 "#00f4"로 표기합니다.

+ +

RGB 함수형 표기법

+ +

16진수 문자열 표기법과 같이, RGB(Red/Green/Blue) 함수 표기법은 빨강, 초록, 파랑, 그리고 불투명도를 나타낼 선택적 알파 채널 구성요소를 사용해 색을 나타냅니다. 그러나 문자열 표기법과 달리 CSS 함수 {{cssxref("color_value", "rgb()", "#rgb()")}}를 사용합니다. rgb() 함수의 세 매개변수는 순서대로 빨강, 파랑, 초록 값이며, 생략 가능한 마지막 네 번째 매개변수가 알파 채널을 나타냅니다.

+ +

각 매개변수의 유효한 값은 다음과 같습니다.

+ +
+
red, green, blue
+
각각 0 이상, 255 이하인 {{cssxref("<integer>")}}이거나, 또는 0% 이상 100% 이하인 {{cssxref("<percentage>")}}여야 합니다.
+
alpha
+
0.0(완전히 투명) 이상, 1.0(완전히 불투명) 이하의 숫자여야 합니다. 백분율도 사용할 수 있으며, 0%는 0.0, 100%는 1.0에 대응합니다.
+
+ +

예를 들어, 50% 불투명도의 밝은 빨강은 rgb(255, 0, 0, 0.5)rgb(100%, 0, 0, 50%) 두 방법으로 만들 수 있습니다.

+ +

HSL 함수형 표기법

+ +

많은 경우, 디자이너와 아티스트는 HSL(색조/채도/명도) 모델을 사용한 색을 선호합니다. 웹에서 HSL 색상은 HSL 함수 표기법을 사용해 나타냅니다. CSS hsl() 함수의 사용법 자체는 rgb() 함수와 매우 유사합니다.

+ +
+
HSL color cylinder +
그림 1. HSL 색 원기둥. Hue defines the actual color based on the position along a circular color wheel representing the colors of the visible spectrum. Saturation is a percentage of how much of the way between being a shade of gray and having the maximum possible amount of the given hue. As the value of luminance (or lightness) increases, the color transitions from the darkest possible to the brightest possible (from black to white). WikipediaSharkD, CC BY-SA 3.0 라이선스 아래에서 재배포.
+
+
+ +

The value of the hue (H) component of an HSL color is an angle from red around through yellow, green, cyan, blue, and magenta (ending up back at red again at 360°) that identifies what the base color is. The value can be specified in any {{cssxref("<angle>")}} unit supported by CSS, including degrees (deg), radians (rad), gradians (grad), or turns (turn). But this doesn't control how vivid or dull, or how bright or dark the color is.

+ +

The saturation (S) component of the color specifies what percentage of the final color is comprised of the specified hue. The rest is defined by the grey level provided by the luminance (L) component.

+ +

Think of it like creating the perfect paint color:

+ +
    +
  1. You start with base paint that's the maximum intensity possible for a given color, such as the most intense blue that can be represented by the user's screen. This is the hue (H) component: a value representing the angle around the color wheel for the vivid hue we want to use as our base.
  2. +
  3. Then select a greyscale paint that corresponds how bright you want the color to be; this is the luminance. Do you want it to be very bright and nearly white, or very dark and closer to black, or somewhere in between? This is specified using a percentage, where 0% is perfectly black and 100% is perfectly white. (regardless of the saturation or hue). In between values are a literal grey area.
  4. +
  5. Now that you have a grey paint and a perfectly vivid color, you need to mix them together. The saturation (S) component of the color indicates what percentage of the final color should be comprised of that perfectly vivid color. The rest of the final color is made up of the grey paint that represents the saturation.
  6. +
+ +

You can also optionally include an alpha channel, to make the color less than 100% opaque.

+ +

Here are some sample colors in HSL notation:

+ +
+ + +

{{EmbedLiveSample("hsl-swatches", 300, 260)}}

+
+ +
+

Note that when you omit the hue's unit, it's assumed to be in degrees (deg).

+
+ +

색 사용하기

+ +

Now that you know what CSS properties exist that let you apply color to elements and the formats you can use to describe colors, you can put this together to begin to make use of color. As you may have seen from the list under {{anch("Things that can have color")}}, there are plenty of things you can color with CSS. Let's look at this from two sides: using color within a {{Glossary("stylesheet")}}, and adding and changing color using {{Glossary("JavaScript")}} code to alter the styles of elements.

+ +

스타일 시트에 색 지정하기

+ +

The easiest way to apply color to elements—and the way you'll usually do it—is to simply specify colors in the CSS that's used when rendering elements. While we won't use every single property mentioned previously, we'll look at a couple of examples. The concept is the same anywhere you use color.

+ +

Let's take a look at an example, starting by looking at the results we're trying to achieve:

+ +
{{EmbedLiveSample("Specifying_colors_in_stylesheets", 650, 150)}}
+ +

HTML

+ +

The HTML responsible for creating the above example is shown here:

+ +
<div class="wrapper">
+  <div class="box boxLeft">
+    <p>
+      This is the first box.
+    </p>
+  </div>
+  <div class="box boxRight">
+    <p>
+      This is the second box.
+    </p>
+  </div>
+</div>
+ +

This is pretty simple, using a {{HTMLElement("div")}} as a wrapper around the contents, which consists of two more <div>s, each styled differently with a single paragraph ({{HTMLElement("p")}}) in each box.

+ +

The magic happens, as usual, in the CSS, where we'll apply colors define the layout for the HTML above.

+ +

CSS

+ +

We'll look at the CSS to create the above results a piece at a time, so we can review the interesting parts one by one.

+ +
.wrapper {
+  width: 620px;
+  height: 110px;
+  margin: 0;
+  padding: 10px;
+  border: 6px solid mediumturquoise;
+}
+ +

The .wrapper class is used to assign styles to the {{HTMLElement("div")}} that encloses all of our other content. This establishes thesize of the container using {{cssxref("width")}} and {{cssxref("height")}} as well as its {{cssxref("margin")}} and {{cssxref("padding")}}.

+ +

Of more interest to our discussion here is the use of the {{cssxref("border")}} property to establish a border around the outside edge of the element. This border is a solid line, 6 pixels wide, in the color mediumturquoise.

+ +

Our two colored boxes share a number of properties in common, so next we establish a class, .box, that defines those shared properties:

+ +
.box {
+  width: 290px;
+  height: 100px;
+  margin: 0;
+  padding: 4px 6px;
+  font: 28px "Marker Felt", "Zapfino", cursive;
+  display: flex;
+  justify-content: center;
+  align-items: center;
+}
+ +

In brief, .box establishes the size of each box, as well as the configuration of the font used within. We also take advantage of CSS Flexbox to easily center the contents of each box. We enable flex mode using {{cssxref("display", "display: flex")}}, and set both {{cssxref("justify-content")}} and {{cssxref("align-items")}} to center. Then we can create a class for each of the two boxes that defines the properties that differ between the two.

+ +
.boxLeft {
+  float: left;
+  background-color: rgb(245, 130, 130);
+  outline: 2px solid darkred;
+}
+ +

The .boxLeft class—which, cleverly, is used to style the box on the left—floats the box to the left, then sets up the colors:

+ + + +
.boxRight {
+  float: right;
+  background-color: hsl(270deg, 50%, 75%);
+  outline: 4px dashed rgb(110, 20, 120);
+  color: hsl(0deg, 100%, 100%);
+  text-decoration: underline wavy #88ff88;
+  text-shadow: 2px 2px 3px black;
+}
+ +

Finally, the .boxRight class describes the unique properties of the box that's drawn on the right. It's configured to float the box to the right so that it appears next to the previous box. Then the following colors are established:

+ + + +

사용자의 색 선택

+ +

There are many situations in which your web site may need to let the user select a color. Perhaps you have a customizable user interface, or you're implementing a drawing app. Maybe you have editable text and need to let the user choose the text color. Or perhaps your app lets the user assign colors to folders or items. Although historically it's been necessary to implement your own {{interwiki("wikipedia", "color picker")}}, HTML now provides support for browsers to provide one for your use through the {{HTMLElement("input")}} element, by using "color" as the value of its {{htmlattrxref("type", "input")}} attribute.

+ +

The <input> element represents a color only in the {{anch("Hexadecimal string notation", "hexadecimal string notation")}} covered above.

+ +

예제: 색 선택하기

+ +

Let's look at a simple example, in which the user can choose a color. As the user adjusts the color, the border around the example changes to reflect the new color. After finishing up and picking the final color, the color picker's value is displayed.

+ +

{{EmbedLiveSample("Example_Picking_a_color", 525, 275)}}

+ +
+

On macOS, you indicate that you've finalized selection of the color by closing the color picker window.

+
+ +

HTML

+ +

The HTML here creates a box that contains a color picker control (with a label created using the {{HTMLElement("label")}} element) and an empty paragraph element ({{HTMLElement("p")}}) into which we'll output some text from our JavaScript code.

+ +
<div id="box">
+  <label for="colorPicker">Border color:</label>
+  <input type="color" value="#8888ff" id="colorPicker">
+  <p id="output"></p>
+</div>
+ +

CSS

+ +

The CSS simply establishes a size for the box and some basic styling for appearances. The border is also established with a 2-pixel width and a border color that won't last, courtesy of the JavaScript below...

+ +
#box {
+  width: 500px;
+  height: 200px;
+  border: 2px solid rgb(245, 220, 225);
+  padding: 4px 6px;
+  font: 16px "Lucida Grande", "Helvetica", "Arial", "sans-serif"
+}
+ +

JavaScript

+ +

The script here handles the task of updating the starting color of the border to match the color picker's value. Then two event handlers are added to deal with input from the <input type="color"> element.

+ +
let colorPicker = document.getElementById("colorPicker");
+let box = document.getElementById("box");
+let output = document.getElementById("output");
+
+box.style.borderColor = colorPicker.value;
+
+colorPicker.addEventListener("input", function(event) {
+  box.style.borderColor = event.target.value;
+}, false);
+
+colorPicker.addEventListener("change", function(event) {
+  output.innerText = "Color set to " + colorPicker.value + ".";
+}, false);
+ +

The {{event("input")}} event is sent every time the value of the element changes; that is, every time the user adjusts the color in the color picker. Each time this event arrives, we set the box's border color to match the color picker's current value.

+ +

The {{event("change")}} event is received when the color picker's value is finalized. We respond by setting the contents of the <p> element with the ID "output" to a string describing the finally selected color.

+ +

현명하게 색 고르기

+ +

Making the right choices when selecting colors when designing a web site can be a tricky process, especially if you aren't well-grounded in art, design, or at least basic color theory. The wrong color choice can render your site unattractive, or even worse, leave the content unreadable due to problems with contrast or conflicting colors. Worse still, if using the wrong colors can result in your content being outright unusable by people withcertain vision problems, particularly color blindness.

+ +

적절한 색 찾기

+ +

Coming up with just the right colors can be tricky, especially without training in art or design. Fortunately, there are tools available that can help you. While they can't replace having a good designer helping you make these decisions, they can definitely get you started.

+ +

기본색

+ +

The first step is to choose your base color. This is the color that in some way defines your web site or the subject matter of the site. Just as we associate green with the beverage {{interwiki("wikipedia", "Mountain Dew")}} and one might think of the color blue in relationship with the sky or the ocean, choosing an appropriate base color to represent your site is a good place to start. There are plenty of ways to select a base color; a few ideas include:

+ + + +

When trying to decide upon a base color, you may find that browser extensions that let you select colors from web content can be particularly handy. Some of these are even specifically designed to help with this sort of work. For example, the web site ColorZilla offers an extension (Chrome / Firefox) that offers an eyedropper tool for picking colors from the web. It can also take averages of the colors of pixels in various sized areas or even a selected area of the page.

+ +
+

The advantage to averaging colors can be that often what looks like a solid color is actually a surprisingly varied number of related colors all used in concert, blending to create a desired effect. Picking just one of these pixels can result in getting a color that on its own looks very out of place.

+
+ +

팔레트 다듬기

+ +

Once you have decided on your base color, there are plenty of online tools that can help you build out a palette of appropriate colors to use along with your base color by applying color theory to your base color to determine appropriate added colors. Many of these tools also support viewing the colors filtered so you can see what they would look like to people with various forms of color blindness. See {{anch("Color and accessibility")}} for a brief explanation of why this matters.

+ +

A few examples (all free to use as of the time this list was last revised):

+ + + +

When designing your palette, be sure to keep in mind that in addition to the colors these tools typically generate, you'll probably also need to add some core neutral colors such as white (or nearly white), black (or nearly black), and some number of shades of gray.

+ +
+

Usually, you are far better off using the smallest number of colors possible. By using color to accentuate rather than adding color to everything on the page, you keep your content easy to read and the colors you do use have far more impact.

+
+ +

색채이론 관련 자료

+ +

A full review of color theory is beyond the scope of this article, but there are plenty of articles about color theory available, as well as courses you can find at nearby schools and universities. A couple of useful resources about color theory:

+ +
+
Color Science (Khan Academy in association with Pixar)
+
An online course which introduces concepts such as what color is, how it's percieved, and how to use colors to express ideas. Presented by Pixar artists and designers.
+
{{interwiki("wikipedia", "Color theory")}} on Wikipedia
+
Wikipedia's entry on color theory, which has a lot of great information from a technical perspective. It's not really a resource for helping you with the color sleection process, but is still full of useful information.
+
+ +

색과 접근성

+ +

There are several ways color can be an {{Glossary("accessibility")}} problem. Improper or careless use of color can result in a web site or app that a percentage of your target audience may not be able to use adequately, resulting in lost traffic, lost business, and possibly even a public relations problem. So it's important to consider your use of color carefully.

+ +

You should do at least basic research into {{interwiki("wikipedia", "color blindness")}}. There are several kinds; the most common is red-green color blindness, which causes people to be unable to differentiate between the colors red and green. There are others, too, ranging from inabilities to tell the difference between certain colors to total inability to see color at all.

+ +
+

The most important rule: never use color as the only way to know something. If, for example, you indicate success or failure of an operation by changing the color of a shape from white to green for success and red for failure, users with red-green color-blindness won't be able to use your site properly. Instead, perhaps use both text and color together, so that everyone can understand what's happening.

+
+ +

For more information about color blindness, see the following articles:

+ + + +

팔레트 디자인 예제

+ +

Let's consider a quick example of selecting an appropriate color palette for a site. Imagine that you're building a web site for a new game that takes place on the planet Mars. So let's do a Google search for photos of Mars. Lots of good examples of Martian coloration there. We carefully avoid the mockups and the photos from movies. And we decide to use a photo taken by one of the Mars landers humanity has parked on the surface over the last few decades, since the game takes place on the planet's surface. We use a color picker tool to select a sample of the color we choose.

+ +

Using an eyedropper tool, we identify a color we like and determine that the color in question is #D79C7A, which is an appropriate rusty orange-red color that's so stereotypical of the Martian surface.

+ +

Having selected our base color, we need to build out our palette. We decide to use Paletton to come up with the other colors we need. Upon opening Paletton, we see:

+ +

Right after loading Paletton.

+ +

Next, we enter our color's hex code (D79C7A) into the "Base RGB" box at the bottom-left corner of the tool:

+ +

After entering base color

+ +

We now see a monochromatic palette based on the color we picked from the Mars photo. If you need a lot of related colors for some reason, those are likely to be good ones. But what we really want is an accent color. Something that will pop along side the base color. To find that, we click the "add complementary" toggle underneath the menu that lets you select the palette type (currently "Monochromatic"). Paletton computes an appropriate accent color; clicking on the accent color down in the bottom-right corner tells us that this color is #508D7C.

+ +

Now with complementary colors included.

+ +

If you're unhappy with the color that's proposed to you, you can change the color scheme, to see if you find something you like better. For example, if we don't like the proposed greenish-blue color, we can click the Triad color scheme icon, which presents us with the following:

+ +

Triad color scheme selected

+ +

That greyish blue in the top-right looks pretty good. Clicking on it, we find that it's #556E8D. That would be used as the accent color, to be used sparingly to make things stand out, such as in headlines or in the highlighting of tabs or other indicators on the site:

+ +

Triad color scheme selected

+ +

Now we have our base color and our accent. On top of that, we have a few complementary shades of each, just in case we need them for gradients and the like. The colors can then be exported in a number of formats so you can make use of them.

+ +

Once you have these colors, you will probably still need to select appropriate neutral colors. Common design practice is to try to find the sweet spot where there's just enough contrast that the text is crisp and readable but not enough contrast to become harsh for the eyes. It's easy to go too far in one way or another so be sure to get feedback on your colors once you've selected them and have examples of them in use available. If the contrast is too low, your text will tend to be washed out by the background, leaving it unreadable, but if your contrast is too high, the user may find your site garish and unpleasant to look at.

+ +

색, 배경, 대비, 출력

+ +

What looks good on screen may look very different on paper. In addition, ink can be expensive, and if a user is printing your page, they don't necessarily need all the backgrounds and such using up their precious ink when all that matters is the text itself. Most browsers, by default, remove background images when printing documents.

+ +

If your background colors and images have been selected carefully and/or are crucial to the usefulness of the content, you can use the CSS {{cssxref("color-adjust")}} property to tell the browser that it should not make adjustments to the appearance of content.

+ +

The default value of color-adjust, economy, indicates that the browser is allowed to make appearance changes as it deems necessary in order to try to optimize the legibility and/or print economy of the content, given the type of output device the document is being drawn onto.

+ +

You can set color-adjust to exact to tell the browser that the element or elements on which you use it have been designed specifically to best work with the colors and images left as they are. With this set, the browser won't tamper with the appearance of the element, and will draw it as indicated by your CSS.

+ +
+

참고: There is no guarantee, though, that color-adjust: exact will result in your CSS being used exactly as given. If the browser provides user preferences to change the output (such as a "don't print backgrounds" checkbox in a print dialog box), that overrides the value of color-adjust.

+
+ +

같이 보기

+ + diff --git a/files/ko/web/html/attributes/autocomplete/index.html b/files/ko/web/html/attributes/autocomplete/index.html new file mode 100644 index 0000000000..50c8de42f9 --- /dev/null +++ b/files/ko/web/html/attributes/autocomplete/index.html @@ -0,0 +1,247 @@ +--- +title: HTML autocomplete 특성 +slug: Web/HTML/Attributes/autocomplete +tags: + - Attribute + - HTML + - Reference + - 자동완성 +translation_of: Web/HTML/Attributes/autocomplete +--- +
{{HTMLSidebar("Global_attributes")}}
+ +

autocomplete 특성을 사용하면 {{glossary("user agent", "사용자 에이전트")}}의 자동완성을 허용할 양식 입력 필드를 지정할 수 있으며, 사용자 에이전트에게 어떤 정보에 대한 자동완성을 원하는지 안내할 수도 있습니다. HTML autocomplete 특성은 텍스트와 숫자를 허용하는 {{HTMLElement("input")}} 요소, {{HTMLElement("textarea")}} 요소, {{HTMLElement("select")}} 요소, {{HTMLElement("form")}} 요소에 사용할 수 있습니다.

+ +

자동완성으로 제안할 값의 출처는 대개 브라우저가 선택합니다. 사전 정의된 값을 사용할 수도 있으나 보통 과거에 사용자가 입력했던 값을 사용합니다. 예를 들어 사용자가 입력한 이름, 주소, 전화번호, 이메일 주소를 브라우저에 저장할 방법을 제공하기도 하고, 신용카드 정보를 미리 암호화해 저장하고 인증절차 후 자동완성 값으로 쓸 수도 있습니다.

+ +

{{HTMLElement("input")}}, {{HTMLElement("select")}}, {{HTMLElement("textarea")}} 요소에 autocomplete 특성을 지정하지 않은 경우, 브라우저는 요소의 양식 소유자, 즉 조상 {{HTMLElement("form")}} 요소 또는 {{htmlattrxref("form", "input")}} 특성의 값을 id 특성으로 사용하는 <form> 요소의 autocomplete 특성을 사용합니다.

+ +

더 많은 정보는 {{HTMLElement("form")}} 요소의 {{htmlattrxref("autocomplete", "form")}} 특성을 참고하세요.

+ +
+

<input>/<select>/<textarea> 요소가 다음 조건을 만족해야 사용자 에이전트가 자동완성을 제공할 수도 있습니다.

+ +
    +
  1. name 또는 id 특성 존재
  2. +
  3. <form> 요소의 자손일 것
  4. +
  5. 양식에 {{HTMLElement("input/submit", "제출")}} 버튼이 있을 것
  6. +
+
+ +

+ +
+
off
+
브라우저가 이 필드에 값을 자동으로 넣는 것을 금지합니다. 문서나 애플리케이션이 자신만의 자동완성 기능을 구현하거나, 보안상 문제로 자동완성을 사용하지 않아야 할 경우 지정할 수 있습니다. +
참고: 대부분의 최신 브라우저에서는 autocompleteoff로 지정하더라도 브라우저가 사용자에게 계정 이름과 비밀번호 저장 여부를 묻는 것을 막을 수 없으며, 저장한 값을 사용해 자동완성하는 것도 막을 수 없습니다. The autocomplete attribute and login fields 문서를 참고하세요.
+
+
on
+
브라우저의 자동완성을 허용합니다. 아무런 안내 정보도 제공하지 않으므로, 브라우저가 스스로의 판단 하에 값을 결정합니다.
+
name
+
사람의 전체 이름. 사람 이름 구조의 복잡함과 다양성으로 인해 보통 개별 이름 구성요소보다 name을 사용하는 것을 선호하지만, 하나씩 받아야 한다면 다음 autocomplete 값도 사용할 수 있습니다. +
+
honorific-prefix
+
호칭. "Mrs.", "Mr.", "Miss", "Ms.", "Dr.", "Mlle." 등.
+
family-name
+
성.
+
given-name
+
이름.
+
additional-name
+
가운데 이름.
+
honorific-suffix
+
접미사. "Jr.", "B.Sc.", "PhD.", "MBASW", "IV" 등.
+
nickname
+
별명, 별칭.
+
+
+
email
+
이메일 주소.
+
username
+
사용자 또는 계정 이름.
+
new-password
+
새로운 비밀번호. 계정을 생성할 때나 비밀번호를 변경할 때, new-password는 "새로운 비밀번호를 입력하세요" 또는 "비밀번호 확인"에 지정해야 합니다. 일반적인 비밀번호와 구분하는 이유는 브라우저가 기존 비밀번호를 자동완성으로 채우는 것을 피하기 위함이며, 안전한 무작위 비밀번호 생성을 제안할 곳을 결정할 때도 사용하기 때문입니다.
+
current-password
+
사용자의 현재 비밀번호.
+
one-time-code
+
사용자를 인증할 때 사용하는 1회성 코드.
+
organization-title
+
직위. "사장", "매니저", "시니어 테크니컬 커뮤니케이터" 등.
+
organization
+
회사 또는 조직명.
+
street-address
+
도로 주소. 여러 줄의 텍스트도 가능하며 두 번째 행정구역(시/군/구) 내에서 구분할 수 있는 주소여야 하지만, 도시 이름, 우편번호, 국가 이름은 포함해선 안됩니다.
+
address-line1, address-line2, address-line3
+
도로 주소의 각 줄. street-address가 존재하지 않는 경우에만 사용해야 합니다.
+
address-level4
+
4단계 주소에서 가장 상세한 {{anch("주소의 행정 단계", "행정구역")}}.
+
address-level3
+
최소 3단계 주소에서의 3단계 {{anch("주소의 행정 단계", "행정구역")}}.
+
address-level2
+
최소 2단계 주소에서의 2단계 {{anch("주소의 행정 단계", "행정구역")}}. 주소에 사용하는 행정구역을 두 단계로 분류하는 국가에서는 보통 도시, 마을 등입니다.
+
address-level1
+
첫 번째 {{anch("주소의 행정 단계", "행정구역")}}. 대한민국에서는 특별시·광역시·도, 미국에서는 주입니다.
+
country
+
국가 코드.
+
country-name
+
국가 이름.
+
postal-code
+
우편번호.
+
cc-name
+
신용카드 등 지불수단 소유자의 전체 이름. 보통 개별 이름 구성요소보다 이 쪽을 더 선호합니다.
+
cc-family-name
+
지불수단 소유자의 성.
+
cc-given-name
+
지불수단 소유자의 이름.
+
cc-additional-name
+
지불수단 소유자의 가운데 이름.
+
cc-number
+
신용카드 번호, 계좌번호 등 지불수단 식별 번호.
+
cc-exp
+
지불수단 유효기간. 보통 MM/YY 또는 MM/YYYY의 형태입니다.
+
cc-exp-month
+
지불수단 유효기간의 월.
+
cc-exp-year
+
지불수단 유효기간의 연도.
+
cc-csc
+
지불수단 보안 코드. 신용카드의 경우 뒷면의 세자리 숫자입니다.
+
cc-type
+
지불수단 유형. "Visa", "Master Card" 등.
+
transaction-currency
+
거래에 사용할 통화 단위.
+
transaction-amount
+
결제 양식에 나타나는 거래량, 금액. 단위는 transaction-currency에 나타난 값을 사용합니다.
+
language
+
선호 언어. 유효한 BCP 47 언어 태그여야 합니다.
+
bday
+
생년월일.
+
bday-day
+
생일.
+
bday-month
+
생월.
+
bday-year
+
생년.
+
sex
+
성별. "남성", "여성", "안드로진" 등 줄바꿈 없는 자유형식 텍스트입니다.
+
tel
+
국가 코드를 포함한 전체 전화번호. 개별 전화번호 구성요소가 필요한 경우 다음 값을 사용할 수 있습니다. +
+
tel-country-code
+
국가 코드. 1(북미), 82(대한민국) 등.
+
tel-national
+
국가 코드를 제외한 전체 전화번호. 지역번호도 포함합니다. 대한민국 전화번호 "82-2-555-6502"의 경우 "02-555-6502"가 됩니다.
+
tel-area-code
+
지역번호.
+
tel-local
+
국가 코드와 지역번호를 제외한 전화번호. 두 부분으로 나눌 수도 있으며, "555-6502"의 경우 tel-local-prefix는 "555", tel-local-suffix는 "6502"가 됩나다.
+
+
+
tel-extension
+
내선번호.
+
impp
+
인스턴트 메시지 프로토콜 엔드포인트의 URL. "xmpp:username@example.net" 등.
+
url
+
URL. 홈페이지, 회사 웹 사이트 주소 등 양식의 맥락에 맞는 값입니다.
+
photo
+
이미지 URL. 사람, 회사, 연락처 정보 등 양식의 맥락에 맞는 값입니다.
+
+ +

WHATWG 표준을 방문해 더 많은 정보를 알아보세요.

+ +

예제

+ +
<div>
+  <label for="cc-number">Enter your credit card number</label>
+  <input type="number" name="cc-number" id="cc-number" autocomplete="off">
+</div>
+ +

주소의 행정 단계

+ +

네 단계의 행정 단계(address-level1부터 address-level4까지)는 주소의 위치를 점차 좁아지는 범위로 나타냅니다. 각각의 국가는 서로 다른 행정구역 시스템을 사용하며 주소를 작성하는 순서도 다를 수 있습니다.

+ +

address-level1은 항상 제일 큰 단계이므로, 국가 이름을 제외한 주소에서 가장 넓은 범위를 나타냅니다.

+ +

유연한 양식 레이아웃

+ +

각각의 국가가 서로 다른 주소 형태를 사용하며, 구성요소의 위치는 물론 개수도 다를 수 있다는 점을 고려했을 때, 가능하다면 사용자가 입력하는 주소가 속한 국가에 따라서 양식의 형태를 바꾸는 것이 도움이 될 것입니다.

+ +

예제

+ +

행정구역 단위 사용법은 국가마다 다릅니다. 다음은 일부 예제로, 모든 상황을 포함하지는 않을 것입니다.

+ +

대한민국

+ +

도로명주소는 다음과 같은 형태입니다.

+ + + +
+
address-level1
+
시/도: "서울특별시", "경기도", "충청남도"
+
address-level2
+
시/군/구: "수원시", "홍성군", "종로구"
+
address-level3
+
구/읍/면: "팔달구", "홍북읍" +
참고: 구/읍/면은 address-level2에 합쳐 "수원시 팔달구", "홍성군 홍북읍"의 형태로 작성하는 경우도 많습니다.
+
+
address-line1
+
도로명, 건물번호: "세종로 1", "효원로 1", "충남대로 21"
+
address-line2
+
상세주소. 아파트의 경우 동/호를 작성합니다. +
참고: street-address를 사용하는 경우 도로명, 건물번호와 상세주소를 같이 작성합니다.
+
+
+ +

우편번호 찾기 기능을 사용하는 경우 행정구역과 도로명, 건물번호까지는 사용자가 직접 입력하지 않는 점도 유의하세요.

+ +

미국

+ +

평범한 주소는 다음 형태입니다.

+ +

432 Anywhere St
+ Exampleville CA 95555

+ +

미국에서의 가장 큰 행정구역은 "주"로, 위 주소에서는 "CA"("캘리포니아"의 미국 우정청 공식 줄임말)입니다. 따라서 address-level1은 주, 즉 "CA"를 사용합니다.

+ +

두 번째 행정구역은 도시 혹은 마을 이름이므로 adress-level2는 "Examplevile"입니다.

+ +

미국 주소는 3단계 이상을 사용하지 않습니다.

+ +

명세

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute", "autocomplete")}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ + + +

{{Compat("html.global_attributes.autocomplete")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/html/attributes/crossorigin/index.html b/files/ko/web/html/attributes/crossorigin/index.html new file mode 100644 index 0000000000..70131a4486 --- /dev/null +++ b/files/ko/web/html/attributes/crossorigin/index.html @@ -0,0 +1,96 @@ +--- +title: 'HTML attribute: crossorigin' +slug: Web/HTML/Attributes/crossorigin +translation_of: Web/HTML/Attributes/crossorigin +--- +
{{draft}}
+ +

{{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }}에 있는 crossOrigin 속성은 element가 CORS 요청을 처리하는 방식을 명시하여 element가 fetch한 데이터를 CORS 가능하게 합니다. 특정 element에서는 CORS 세팅 속성이 될 수도 있습니다.

+ +

Media element의 crossorigin 속성은 CORS 세팅입니다.

+ +

세팅 속성은 열거형이며 아래의 값을 가질 수 있습니다:

+ + + + + + + + + + + + + + + + + + + + +
KeywordDescription
anonymouselement의 CORS 요청의 credentials flag가 'same-origin'으로 지정됩니다.
use-credentialselement의 CORS 요청의 crendentials flag가 'include'로 지정됩니다.
""crossorigin 또는 crossorigin=""처럼 빈 값을 할당하는건 anonymous와 동일합니다.
+ +

기본적으로 (attribute를 명시하지 않으면) CORS 요청은 할 수 없습니다. "anonymous" 키워드는 쿠키를 통한 user credentials 교환이 필요 없음을 의미합니다. Same origin이 아닌 경우 client-side SSL certificates/HTTP 인증은 Terminology section of the CORS specification에서 기술하고 있습니다.

+ +

빈 문자열이나 잘못된 값일 경우 anonymous 와 동일하게 동작합니다.

+ +

예시: script element의 crossorigin

+ +

아래의 {{HTMLElement("script")}} element를 통해 브라우저로 하여금 https://example.com/example-framework.js 스크립트를 user-credential 없이 요청하도록 명시할 수 있습니다.

+ +
<script src="https://example.com/example-framework.js" crossorigin="anonymous"></script>
+ +

예시: credential 포함한 Webmanifest

+ +

Manifest 요청 시 credential이 필요하다면 same-origin의 리소스라 하여도  use-credentials 값을 사용해야 합니다.

+ +
<link rel="manifest" href="/app.webmanifest" crossorigin="use-credentials">
+ +

사양

+ + + + + + + + + + + + + + + + + + + + + +
사양상태설명
{{SpecName('HTML WHATWG', 'infrastructure.html#cors-settings-attributes', 'CORS settings attributes')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML WHATWG', 'embedded-content.html#attr-img-crossorigin', 'crossorigin')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ +

<script crossorigin>

+ + + +

{{Compat("html.elements.script.crossorigin")}}

+ +

<video crossorigin>

+ + + +

{{Compat("html.elements.video.crossorigin")}}

+ +

더 보기

+ + + +
{{QuickLinksWithSubpages("/en-US/docs/Web/HTML/")}}
diff --git a/files/ko/web/html/attributes/index.html b/files/ko/web/html/attributes/index.html new file mode 100644 index 0000000000..12e0c02235 --- /dev/null +++ b/files/ko/web/html/attributes/index.html @@ -0,0 +1,733 @@ +--- +title: HTML 특성 참고서 +slug: Web/HTML/Attributes +tags: + - HTML + - Reference +translation_of: Web/HTML/Attributes +--- +
{{HTMLSidebar}}
+ +

HTML의 요소들은 특성을 가지고 있습니다. 특성은 사용자가 원하는 기준에 맞도록 요소를 설정하거나 다양한 방식으로 요소의 동작을 조절하기 위한 값을 말합니다.

+ +

특성 목록

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
특성 이름요소설명
accept{{ HTMLElement("form") }}, {{ HTMLElement("input") }}서버에서 허용하는 유형의 목록. 보통 파일 유형을 의미합니다.
accept-charset{{ HTMLElement("form") }}지원하는 문자 집합의 목록.
accesskey전역 특성해당 요소로 초점을 이동시키거나 활성화시키기 위한 키보드 단축키를 정의합니다.
action{{ HTMLElement("form") }}폼(form)으로부터 전송된 정보를 처리할 프로그램의 URI입니다.
align{{ HTMLElement("applet") }}, {{ HTMLElement("caption") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }},  {{ HTMLElement("hr") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }},  {{ HTMLElement("td") }},  {{ HTMLElement("tfoot") }} , {{ HTMLElement("th") }}, {{ HTMLElement("thead") }}, {{ HTMLElement("tr") }}해당 요소의 가로 정렬 방식을 명시합니다.
allow{{ HTMLElement("iframe") }}Specifies a feature-policy for the iframe.
alt{{ HTMLElement("applet") }}, {{ HTMLElement("area") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}이미지를 표시할 수 없는 경우 표시할 대체 문구입니다.
async{{ HTMLElement("script") }}해당 스크립트는 비동기적으로 실행되어야함을 나타냅니다.
autocapitalize전역 특성사용자가 입력하거나 편집하는 문구를 자동으로 대문자로 바꿀지 여부와 방법을 제어합니다.
autocomplete{{ HTMLElement("form") }}, {{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}이 폼 내의 컨트롤에 대해 브라우저가 지원하는 값 자동완성 기능을 기본으로 설정할 것인지를 나타냅니다.
autofocus{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}페이지가 로드된 후 자동으로 해당 요소로 초점이 이동합니다.
autoplay{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}오디오나 비디오가 가능한 빠른 시점에 재생됩니다.
background{{ HTMLElement("body") }}, {{ HTMLElement("table") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}Specifies the URL of an image file. +
Note: Although browsers and email clients may still support this attribute, it is obsolete. Use CSS {{ Cssxref("background-image") }} instead.
+
bgcolor{{ HTMLElement("body") }}, {{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("table") }}, {{ HTMLElement("tbody") }}, {{ HTMLElement("tfoot") }}, {{ HTMLElement("td") }}, {{ HTMLElement("th") }}, {{ HTMLElement("tr") }} +

요소의 배경색입니다.

+ +
+

주: 이 속성은 더 이상 사용하지 않습니다. CSS의 {{ Cssxref("background-color") }} 속성을 대신 사용하시기 바랍니다.

+
+
border{{ HTMLElement("img") }}, {{ HTMLElement("object") }}, {{ HTMLElement("table") }} +

선의 굵기입니다.

+ +
+

주: 이 속성은 더 이상 사용하지 않습니다. CSS의 {{ Cssxref("border") }} 속성을 대신 사용하시기 바랍니다.

+
+
buffered{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}이미 버퍼링된 미디어의 시간 범위를 가집니다.
capture{{ HTMLElement("input") }}From the {{SpecName('HTML Media Capture', '#the-capture-attribute','media capture')}}spec, specifies a new file can be captured.
challenge{{ HTMLElement("keygen") }}공개 키와 같이 전송된 challenge 문자열입니다.
charset{{ HTMLElement("meta") }}, {{ HTMLElement("script") }}페이지 또는 스크립트의 문자 인코딩을 선언합니다.
checked{{ HTMLElement("command") }}, {{ HTMLElement("input") }}페이지가 로딩될 때, 해당 요소가 체크되어 있어야하는지를 나타냅니다.
cite{{ HTMLElement("blockquote") }}, {{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("q") }}변경 또는 인용구문의 출처를 가리키는 URI를 가집니다.
class전역 특성공통적인 속성으로 요소의 스타일을 지정할 때 CSS와 함께 자주 사용됩니다.
code{{ HTMLElement("applet") }}로딩 후 실행할 애플릿의 클래스 파일의 URL을 명시합니다.
codebase{{ HTMLElement("applet") }}이 속성은 코드(code) 속성이 참조하는 애플릿의 .class 파일이 저장되어 있는 디렉토리의 절대경로 또는 상대경로 URL을 제공합니다.
color{{ HTMLElement("basefont") }}, {{ HTMLElement("font") }}, {{ HTMLElement("hr") }} +

이 속성은 미리 정의된 색상 명칭 또는 #RRGGBB 형식의 16진수로 명시된 색상으로 텍스트 색상을 설정한다.

+ +
+

주: 이 속성은 더 이상 사용하지 않습니다. CSS의 {{ Cssxref("color") }} 속성을 대신 사용하시기 바랍니다.

+
+
cols{{ HTMLElement("textarea") }}textarea에 표시할 컬럼의 수를 정의한다.
colspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}colspan 속성은 어떤 셀이 확장되어야 할 컬럼의 수를 정의한다.
content{{ HTMLElement("meta") }}A value associated with http-equiv or name depending on the context.
contenteditable전역 특성Indicates whether the element's content is editable.
contextmenu전역 특성Defines the ID of a {{ HTMLElement("menu") }} element which will serve as the element's context menu.
controls{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the browser should show playback controls to the user.
coords{{ HTMLElement("area") }}A set of values specifying the coordinates of the hot-spot region.
crossorigin{{ HTMLElement("audio") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}, {{ HTMLElement("video") }}How the element handles cross-origin requests
csp {{experimental_inline}}{{ HTMLElement("iframe") }}Specifies the Content Security Policy that an embedded document must agree to enforce upon itself.
data{{ HTMLElement("object") }}Specifies the URL of the resource.
data-*전역 특성Lets you attach custom attributes to an HTML element.
datetime{{ HTMLElement("del") }}, {{ HTMLElement("ins") }}, {{ HTMLElement("time") }}Indicates the date and time associated with the element.
decoding{{ HTMLElement("img") }}Indicates the preferred method to decode the image.
default{{ HTMLElement("track") }}Indicates that the track should be enabled unless the user's preferences indicate something different.
defer{{ HTMLElement("script") }}Indicates that the script should be executed after the page has been parsed.
dir전역 특성Defines the text direction. Allowed values are ltr (Left-To-Right) or rtl (Right-To-Left)
dirname{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}
disabled{{ HTMLElement("button") }}, {{ HTMLElement("command") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("optgroup") }}, {{ HTMLElement("option") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates whether the user can interact with the element.
download{{ HTMLElement("a") }}, {{ HTMLElement("area") }}Indicates that the hyperlink is to be used for downloading a resource.
draggable전역 특성Defines whether the element can be dragged.
dropzone전역 특성Indicates that the element accept the dropping of content on it.
enctype{{ HTMLElement("form") }}Defines the content type of the form date when the method is POST.
enterkeyhint {{experimental_inline}}{{ HTMLElement("textarea") }}, contenteditableThe enterkeyhint specifies what action label (or icon) to present for the enter key on virtual keyboards. The attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute).
for{{ HTMLElement("label") }}, {{ HTMLElement("output") }}Describes elements which belongs to this one.
form{{ HTMLElement("button") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("label") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}Indicates the form that is the owner of the element.
formaction{{ HTMLElement("input") }}, {{ HTMLElement("button") }}Indicates the action of the element, overriding the action defined in the {{ HTMLElement("form") }}.
formenctype{{ HTMLElement("button") }}, {{ HTMLElement("input") }}If the button/input is a submit button (type="submit"), this attribute sets the encoding type to use during form submission. If this attribute is specified, it overrides the enctype attribute of the button's form owner.
formmethod{{ HTMLElement("button") }}, {{ HTMLElement("input") }}If the button/input is a submit button (type="submit"), this attribute sets the submission method to use during form submission (GET, POST, etc.). If this attribute is specified, it overrides the method attribute of the button's form owner.
formnovalidate{{ HTMLElement("button") }}, {{ HTMLElement("input") }}If the button/input is a submit button (type="submit"), this boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the novalidate attribute of the button's form owner.
formtarget{{ HTMLElement("button") }}, {{ HTMLElement("input") }}If the button/input is a submit button (type="submit"), this attribute specifies the browsing context (for example, tab, window, or inline frame) in which to display the response that is received after submitting the form. If this attribute is specified, it overrides the target attribute of the button's form owner.
headers{{ HTMLElement("td") }}, {{ HTMLElement("th") }}IDs of the <th> elements which applies to this element.
height{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }} +

Specifies the height of elements listed here. For all other elements, use the CSS {{cssxref("height")}} property.

+ +
+

Note: In some instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("height") }} property should be used instead.

+
+
hidden전역 특성Prevents rendering of given element, while keeping child elements, e.g. script elements, active.
high{{ HTMLElement("meter") }}Indicates the lower bound of the upper range.
href{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("link") }} 링크된 리소스의 URL
hreflang{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}링크된 리소스의 언어를 나타냄
http-equiv{{ HTMLElement("meta") }}
icon{{ HTMLElement("command") }}Specifies a picture which represents the command.
id전역 특성일반적으로, 특정한 요소를 스타일하기 위해 CSS와 함꼐 사용됨. 이 속성의 값은 유일해야함.
importance {{experimental_inline}}{{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("link") }}, {{ HTMLElement("script") }}Indicates the relative fetch priority for the resource.
integrity{{ HTMLElement("link") }}, {{ HTMLElement("script") }}Specifies a Subresource Integrity value that allows browsers to verify what they fetch.
intrinsicsize {{deprecated_inline}}{{ HTMLElement("img") }}This attribute tells the browser to ignore the actual intrinsic size of the image and pretend it’s the size specified in the attribute.
inputmode{{ HTMLElement("textarea") }}, contenteditableProvides a hint as to the type of data that might be entered by the user while editing the element or its contents. The attribute can be used with form controls (such as the value of textarea elements), or in elements in an editing host (e.g., using contenteditable attribute).
ismap{{ HTMLElement("img") }}Indicates that the image is part of a server-side image map.
itemprop전역 특성
keytype{{ HTMLElement("keygen") }}Specifies the type of key generated.
kind{{ HTMLElement("track") }}Specifies the kind of text track.
label{{ HTMLElement("track") }}Specifies a user-readable title of the text track.
lang전역 특성요소에서 사용된 언어를 정의합니다.
language{{ HTMLElement("script") }}요소에서 사용된 스크립트 언어를 정의합니다.
list{{ HTMLElement("input") }}Identifies a list of pre-defined options to suggest to the user.
loading {{experimental_inline}}{{ HTMLElement("img") }}, {{ HTMLElement("iframe") }}Indicates if the element should be loaded lazily (loading="lazy") or loaded immediately (loading="eager").
list{{ HTMLElement("input") }}Identifies a list of pre-defined options to suggest to the user.
loop{{ HTMLElement("audio") }}, {{ HTMLElement("bgsound") }}, {{ HTMLElement("marquee") }}, {{ HTMLElement("video") }}미디어가 재생을 완료했을때 다시 재생을 시작해야할지를 나타냅니다.
low{{ HTMLElement("meter") }}Indicates the upper bound of the lower range.
manifest{{ HTMLElement("html") }}문서의 캐시 매니페스트의 URL을 가리킵니다.
max{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}허용되는 최대 값을 나타냅니다.
maxlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}요소에 허용되는 문자의 최대 길이를 나타냅니다.
minlength{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}Defines the minimum number of characters allowed in the element.
media{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}Specifies a hint of the media for which the linked resource was designed.
method{{ HTMLElement("form") }}폼을 제출할때 사용할 HTTP 메소드를 정의함. GET(기본값) 또는 POST 가 될수 있음.
min{{ HTMLElement("input") }}, {{ HTMLElement("meter") }}허용되는 최소 값을 나타냄.
multiple{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Indicates whether multiple values can be entered in an input of the type email or file.
muted{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}Indicates whether the audio will be initially silenced on page load.
name{{ HTMLElement("button") }}, {{ HTMLElement("form") }}, {{ HTMLElement("fieldset") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("input") }}, {{ HTMLElement("keygen") }}, {{ HTMLElement("object") }}, {{ HTMLElement("output") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}, {{ HTMLElement("map") }}, {{ HTMLElement("meta") }}, {{ HTMLElement("param") }}요소의 이름. For example used by the server to identify the fields in form submits.
novalidate{{ HTMLElement("form") }}This attribute indicates that the form shouldn't be validated when submitted.
open{{ HTMLElement("details") }}Indicates whether the details will be shown on page load.
optimum{{ HTMLElement("meter") }}Indicates the optimal numeric value.
pattern{{ HTMLElement("input") }}Defines a regular expression which the element's value will be validated against.
ping{{ HTMLElement("a") }}, {{ HTMLElement("area") }}
placeholder{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}필드에 무엇이 들어갈수 있는지 사용자에게 힌트를 제공합니다.
poster{{ HTMLElement("video") }}A URL indicating a poster frame to show until the user plays or seeks.
preload{{ HTMLElement("audio") }}, {{ HTMLElement("video") }}전체,부분,또는 아무런 리소스가 미리 로드되어야하는지를 나타냅니다.
radiogroup{{ HTMLElement("command") }}
readonly{{ HTMLElement("input") }}, {{ HTMLElement("textarea") }}요소가 수정될 수 있는지를 나타냅니다.
rel{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("link") }}Specifies the relationship of the target object to the link object.
required{{ HTMLElement("input") }}, {{ HTMLElement("select") }}, {{ HTMLElement("textarea") }}이 요소가 채워져야 하는지를 나타냅니다.
reversed{{ HTMLElement("ol") }}Indicates whether the list should be displayed in a descending order instead of a ascending.
rows{{ HTMLElement("textarea") }}textarea의 줄 개수를 정의합니다.
rowspan{{ HTMLElement("td") }}, {{ HTMLElement("th") }}Defines the number of rows a table cell should span over.
sandbox{{ HTMLElement("iframe") }}
scope{{ HTMLElement("th") }}
scoped{{ HTMLElement("style") }}
selected{{ HTMLElement("option") }}Defines a value which will be selected on page load.
shape{{ HTMLElement("a") }}, {{ HTMLElement("area") }}
size{{ HTMLElement("input") }}, {{ HTMLElement("select") }}Defines the width of the element (in pixels). If the element's type attribute is text or password then it's the number of characters.
sizes{{ HTMLElement("link") }}
slot전역 특성Assigns a slot in a shadow DOM shadow tree to an element.
span{{ HTMLElement("col") }}, {{ HTMLElement("colgroup") }}
spellcheck전역 특성Indicates whether spell checking is allowed for the element.
src{{ HTMLElement("audio") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("track") }}, {{ HTMLElement("video") }}내장 컨텐츠의 URL
srcdoc{{ HTMLElement("iframe") }}
srclang{{ HTMLElement("track") }}
srcset{{ HTMLElement("img") }}
start{{ HTMLElement("ol") }}Defines the first number if other than 1.
step{{ HTMLElement("input") }}
style전역 특성이전 스타일을 오버라이드할 CSS 스타일을 정의함.
summary{{ HTMLElement("table") }}
tabindex전역 특성Overrides the browser's default tab order and follows the one specified instead.
target{{ HTMLElement("a") }}, {{ HTMLElement("area") }}, {{ HTMLElement("base") }}, {{ HTMLElement("form") }}
title전역 특성요소 위에 호버링했을떄 표시될 툴팁의 텍스트
translate전역 특성Specify whether an element’s attribute values and the values of its Text node children are to be translated when the page is localized, or whether to leave them unchanged.
type{{ HTMLElement("button") }}, {{ HTMLElement("input") }}, {{ HTMLElement("command") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("object") }}, {{ HTMLElement("script") }}, {{ HTMLElement("source") }}, {{ HTMLElement("style") }}, {{ HTMLElement("menu") }}요소의 타입을 정의함
usemap{{ HTMLElement("img") }},  {{ HTMLElement("input") }}, {{ HTMLElement("object") }}
value{{ HTMLElement("button") }}, {{ HTMLElement("option") }}, {{ HTMLElement("input") }}, {{ HTMLElement("li") }}, {{ HTMLElement("meter") }}, {{ HTMLElement("progress") }}, {{ HTMLElement("param") }}페이지가 로드된뒤 요소에 표시될 기본값을 지정합니다.
width{{ HTMLElement("canvas") }}, {{ HTMLElement("embed") }}, {{ HTMLElement("iframe") }}, {{ HTMLElement("img") }}, {{ HTMLElement("input") }}, {{ HTMLElement("object") }}, {{ HTMLElement("video") }}Note: In some instances, such as {{ HTMLElement("div") }}, this is a legacy attribute, in which case the CSS {{ Cssxref("width") }} property should be used instead. In other cases, such as {{ HTMLElement("canvas") }}, the width must be specified with this attribute.
wrap{{ HTMLElement("textarea") }}Indicates whether the text should be wrapped.
+ +

Content versus IDL attributes

+ +

In HTML, most attributes have two faces: the content attribute and the IDL attribute.

+ +

The content attribute is the attribute as you set it from the content (the HTML code) and you can set it or get it via {{domxref("element.setAttribute()")}} or {{domxref("element.getAttribute()")}}. The content attribute is always a string even when the expected value should be an integer. For example, to set an {{HTMLElement("input")}} element's maxlength to 42 using the content attribute, you have to call setAttribute("maxlength", "42") on that element.

+ +

The IDL attribute is also known as a JavaScript property. These are the attributes you can read or set using JavaScript properties like element.foo. The IDL attribute is always going to use (but might transform) the underlying content attribute to return a value when you get it and is going to save something in the content attribute when you set it. In other words, the IDL attributes, in essence, reflect the content attributes.

+ +

Most of the time, IDL attributes will return their values as they are really used. For example, the default type for {{HTMLElement("input")}} elements is "text", so if you set input.type="foobar", the <input> element will be of type text (in the appearance and the behavior) but the "type" content attribute's value will be "foobar". However, the type IDL attribute will return the string "text".

+ +

IDL attributes are not always strings; for example, input.maxlength is a number (a signed long). When using IDL attributes, you read or set values of the desired type, so input.maxlength is always going to return a number and when you set input.maxlength ,it wants a number. If you pass another type, it is automatically converted to a number as specified by the standard JavaScript rules for type conversion.

+ +

IDL attributes can reflect other types such as unsigned long, URLs, booleans, etc. Unfortunately, there are no clear rules and the way IDL attributes behave in conjunction with their corresponding content attributes depends on the attribute. Most of the time, it will follow the rules laid out in the specification, but sometimes it doesn't. HTML specifications try to make this as developer-friendly as possible, but for various reasons (mostly historical), some attributes  behave oddly (select.size, for example) and you should read the specifications to understand how exactly they behave.

+ +

같이 보기

+ + diff --git a/files/ko/web/html/block-level_elements/index.html b/files/ko/web/html/block-level_elements/index.html new file mode 100644 index 0000000000..637ace1c8c --- /dev/null +++ b/files/ko/web/html/block-level_elements/index.html @@ -0,0 +1,127 @@ +--- +title: 블록 레벨 요소 +slug: Web/HTML/Block-level_elements +tags: + - Beginner + - Development + - Guide + - HTML + - HTML5 + - Web +translation_of: Web/HTML/Block-level_elements +--- +

HTML(Hypertext Markup Language)의 요소는 역사적으로 "블록 레벨" 요소와 "인라인" 요소로 분류됐습니다. 기본적으로 블록 레벨 요소는 부모 요소의 전체 공간을 차지하여 "블록"을 만듭니다. 이 글에서 자세한 설명을 읽을 수 있습니다.

+ +

{{glossary("browser", "브라우저")}}는 보통 블록 레벨 요소의 앞과 뒤를 개행해서 그립니다. 상자를 쌓는 것 처럼 생각할 수 있습니다.

+ +
+

블록 레벨 요소는 언제나 새로운 줄에서 시작하고, 좌우 양쪽으로 최대한 늘어나 가능한 모든 너비를 차지합니다.

+
+ +

다음 예제가 블록 레벨 요소의 영향을 보여줍니다.

+ +

블록 레벨 요소

+ +

HTML

+ +
<p>이 문단은 블록 레벨 요소입니다. 부모 요소와 구분할 수 있도록 배경 색을 입혔습니다.</p>
+ +

CSS

+ +
p { background-color: #8ABB55; }
+ +

{{EmbedLiveSample('블록_레벨_요소')}}

+ +

사용처

+ + + +

블록 레벨 vs. 인라인

+ +

블록 레벨 요소와 인라인 요소는 몇 가지 중요한 차이점을 가지고 있습니다.

+ +
+
콘텐츠 모델
+
일반적으로 블록 레벨 요소는 인라인 요소와 (때때로) 다른 블록 레벨 요소를 포함할 수 있습니다. 이런 고유한 구조적 차이점으로 인해 블록 레벨 요소는 인라인 요소보다 더 "큰" 구조를 생성할 수 있습니다.
+
기본 서식
+
기본적으로 블록 레벨 요소는 새로운 줄에서 시작하지만, 인라인 요소는 줄의 어느 곳에서나 시작할 수 있습니다.
+
+ +

블록 레벨과 인라인 요소의 분류는 HTML 명세 4.01까지 사용됐습니다. 이런 이진적 구분은 HTML5부터 보다 복잡한 콘텐츠 카테고리 집합으로 대체됐습니다. "인라인" 카테고리는 구문 콘텐츠와 적당히 짝지을 수 있지만 "블록 레벨" 카테고리는 어느 HTML5 콘텐츠 카테고리와도 정확히 일치하지 않습니다. 그러나 블록 레벨과 인라인 요소를 조합하면 플로우 콘텐츠에 대응합니다. 대화형 콘텐츠 등 추가 카테고리도 존재합니다.

+ +

요소 목록

+ +

다음은 HTML 블록 레벨 요소의 전체 목록입니다. (사실 HTML5의 새로운 요소를 설명할 때, "블록 레벨"이라는 용어는 정의되지 않습니다.)

+ +
+
+
{{ HTMLElement("address") }}
+
연락처 정보.
+
{{ HTMLElement("article") }}
+
단락 콘텐츠.
+
{{ HTMLElement("aside") }}
+
부가 콘텐츠.
+
{{ HTMLElement("blockquote") }}
+
긴("블록")  인용구.
+
{{HTMLElement("details")}}
+
상세 정보 위젯.
+
{{HTMLElement("dialog")}}
+
대화상자.
+
{{ HTMLElement("dd") }}
+
설명 목록의 정의 설명.
+
{{ HTMLElement("div") }}
+
문서의 분할.
+
{{ HTMLElement("dl") }}
+
설명 목록.
+
{{HTMLElement("dt")}}
+
설명 목록의 정의.
+
{{ HTMLElement("fieldset") }}
+
필드 집합의 라벨.
+
{{ HTMLElement("figcaption") }}
+
그림 설명.
+
{{ HTMLElement("figure") }}
+
미디어 콘텐츠 그룹과 설명. ({{ HTMLElement("figcaption") }}을 참고하세요)
+
{{ HTMLElement("footer") }}
+
페이지나 구역의 푸터.
+
{{ HTMLElement("form") }}
+
입력 폼.
+
{{ HTMLElement("h1") }}, {{ HTMLElement("h2") }}, {{ HTMLElement("h3") }}, {{ HTMLElement("h4") }}, {{ HTMLElement("h5") }}, {{ HTMLElement("h6") }}
+
1~6단계 제목.
+
{{ HTMLElement("header") }}
+
페이지나 구역의 헤더.
+
{{ HTMLElement("hgroup") }}
+
헤더 정보 그룹.
+
{{ HTMLElement("hr") }}
+
수평선(구분선).
+
{{HTMLElement("li")}}
+
목록의 항목.
+
{{HTMLElement("main")}}
+
문서에서 하나 뿐인 중심 콘텐츠.
+
{{HTMLElement("nav")}}
+
탐색 링크를 포함.
+
{{ HTMLElement("ol") }}
+
정렬된 목록.
+
{{ HTMLElement("p") }}
+
문단.
+
{{ HTMLElement("pre") }}
+
미리 서식 적용한 글.
+
{{ HTMLElement("section") }}
+
웹 페이지의 구역.
+
{{ HTMLElement("table") }}
+
표.
+
{{ HTMLElement("ul") }}
+
정렬되지 않은 목록.
+
+
+ +

같이 보기

+ + + +
{{QuickLinksWithSubpages("/ko/docs/Web/HTML/")}}
diff --git a/files/ko/web/html/canvas/index.html b/files/ko/web/html/canvas/index.html new file mode 100644 index 0000000000..bbe466e58d --- /dev/null +++ b/files/ko/web/html/canvas/index.html @@ -0,0 +1,135 @@ +--- +title: Canvas API +slug: Web/HTML/Canvas +tags: + - API + - Canvas + - JavaScript + - 개요 + - 레퍼런스 +translation_of: Web/API/Canvas_API +--- +
{{CanvasSidebar}}
+ +

Canvas API는 JavaScript와 HTML {{HtmlElement("canvas")}} 엘리먼트를 통해 그래픽을 그리기위한 수단을 제공합니다. 무엇보다도 애니메이션, 게임 그래픽, 데이터 시각화, 사진 조작 및 실시간 비디오 처리를 위해 사용됩니다.

+ +

Canvas API는 주로 2D 그래픽에 중점을 두고 있습니다. WebGL API 또한 <canvas> 엘리먼트를 사용하며, 하드웨어 가속 2D 및 3D 그래픽을 그립니다.

+ +

기본 예시

+ +

canvas에 초록색 사각형을 그리는 간단한 예시입니다.

+ +

HTML

+ +
<canvas id="canvas"></canvas>
+
+ +

JavaScript

+ +

{{domxref("Document.getElementById()")}} 메소드는 HTML <canvas> 엘리먼트에 대한 참조를 얻습니다. 그 다음, {{domxref("HTMLCanvasElement.getContext()")}} 메소드는 엘리먼트의 컨텍스트(렌더링될 그리기의 대상)를 얻습니다.

+ +

실제 그리기는 {{domxref("CanvasRenderingContext2D")}} 인터페이스를 사용해 수행됩니다. {{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle")}} 프로퍼티는 사각형을 초록색으로 만듭니다. {{domxref("CanvasRenderingContext2D.fillRect()", "fillRect()")}} 메소드는 좌측 상단 코너를 (10, 10) 위치에 놓으며, 너비를 150, 높이를 100으로 지정합니다.

+ +
const canvas = document.getElementById('canvas');
+const ctx = canvas.getContext('2d');
+
+ctx.fillStyle = 'green';
+ctx.fillRect(10, 10, 150, 100);
+
+ +

결과

+ +

{{ EmbedLiveSample('기본_예시', 700, 180) }}

+ +

레퍼런스

+ +
+ +
+ +
+

노트: WebGLRenderingContext에 관련된 인터페이스는 WebGL 하위에 참조되어있습니다.

+
+ +

{{domxref("CanvasCaptureMediaStream")}}은 관련된 인터페이스입니다.

+ +

가이드 및 튜토리얼

+ +
+
Canvas 튜토리얼
+
Canvas API의 기본적인 사용과 고급 기능 모두를 다루는 이해하기 쉬운 튜토리얼.
+
HTML5 Canvas 깊이 살펴보기
+
Canvas API 및 WebGL의 실습, 자세한 소개.
+
Canvas 핸드북
+
Canvas API에 대한 유용한 레퍼런스.
+
데모: A basic ray-caster
+
Canvas를 사용한 ray-tracing 애니메이션 데모.
+
Canvas를 사용하여 비디오 조작
+
{{HTMLElement("video")}}와 {{HTMLElement("canvas")}}를 조합하여 실시간으로 비디오 데이터를 조작.
+
+ +

라이브러리

+ +

Canvas API는 굉장히 강력하지만, 사용하는 것이 항상 간단하지 않습니다. 아래에 나열된 라이브러리들은 캔버스 기반 프로젝트를 더 빠르고 더 쉽게 생성할 수 있게 해줍니다.

+ + + +
+

노트: WebGL을 사용하는 2D 및 3D를 위한 WebGL API를 확인하세요.

+
+ +

명세

+ + + + + + + + + + + + + + + + +
명세상태코멘트
{{SpecName('HTML WHATWG', '#2dcontext', 'the 2D rendering context')}}{{Spec2('HTML WHATWG')}}
+ +

브라우저 호환성

+ +

Mozilla 애플리케이션은 Gecko 1.8(Firefox 1.5)을 시작으로 <canvas>에 대한 지원을 받았습니다. OS X Dashboard 및 Safari를 위해 Apple이 소개한 것이 캔버스 엘리먼트의 기원입니다. Internet Explorer는 9버전부터 <canvas>를 지원하며, 이전 버전의 IE에서는 Google의 Explorer Canvas 프로젝트의 스크립트를 추가하여 <canvas>에 대한 지원을 효과적으로 추가할 수 있습니다. Google Chrome 및 Opera 9 또한 <canvas>를 지원합니다.

+ +

함께 보기

+ + diff --git a/files/ko/web/html/canvas/manipulating_video_using_canvas/index.html b/files/ko/web/html/canvas/manipulating_video_using_canvas/index.html new file mode 100644 index 0000000000..7851f86154 --- /dev/null +++ b/files/ko/web/html/canvas/manipulating_video_using_canvas/index.html @@ -0,0 +1,164 @@ +--- +title: 캔버스(canvas)를 이용한 비디오 조작하기 +slug: Web/HTML/Canvas/Manipulating_video_using_canvas +tags: + - Canvas + - Video + - 비디오 + - 캔버스 +translation_of: Web/API/Canvas_API/Manipulating_video_using_canvas +--- +
{{CanvasSidebar}}
+ +
+

비디오에서 다양한 시각적 효과를 보여주기 위해, 캔버스비디오의 기능을 결합하여 실시간으로 비디오 데이터를 조작할 수 있습니다. 이 튜토리얼에서는 자바스크립트 코드로 어떻게 크로마 키잉(chroma-keying, 또한 "녹색 스크린 효과, green screen effect")을 구현할 수 있는지 보여줍니다. 

+
+ +

라이브 예제 보기

+ +

문서(document) 내용

+ +

이 내용을 보여주기 위한 XHTML 문서는 아래와 같습니다.

+ +
<!DOCTYPE html>
+<html>
+  <head>
+    <style>
+      body {
+        background: black;
+        color:#CCCCCC;
+      }
+      #c2 {
+        background-image: url(foo.png);
+        background-repeat: no-repeat;
+      }
+      div {
+        float: left;
+        border :1px solid #444444;
+        padding:10px;
+        margin: 10px;
+        background:#3B3B3B;
+      }
+    </style>
+    <script type="text/javascript" src="main.js"></script>
+  </head>
+
+  <body onload="processor.doLoad()">
+    <div>
+      <video id="video" src="video.ogv" controls="true"/>
+    </div>
+    <div>
+      <canvas id="c1" width="160" height="96"></canvas>
+      <canvas id="c2" width="160" height="96"></canvas>
+    </div>
+  </body>
+</html>
+
+ +

여기에서 중요한 요소는:

+ +
    +
  1. 이 문서에는 ID가 c1, c2인 두 개의  캔버스가 있습니다. 캔버스 c1은 비디오 원본의 현재 프레임을 보여주기 위해 사용되고, c2는 크로마 키잉 효과를 수행한 결과를 보여줍니다. c2에서 비디오의 녹색 배경을 대체할 정지 이미지를 미리 로드합니다.
  2. +
  3. 자바스크립트 코드는 main.js에서 가져옵니다. 이 스크립트는 자바스크립트 1.8 기능을 사용했기 때문에 스크립트를 가져오는 22번째 줄에서 버전이 명시됩니다(원문: this script uses JavaScript 1.8 features, so that version is specified in line 22 when importing the script).
  4. +
  5. 문서가 로드되면, processor.doLoad() 메서드가 실행됩니다.
  6. +
+ +

자바스크립트 코드

+ +

main.js에 있는 자바스크립트 코드는 3개의 메서드로 구성됩니다.

+ +

크로마 키잉 플레이어 초기화

+ +

doLoad() 메서드는 문서가 최초에 로드될 때 호출됩니다. 이 메서드가 하는 일은 크로마 키잉 처리에서 쓰일 변수를 준비하고, 이벤트 리스너를 등록함으로써 사용자가 비디오 재생을 시작할 때 감지할 수 있도록 해줍니다. 

+ +
  var processor;
+
+  processor.doLoad = function doLoad() {
+    this.video = document.getElementById('video');
+    this.c1 = document.getElementById('c1');
+    this.ctx1 = this.c1.getContext('2d');
+    this.c2 = document.getElementById('c2');
+    this.ctx2 = this.c2.getContext('2d');
+    let self = this;
+    this.video.addEventListener('play', function() {
+        self.width = self.video.videoWidth / 2;
+        self.height = self.video.videoHeight / 2;
+        self.timerCallback();
+      }, false);
+  },
+
+ +

이코드는 XHTML에서 중요한 요소인 비디오와 캔버스의 참조를 가져옵니다. 두 개의 캔버스에 대한 그래픽 컨텍스트의 참조도 가져옵니다. 이 참조들은 뒤에서 크로마 키잉 효과를 구현할 때 사용됩니다.

+ +

그리고 addEventListener()는 비디오가 재생을 시작하기 위해 호출되기 때문에 사용자가 재생 버튼을 누를 때 알림을 받습니다. 재생이 시작되면 이 코드는 비디오의 가로, 세로를 이등분 한 값을 가져오고(크로마 키잉 효과를 수행할 때 이등분 함), timerCallback() 메서드를 호출하여 비디오를 보고 시각적 효과를 계산하기 시작합니다.

+ +

타이머 콜백

+ +

타이머 콜백은 비디오가 재생되기 시작("재생" 이벤트가 발생)할 때 호출되는데, 매 프레임마다 키잉 효과를 주기 위해 주기적으로 호출 될 수 있도록 설정해 주어야 합니다.

+ +
  processor.timerCallback = function timerCallback() {
+    if (this.video.paused || this.video.ended) {
+      return;
+    }
+    this.computeFrame();
+    let self = this;
+    setTimeout(function() {
+        self.timerCallback();
+      }, 0);
+  },
+
+ +

콜백에서 하는 첫 번 째 일은 비디오가 재생되고 있는지 확인하는 것인데, 만약 그렇지 않다면 콜백은 아무 일도 하지 않고 즉시 반환됩니다.

+ +

그 후에 현재 비디오 프레임에서 크로마 키잉 효과를 주기 위한 computeFrame() 메서드를 호출합니다.

+ +

콜백에서 마지막으로 하는 일은 setTimeout()을 호출하여 가능한 한 빨리 timerCallback() 메서드를 다시 호출할 수 있도록 하는 것입니다. 실제로는, 비디오 프레임 속도에 대한 기반 지식으로 호출할 수 있도록 합니다. 

+ +

비디오 프레임 데이터 조작

+ +

아래의 computeFrame() 메서드는 프레임 데이터를 가져와서 크로마 키잉 효과를 수행하는 역할을 합니다. 

+ +
  processor.computeFrame = function computeFrame() {
+    this.ctx1.drawImage(this.video, 0, 0, this.width, this.height);
+    let frame = this.ctx1.getImageData(0, 0, this.width, this.height);
+    let l = frame.data.length / 4;
+
+    for (let i = 0; i < l; i++) {
+      let r = frame.data[i * 4 + 0];
+      let g = frame.data[i * 4 + 1];
+      let b = frame.data[i * 4 + 2];
+      if (g > 100 && r > 100 && b < 43)
+        frame.data[i * 4 + 3] = 0;
+    }
+    this.ctx2.putImageData(frame, 0, 0);
+    return;
+  }
+
+ +

위 과정이 계속 호출 되면, 아래와 같이 비디오 요소에 가장 최근 프레임의 비디오 데이터가 표출됩니다.

+ +

video.png

+ +

2번째 줄에서, 첫 번째 캔버스의 그래픽 컨텍스트 ctx1에 비디오 프레임이 복사 되는데, 원본의 절반 크기로 프레임을 그리기 위해 이전에 저장한 가로, 세로 값으로 지정합니다. 컨텍스트의 drawImage() 메서드에 비디오 요소를 전달하기만 하면 현재 비디오 프레임을 그릴 수 있습니다. 결과는 아래와 같습니다: 

+ +

sourcectx.png

+ +

3번째 줄에서는 첫 번째 컨텍스트의 getImageData() 메서드를 호출해서 현재 비디오 프레임의 원시 그래픽 데이터 복사본을 가져옵니다. 이것은 조작할 수 있는 원시 32비트 픽셀 이미지 데이터를 제공합니다. 4번째 줄에서는 프레임의 이미지 데이터 전체 크기를 4로 나누어 이미지의 픽셀 수를 계산합니다.

+ +

6번째 줄에서 시작하는 for 문은 프레임의 픽셀을 스캔하여, 빨간색, 녹색, 파란색 값을 추출하여 사전에 정의된 숫자와 비교합니다. 이 숫자는 foo.png에서 가져온 배경 이미지로 대체될 녹색 스크린 영역을 감지합니다.

+ +

녹색 스크린이라고 간주된 매개변수 내의 프레임 이미지 데이터의 모든 픽셀은 투명해질 수 있도록 알파값이 0으로 대체됩니다. 결과적으로 최종 이미지는 100% 투명해진 녹색 스크린 영역을 갖게 되고, 13번째 줄에서 대상 컨텍스트에 고정된 배경 위로 올려져 그려집니다.

+ +

결과 이미지는 아래와 같습니다:

+ +

output.png

+ +

이 과정은 비디오가 재생될 때마다 반복되므로, 매 프레임마다 처리되어 크로마 키잉 효과가 나타나는 것입니다.

+ +

라이브 예제 보기

+ +

더 보기

+ + diff --git a/files/ko/web/html/canvas/tutorial/advanced_animations/index.html b/files/ko/web/html/canvas/tutorial/advanced_animations/index.html new file mode 100644 index 0000000000..1779e63b2c --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/advanced_animations/index.html @@ -0,0 +1,376 @@ +--- +title: 발전된 애니메이션 +slug: Web/HTML/Canvas/Tutorial/Advanced_animations +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 id="canvas" width="600" height="300"></canvas>
+
+ +

언제나처럼, 우리는 context를 먼저 그려야 한다. 공을 그리기 위해 우리는 캔버스에 그림을 그리기 위한 프로퍼티와 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();
+ +

특이할 건 없다. 이공은 사실상 간단한 원이고 그리는 방법은 다음{{domxref("CanvasRenderingContext2D.arc()", "arc()")}} 메소드에서 참고할 수 있다.

+ +

속도 추가하기

+ +

우리한테는 이제 공이 있다. 이제 이 튜토리얼 마지막 챕터에서 배웠던 것과 같은 기본 애니메이션을 추가할 준비가 되었다. 다시 한 번, 애니메이션 컨트롤은 {{domxref("window.requestAnimationFrame()")}}가 도와주 것이다. 공은 위치에 속도 벡터를 추가하여 움직일 수 있게 된다.  각각의 프레임에, 우리는{{domxref("CanvasRenderingContext2D.clearRect", "clear", "", 1)}}를 캔버스에 주어 오래된 원을 이전 프래임에서 지운다.

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

경계

+ +

경게 충돌 테스트의 필요 없이 우리가 만든 공은 캔버스 밖으로 빠르게 빠져나갈 것입니다. 우리는 공의 xy 위치가 캔버스 차원을 빠져나갔는지 체크해서 방향과 속도를 바꿔주어야 합니다. 그러기 위해서 우리는 draw 메소드에 다음 확인사항을 추가할 것입니다.:

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

First demo

+ +

이제 동작을 확인해 봅시다. 시작하려먼 마우스를 캔버스 안으로 움직여 주세요.

+ + + +

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

+ +

가속

+ +

움직임을 좀 더 리얼하게 만들기 위해, 우리는 속도를 다음과 같이 줄 겁니다. 예를들어:

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

이것은 각 프레임의 세로 속도를 줄여주어, 공이 결국 바닥에서 튀게 만듭니다.

+ + + +

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

+ +

후행 효과

+ +

지금까지 우리는 {{domxref("CanvasRenderingContext2D.clearRect", "clearRect")}}메소드를 사용해서 이전 프레임을 지웠다. 만약 당신이 {{domxref("CanvasRenderingContext2D.fillRect", "fillRect")}}르 사용하여 약간 투명도를 준다면, 쉽게 후행 효과(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")}}

+ +

Breakout

+ +

이 짧은 챕터는 발전된 애니메이션을 만들기 위한 조금의 기술을 설명했다. 여기에 더 많은 것들이 있다! 노나 벽돌을 추가해서 이 튜토리얼을  Breakout 으로 발전시키는 건 어떨까?  Game development에서 게임에 관련된 글들을 찾아보자.

+ +

더보기

+ + + +

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

diff --git a/files/ko/web/html/canvas/tutorial/applying_styles_and_colors/index.html b/files/ko/web/html/canvas/tutorial/applying_styles_and_colors/index.html new file mode 100644 index 0000000000..df094acb71 --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/applying_styles_and_colors/index.html @@ -0,0 +1,732 @@ +--- +title: 스타일과 색 적용하기 +slug: Web/HTML/Canvas/Tutorial/Applying_styles_and_colors +tags: + - HTML5 + - 그래픽 + - 캔버스 +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")}}
+ +
+

도형 그리기 장에서는 기본 선과 채우기 스타일만 사용했습니다. 여기서 우리는 그리기를 조금 더 매력적으로 만들 수있는 캔버스 옵션을 살펴볼 것입니다. 그리기에 다른 색상, 선 스타일, 그라디언트, 패턴 및 그림자를 추가하는 방법을 배우게됩니다.

+
+ +

색상

+ +

지금까지는 그리기 메소드만 살펴봤습니다. 도형에 색을 적용하고자 하면, fillStyle과  strokeStyle 두 가지 중요한 속성을 사용할 수 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.fillStyle", "fillStyle = color")}}
+
도형을 채우는 색을 설정합니다.
+
{{domxref("CanvasRenderingContext2D.strokeStyle", "strokeStyle = color")}}
+
도형의 윤곽선 색을 설정합니다.
+
+ +

여기서의 color는 CSS의 {{cssxref("<color>")}}, 그라디언트 객체, 패턴 객체를 뜻합니다. 그라디언트 객체와 패턴 객체는 페이지 아래에서 설명합니다. 윤곽선과 채움 색의 초기 설정값은 검은색입니다. (CSS 색상 값 #000000)

+ +
+

참고: strokeStyle 또는 fillStyle 속성을 설정하면, 새로 설정된 값이 앞으로 그려질 도형의 기본 값이 됩니다. 각 도형에 다른 색을 적용하려면 fillStyle 또는 strokeStyle 속성을 다시 적용해야 합니다.

+
+ +

색의 올바른 값은 CSS3 사양에 나오는 {{cssxref("<color>")}} 값입니다. 아래에 나오는 색은 모두 한가지 색을 다르게 표현한 것입니다.

+ +
// fillStyle에 적용되는 색은 모두 '오렌지'
+
+ctx.fillStyle = "orange";
+ctx.fillStyle = "#FFA500";
+ctx.fillStyle = "rgb(255, 165, 0)";
+ctx.fillStyle = "rgba(255, 165, 0, 1)";
+
+ +

fillStyle 예제

+ +

이 예제에서 for 반복문을 두 번 사용하여 사각형 격자를 그릴 것입니다. 결과는 스크린샷과 같을 것입니다. 결과가 그리 대단한 것은 아닙니다. 각 사각형의 RGB 색상값에서 붉은색과 녹색 값만을 변수 ij를 사용하여 변경합니다. 파란색 채널은 고정된 값입니다. 채널 값들을 변경함으로써, 모든 종류의 팔레트를 생성할 수 있습니다. 단계를 늘리면 Photoshop에서 사용하는 색상 팔레트와 비슷한 모양을 얻을 수 있습니다.

+ +
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 예제

+ +

이번 예제는 위에 나온 예제와 비슷하지만, strokeStyle 속성을 사용하여 윤곽선의 색을 바꿉니다. 사각형 대신, 원을 그리는 arc() 메소드를 사용합니다.

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

결과는 아래와 같습니다.

+ +

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

+ +

투명도

+ +

캔버스에는 불투명한 도형을 그릴 수도 있고, 반투명한 도형도 그릴 수도 있습니다. globalAlpha 값을 설정하거나 윤곽선 또는 채움 스타일에 반투명 색을 적용하면 됩니다.

+ +
+
{{domxref("CanvasRenderingContext2D.globalAlpha", "globalAlpha = transparencyValue")}}
+
투명도 값이 설정되면 이후 캔버스에 그려지는 모든 도형들의 투명도가 바뀝니다. 설정하는 값은 0.0(완전히 투명)과 1.0(완전히 불투명) 사이에 있어야 하며, 초기 설정값은 1.0(완전히 투명)입니다.
+
+ +

globalAlpha는 모두 같은 투명도로 캔버스에 많은 도형을 그릴 때 유용합니다. 하지만, 보통은 각각의 도형마다 투명도를 설정하는 것이 더 유용할 것입니다.

+ +

strokeStylefillStyle 값에 CSS rgba 색상값을 적용할 수 있으므로, 투명한 색을 적용하려면 아래와 같은 표기법을 사용할 수 있습니다.

+ +
// 외곽선과 채움 스타일에 투명 적용
+
+ctx.strokeStyle = 'rgba(255, 0, 0, 0.5)';
+ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
+
+ +

rgba() 함수는 rgb() 함수와 비슷하지만, 인자가 하나 더 있습니다. 마지막 인자는 투명도 값을 설정하는 인자입니다. 올바른 범위는 0.0(완전히 투명)에서 1.0(완전히 불투명)입니다.

+ +

globalAlpha 예제

+ +

이 예제에서, 네 가지 다른 색을 가진 사각형을 배경에 그릴 것입니다. 그 위에, 반투명한 원을 여러 개 그릴 것입니다. globalAlpha 값을 0.2로 설정하면 이후 그려질 도형은 이 값을 사용합니다. for 반복문을 사용하여 점점 큰 반지름의 원을 그립니다. 최종 결과물은 원형 그레이디언트가 됩니다. 원이 겹쳐지면서 점점 불투명해지는 것을 볼 수 있으며, 최종적으로 한 가운데에 있는 원에서는 뒷 배경이 거의 보이지 않게 됩니다.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  // 배경을 그린다
+  ctx.fillStyle = '#FD0';
+  ctx.fillRect(0, 0, 75, 75);
+  ctx.fillStyle = '#6C0';
+  ctx.fillRect(75, 0, 75, 75);
+  ctx.fillStyle = '#09F';
+  ctx.fillRect(0, 75, 75, 75);
+  ctx.fillStyle = '#F30';
+  ctx.fillRect(75, 75, 75, 75);
+  ctx.fillStyle = '#FFF';
+
+  // 투명값을 설정한다
+  ctx.globalAlpha = 0.2;
+
+  // 반투명한 원을 그린다
+  for (var i = 0; i < 7; i++){
+    ctx.beginPath();
+    ctx.arc(75, 75, 10 + 10 * i, 0, Math.PI * 2, true);
+    ctx.fill();
+  }
+}
+ + + +

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

+ +

rgba()를 사용한 예제

+ +

두번째 예제에서는 위의 예제와 비슷한 일을 하지만, 겹쳐진 원을 그리는 대신, 불투명도가 증가하는 작은 사각형을 그릴 것입니다. 각각의 도형마다 윤곽선이나 채움 스타일을 따로따로 설정할 수 있기 때문에, rgba()를 사용할 때는 조금 더 제어가 쉽고 융통성도 있습니다.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 배경을 그린다
+  ctx.fillStyle = 'rgb(255,221,0)';
+  ctx.fillRect(0,0,150,37.5);
+  ctx.fillStyle = 'rgb(102,204,0)';
+  ctx.fillRect(0,37.5,150,37.5);
+  ctx.fillStyle = 'rgb(0,153,255)';
+  ctx.fillRect(0,75,150,37.5);
+  ctx.fillStyle = 'rgb(255,51,0)';
+  ctx.fillRect(0,112.5,150,37.5);
+
+  // 반투명한 사각형을 그린다
+  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")}}

+ +

선 모양

+ +

선의 스타일을 바꾸는 방법이 몇가지 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.lineWidth", "lineWidth = value")}}
+
이후 그려질 선의 두께를 설정합니다.
+
{{domxref("CanvasRenderingContext2D.lineCap", "lineCap = type")}}
+
선의 끝 모양을 설정합니다.
+
{{domxref("CanvasRenderingContext2D.lineJoin", "lineJoin = type")}}
+
선들이 만나는 "모서리"의 모양을 설정합니다.
+
{{domxref("CanvasRenderingContext2D.miterLimit", "miterLimit = value")}}
+
두 선이 예각으로 만날 때 접합점의 두께를 제어할 수 있도록, 연결부위의 크기를 제한하는 값을 설정합니다.
+
{{domxref("CanvasRenderingContext2D.getLineDash", "getLineDash()")}}
+
음수가 아닌 짝수를 포함하는 현재 선의 대시 패턴 배열을 반환합니다.
+
{{domxref("CanvasRenderingContext2D.setLineDash", "setLineDash(segments)")}}
+
현재 선의 대시 패턴을 설정합니다.
+
{{domxref("CanvasRenderingContext2D.lineDashOffset", "lineDashOffset = value")}}
+
선의 대시 배열이 어디서 시작될지 지정합니다.
+
+ +

아래 예제들을 보면 어떻게 동작하는지 이해할 수 있을 것입니다.

+ +

lineWidth 예제

+ +

현재 선의 두께를 설정합니다. 설정값은 반드시 양수이어야 하며, 초기 설정값은 1.0 단위입니다.

+ +

선의 두께는 지정된 경로의 가운데에 있는 획의 두께입니다. 이 말의 뜻은, 경로의 좌우로, 설정된 두께 반 만큼의 폭 영역이 그려진다는 것입니다. 캔버스 좌표는 픽셀을 직접 참조하지 않으므로, 선명한 수평 및 수직선을 얻기 위해 특별히 주의를 기울여야 합니다.

+ +

아래에 나오는 예제에서는, 선의 두께가 점점 증가하는 10개의 직선이 그려집니다. 가장 왼쪽의 선은 1.0 단위 폭입니다. 그러나, 경로의 위치 때문에 가장 왼쪽과 다른 모든 홀수 폭 두께 선은 선명하게 보이지 않습니다.

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

+ +

선명한 선을 얻으려면 경로에 획을 어떻게 그려지는지 이해해야 합니다. 아래의 이미지를 보면, 격자는 캔버스의 좌표 격자를 나타냅니다. 격자선 사이에 있는 사각형은 실제 픽셀과 딱 맞아 떨어집니다. 아래에 있는 첫번째 이미지를 보면, (2,1)에서 (5,5)로 사각형이 채워져 있습니다. 사각형의 전체 영역(연한 붉은 색)은 픽셀 경계선 사이에 딱 맞아 떨어지기 때문에 채워진 사각형은 선명한 가장자리를 갖습니다.

+ +

+ +

만일 (3,1)에서 (3,5)로 그리는 직선의 두께가 1.0이라면, 두번째 이미지와 같은 상황이 됩니다. 채워진 실제 영역 (진한 파란색)은 패스의 양쪽에있는 픽셀의 절반까지만 확장됩니다. 이것은 1 픽셀을 채우는 것이 아니므로 근사값으로 화면에 그려지게 됩니다. 그래서 양옆의 영역(연한 파란색과 짙은 파란 색)으로, 실제 설정한 색과는 다른 흐릿한 색으로 채워지는 것입니다. 이전 예제에서 보듯이 선 두께가 1.0인 선에서 일어난 일입니다.

+ +

이렇게 되는 것을 막으려면, 경로를 아주 정밀하게 생성해야 합니다. 선의 두께가 1.0이면 경로의 양쪽으로 0.5 단위만큼이라는 것을 알고 있으니, (3.5,1)에서 (3.5,5)로 그리는 경로를 생성하는 세번째 이미지의 결과는 완벽히 정밀하게 1 픽셀 두께의 수직선이 됩니다.

+ +
+

참고: 위에 나온 수직선 그리기 예제를 살펴보면, Y 위치는 정수로 된 격자선 위치를 참조하고 있습니다. 그렇지 않았다면, 끝점에서 픽셀의 반을 차지한 상태로 보였을 것입니다. (초기값이 buttlineCap 스타일의 설정값에 따라 다르게 보입니다. 홀수 두께 선들의 좌표를 0.5 픽셀씩 조정하여 다시 계산하고 싶을지도 모릅니다. lineCap 스타일을 square로 설정함으로써, 끝점에서 선의 외곽 경계선은 픽셀에 딱 맞게 자동적으로 확장될 것입니다.)

+ +

경로의 시작 지점과 종료 지점의 끝점만이 영향을 받는다는 것에 주목하세요. 만약 closePath()로 경로가 닫힌다면, 시작 지점과 종료 지점은 없는 것입니다. 그 대신, 경로 안에 있는 모든 끝점들은, 초기 설정값이 miterlineJoin 스타일의 설정값을 사용하여 이전 부분 및 다음 부분과 이어지는데, 교차되는 점들로 이어진 부분들의 외곽 경계선을 자동적으로 확장하는 효과가 생깁니다. 그렇기 때문에 만약 이들 이어진 부분들이 수직 또는 수평이라면, 그려지는 선들은 각 끝점의 중심에 놓인 픽셀을 가득 채우게 될 것입니다. 이들 선 스타일에 대한 예제는 아래에 나옵니다.

+
+ +

짝수 두께의 선들은 반으로 나누어도 각각의 반은 정수의 양만큼이기 때문에 픽셀을 조정할 필요가 없습니다.

+ +

비트맵이 아닌 벡터 2D 그래픽으로 작업할 때, 작업을 시작할 때는 약간 힘들겠지만, 격자와 경로의 위치에 주의를 기울인다면, 크기를 키우거나 줄이거나 또는 어떠한 변형을 하더라도 그리려는 이미지는 똑바로 보일 것입니다. 1.0 두께의 수직선은 2배로 크기를 키웠을 때, 정확히 2 픽셀 두께의 선이 되며, 올바른 위치에 나타날 것입니다.

+ +

lineCap 예제

+ +

lineCap 속성은 그리려는 모든 선의 끝점 모양을 결정합니다. butt, round, square라는 세 가지 값을 가지며, 초기 설정값은 butt입니다.

+ +

+ +
+
butt
+
선의 끝이 좌표에 딱맞게 잘립니다.
+
round
+
선의 끝이 동그랗습니다.
+
square
+
선 끝에, 선 두께 반만큼의 사각형 영역이 더해집니다.
+
+ +

이 예제에서는, 각기 다른 lineCap 속성 값을 가진 선 세개가 그려집니다. 또한 각 선들의 차이점을 정확히 보이기 위한 안내선이 추가로 그려집니다. 세개의 선 모두, 이 안내선 위에 시작과 종료 좌표가 있습니다.

+ +

맨 왼쪽에 있는 선은 초기 설정값인 butt을 사용합니다. 안내선에 딱 맞게 선이 시작되고 끝이 납니다. 가운데에 있는 선은 round를 사용합니다. 선 두께의 반을 반지름으로 하는 반원이 끝에 붙습니다. 맨 오른쪽에 있는 선은 square를 사용합니다. 선 두께 만큼의 너비와 선 두께 반 만큼의 높이를 가진 네모 상자가 끝에 붙습니다.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  var lineCap = ['butt','round','square'];
+
+  // 안내선을 그린다
+  ctx.strokeStyle = '#09f';
+  ctx.beginPath();
+  ctx.moveTo(10, 10);
+  ctx.lineTo(140, 10);
+  ctx.moveTo(10, 140);
+  ctx.lineTo(140, 140);
+  ctx.stroke();
+
+  // 선을 그린다
+  ctx.strokeStyle = 'black';
+  for (var i=0;i<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")}}

+ +

lineJoin 예제

+ +

lineJoin 속성은, 도형을 이루는 선이나 호나 곡선들이 연결되는 지점의 모양을 결정합니다. 끝점과 제어점이 정확히 같은 위치인, 길이가 0인 부분들은 제외된다.

+ +

이 속성에는 세 가지 값이 있는데, round, bevel, miter이며, 초기 설정값은 miter입니다. 두 부분들이 같은 방향으로 연결되어 있는 경우에는, lineJoin을 설정해도 아무런 효과가 나타나지 않습니다.

+ +

+ +
+
round
+
도형의 모서리를, 연결되는 부분들의 공통 끝점을 중심으로 하는 원 모양으로 만듭니다. 이때 원의 반지름은 선의 두께와 같습니다.
+
bevel
+
도형의 모서리를, 연결되는 부분들의 공통 끝점에서 세모 모양으로 만듭니다.
+
miter
+
도형의 모서리를, 두 부분의 바깥쪽 테두리 선을 각각 연장하여 교차된 점으로 생긴 마름모꼴 모양으로 만듭니다. miterLimit 속성값에 따라 모양이 달라집니다.
+
+ +

아래 예제에서 세 개의 경로를 그릴 것입니다. 세 경로는 각각 다른 lineJoin 속성값을 가집니다.

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

+ +

miterLimit 속성 예제

+ +

위의 예제에서 볼 수 있듯이, 속성값을 miter로 하여 두 선이 연결되면, 연결되는 두 선의 바깥쪽 테두리는 연장선이 만나는 지점까지 확장됩니다. 연결된 두 선이 이루는 각도가 크면, 확장되는 영역이 크지 않지만, 각도가 작아짐(끝이 뾰족해짐)에 따라서 이 영역이 기하급수적으로 커질 수도 있습니다.

+ +

miterLimit 속성은 끝점이 만나는 지점과 테두리 연장선이 만나는 지점이 얼마나 떨어져 있을지를 결정합니다. 두 선이 이 값을 넘게 되면, lineJoin 속성의 bevel 값 모양이 적용됩니다. miterLimit 속성값(HTML {{HTMLElement("canvas")}}에서, 초기 설정값은 10.0)에 의해, 현재 좌표 방식 안에서, 선의 두께에 따라, 어느 정도까지 뾰족해질 수 있는지가 계산됩니다. 그래서 miterLimit은 현재 디스플레이 비율이나 경로의 변형 같은 것으로 각각 설정될 수 있습니다. 그렇게 하여 선의 모서리에만 영향을 줍니다.

+ +

더 자세히 얘기하자면, 뾰족함 제한(miter limit)은, 선 두께의 반과 확장되는 길이(HTML 캔버스에서, 선이 연결되는 바깥쪽 끝부분과, 경로에서 연결되는 두 부분의 공통 끝점 사이로 측정합니다.)의 최대 허용 비율입니다. 이것은 두 부분의 외곽선이 만나는 안쪽 점과 바깥쪽 점 사이 거리와, 선 두께의 최대 허용 비율과 같습니다. miter 값 모양이 아닌 bevel 값 모양으로 연결되는 지점의 최소 안쪽 각 반 만큼의 값과 같은 것입니다.

+ + + +

다음 예제에서는 miterLimit 값을 바꾸고 그 결과가 어떤지 바로 확인할 수 있습니다. 파란색 선은 지그재그 무늬 안에서 선들의 시작 지점과 종료 지점을 나타냅니다.

+ +

이 예제에서 miterLimit 값을 4.2보다 낮게 설정하면, 모든 연결 지점은 bevel 값 모양이 되어 파란색 선에 붙을 것입니다. miterLimit 값이 10보다 높다면, 거의 모든 연결 지점들이 파란색 선 바깥쪽에 있을 것입니다. 왼쪽으로 갈수록 파란색 선에서 더 많이 튀어나오는데, 왼쪽으로 갈수록 연결되는 각이 더 작아지기 때문입니다. 값을 5로 설정하면, 반은 bevel 값 모양으로, 반은 miter 값 모양이 됩니다.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 캔버스를 비운다
+  ctx.clearRect(0,0,150,150);
+
+  // 안내선을 그린다
+  ctx.strokeStyle = '#09f';
+  ctx.lineWidth   = 2;
+  ctx.strokeRect(-5,50,160,50);
+
+  // 선 스타일을 설정한다
+  ctx.strokeStyle = '#000';
+  ctx.lineWidth = 10;
+
+  // 입력 값을 검사한다
+  if (document.getElementById('miterLimit').value.match(/\d+(\.\d+)?/)) {
+    ctx.miterLimit = parseFloat(document.getElementById('miterLimit').value);
+  } else {
+    alert('Value must be a positive number');
+  }
+
+  // 선을 그린다
+  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")}}

+ +

 

+ +

대시라인 사용하기

+ +

setLineDash 메소드와 lineDashOffset 속성은 선의 대시 패턴을 지정합니다.  setLineDash 메소드는 거리를 지정하는 숫자 목록을 받아 선과 틈을 교대로 그리며 lineDashOffset 속성은 패턴을 시작할 위치를 오프셋으로 설정합니다.

+ +

이 예제에서 우리는 행진하는 개미 효과를 만들고 있습니다. 컴퓨터 그래픽 프로그램의 선택 도구에서 흔히 볼 수있는 애니메이션 기술입니다. 테두리를 애니메이션화하여 사용자가 선택 테두리와 이미지 배경을 구별하는 데 도움이됩니다. 이 튜토리얼의 뒷부분에서 이 작업 및 다른 기본 애니메이션을 수행하는 방법을 배울 수 있습니다.

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

+ +

그라디언트(Gradient)

+ +

다른 그래픽 프로그램들과 마찬가지로, 선형 및 원형의 그레이디언트를 사용할 수 있습니다. 다음 메소드 중 하나를 사용하여 {{domxref("CanvasGradient")}} 객체를 생성합니다. 그런 다음 이 객체를 fillStyle 또는 strokeStyle 속성에 할당 할 수 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.createLinearGradient", "createLinearGradient(x1, y1, x2, y2)")}}
+
시작점 좌표를 (x1, y1)로 하고, 종료점 좌표를 (x2, y2)로 하는 선형 그라디언트 오브젝트를 생성합니다.
+
{{domxref("CanvasRenderingContext2D.createRadialGradient", "createRadialGradient(x1, y1, r1, x2, y2, r2)")}}
+
반지름이 r1이고 좌표 (x1, y1)을 중심으로 하는 원과, 반지름이 r2이고 좌표 (x2, y2)를 중심으로 하는 원을 사용하여 그라디언트가 생성됩니다.
+
+ +

예를 들면 다음과 같습니다.

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

CanvasGradient 객체를 만들었다면, addColorStop() 메소드를 사용하여, 오브젝트에 색을 적용할 수 있습니다.

+ +
+
{{domxref("CanvasGradient.addColorStop", "gradient.addColorStop(position, color)")}}
+
gradient 오브젝트에 새로운 색 중단점(color stop)을 생성합니다. position은 0.0에서 1.0 사이의 숫자이고 그라디언트에서 색상의 상대적인 위치를 정의합니다. color 인자는 CSS {{cssxref("<color>")}}를 나타내는 문자열이어야하고, 그라디언트가 (전환효과로) 진행되면서 도달한 지점의 색상을 의미합니다.
+
+ +

색 중단점은 원하는 만큼 마음대로 추가할 수 있습니다. 흰 색에서 검은 색으로 변하는 선형 그레이디언트를 만들려면 아래와 같이 합니다.

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

createLinearGradient 예제

+ +

이 예제에서 그레이디언트 두 개를 만들 것입니다. 예제에서 볼 수 있듯이, strokeStylefillStyle 속성 모두 canvasGradient 오브젝트를 속성 값으로 가질 수 있습니다.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 그레이디언트를 생성한다
+  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)');
+
+  // 외곽선과 채움 스타일에 그레이디언트를 적용한다
+  ctx.fillStyle = lingrad;
+  ctx.strokeStyle = lingrad2;
+
+  // 도형을 그린다
+  ctx.fillRect(10, 10, 130, 130);
+  ctx.strokeRect(50, 50, 50, 50);
+
+}
+
+ + + +

첫번째 그라디언트는 배경 그라디언트입니다. 보시다시피 같은 위치에 두 가지 색상을 지정했습니다. 매우 선명한 색상 전환을 만들기 위해 이 작업을 수행합니다(이 경우 흰색에서 녹색으로). 일반적으로 색상 중단점을 정의하는 순서는 중요하지 않지만, 이 특별한 경우에는 의미가 있습니다.

+ +

두 번째 그래디언트에서는 시작 색상 (위치 0.0)을 지정하지 않았는데, 자동으로 다음 색상 중단점의 색상으로 가정하기 때문에 반드시 필요하지는 않기 때문입니다. 따라서 위치 0.5에 검은색을 지정하면 시작부터 중단점까지 자동으로 검정색 그라이언트를 만듭니다.

+ +

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

+ +

createRadialGradient 예제

+ +

이 예제에서는 원형 그레이디언트를 4개 만들 것입니다. 포토샵같은 프로그램에서 원형 그레이디언트를 만들 때는 하나의 점을 중심으로 그레이디언트를 만드는데, 캔버스의 원형 그레이디언트에서는 시작과 종료 지점 두군데를 제어할 수 있기 때문에, 기존의 프로그램에서 볼 수 있는 원형 그레이디언트보다는 더 복잡한 효과를 만들어 낼 수 있습니다.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 그라디언트를 생성한다
+  var radgrad = ctx.createRadialGradient(45,45,10,52,50,30);
+  radgrad.addColorStop(0, '#A7D30C');
+  radgrad.addColorStop(0.9, '#019F62');
+  radgrad.addColorStop(1, 'rgba(1,159,98,0)');
+
+  var radgrad2 = ctx.createRadialGradient(105,105,20,112,120,50);
+  radgrad2.addColorStop(0, '#FF5F98');
+  radgrad2.addColorStop(0.75, '#FF0188');
+  radgrad2.addColorStop(1, 'rgba(255,1,136,0)');
+
+  var radgrad3 = ctx.createRadialGradient(95,15,15,102,20,40);
+  radgrad3.addColorStop(0, '#00C9FF');
+  radgrad3.addColorStop(0.8, '#00B5E2');
+  radgrad3.addColorStop(1, 'rgba(0,201,255,0)');
+
+  var radgrad4 = ctx.createRadialGradient(0,150,50,0,140,90);
+  radgrad4.addColorStop(0, '#F4F201');
+  radgrad4.addColorStop(0.8, '#E4C700');
+  radgrad4.addColorStop(1, 'rgba(228,199,0,0)');
+
+  // 도형을 그린다
+  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);
+}
+
+ + + +

이 예제에서는 원형 그레이디언트에 사용되는 두 원의 중심을 달리하여 입체적인 공처럼 보이게 했습니다. 안쪽 원과 바깥쪽 원은 겹치지 않게 하는 것이 좋습니다. 왜냐하면 예상하기 힘든 이상한 결과가 나타날 수 있기 때문입니다.

+ +

그레이디언트의 마지막 색 적용 지점에서는 투명도를 적용하였습니다. 투명도가 적용된 지점에서 이전 지점까지의 색 변화를 보기 좋게 만들려면, 두 지점에 똑같은 색을 적용하면 되는데, 이 예제에서는 색의 값을 다른 방식으로 입력하여 헷갈릴 수도 있습니다. 첫번째 그레이디언트에 사용된 #019F62rgba(1,159,98,1)은 같은 색입니다.

+ +

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

+ +

패턴(Patterns)

+ +

이전 페이지의 예제 중 하나에서 일련의 루프를 사용하여 이미지 패턴을 만들었습니다. 그러나 훨씬 간단한 메소드 인 createPattern () 메소드가 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.createPattern", "createPattern(image, type)")}}
+
새 캔버스 패턴 객체를 만들어 반환합니다. image는 {{domxref("CanvasImageSource")}}(즉, {{domxref("HTMLImageElement")}}, 다른 캔버스, {{HTMLElement("video")}} 요소 등등)입니다. type은 이미지 사용 방법을 나타내는 문자열입니다.
+
+ +

type은 패턴을 만들기 위해 이미지를 사용하는 방법을 지정하며, 다음 문자열 값 중 하나 여야합니다.

+ +
+
repeat
+
수직 및 수평 방향으로 이미지를 이어 붙입니다.
+
repeat-x
+
수평 방향으로만 이미지를 이어 붙입니다.
+
repeat-y
+
수직 방향으로만 이미지를 이어 붙입니다.
+
no-repeat
+
이미지를 이어 붙이지 않습니다. 이미지는 한번만 사용됩니다.
+
+ +

이 메소드를 사용하여 위에서 본 그라디언트 메소드와 매우 유사한 {{domxref ( "CanvasPattern")}} 객체를 생성합니다. 패턴을 생성하면 fillStyle 또는 strokeStyle 속성에 패턴을 할당 할 수 있습니다. 예를 들면 다음과 같습니다.

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

참고: drawImage () 메서드와 마찬가지로 이 메소드를 호출하기 전에 이미지가 로드되었는지 확인해야합니다. 그렇지 않으면 패턴이 잘못 그려 질 수 있습니다.

+
+ +

createPattern 예제

+ +

이 마지막 예제에서, fillStyle 속성에 적용할 패턴을 만들 것입니다. 한 가지 눈여겨 볼 것은, 이미지 onload 핸들러 사용한다는 것입니다. 이미지를 패턴에 적용하기 전에 불러오기가 완료되었는지 확인하는 것입니다.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 패턴으로 사용할 이미지 오브젝트를 생성한다
+  var img = new Image();
+  img.src = 'https://mdn.mozillademos.org/files/222/Canvas_createpattern.png';
+  img.onload = function() {
+
+    // 패턴을 생성한다
+    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")}}

+ +

그림자

+ +

그림자 사용에는 네 개의 속성이 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.shadowOffsetX", "shadowOffsetX = float")}}
+
그림자가 객체에서 연장되어야하는 수평 거리를 나타냅니다. 이 값은 변환 행렬의 영향을 받지 않습니다. 기본값은 0입니다.
+
{{domxref("CanvasRenderingContext2D.shadowOffsetY", "shadowOffsetY = float")}}
+
그림자가 객체에서 연장되어야하는 수직 거리를 나타냅니다. 이 값은 변환 행렬의 영향을 받지 않습니다. 기본값은 0입니다.
+
{{domxref("CanvasRenderingContext2D.shadowBlur", "shadowBlur = float")}}
+
흐림(blur) 효과의 크기를 나타냅니다. 이 값은 픽셀 수와 일치하지 않으며 현재 변환 행렬의 영향을 받지 않습니다. 기본값은 0입니다.
+
{{domxref("CanvasRenderingContext2D.shadowColor", "shadowColor = color")}}
+
그림자 효과의 색상을 나타내는 표준 CSS 색상 값. 기본적으로 완전 검은색입니다.
+
+ +

shadowOffsetXshadowOffsetY 속성은 그림자가 X 및 Y 방향으로 객체에서 얼마나 멀리 떨어져야하는지 나타냅니다. 이 값은 현재 변환 행렬의 영향을받지 않습니다. 음수값을 사용하면 그림자가 위로 또는 왼쪽으로 확장되고 양수값을 사용하면 그림자가 아래로 또는 오른쪽으로 확장됩니다. 기본값은 모두 0입니다.

+ +

shadowBlur 속성은 흐림 효과의 크기를 나타냅니다. 이 값은 픽셀 수와 일치하지 않으며 현재 변환 행렬의 영향을받지 않습니다. 기본값은 0입니다.

+ +

shadowColor 속성은 그림자 효과의 색상을 나타내는 표준 CSS 색상 값입니다. 기본값은 완전 검은색입니다.

+ +
+

알아둘 것: 음영은 source-over 합성 작업에만 사용됩니다.

+
+ +

그림자 있는 글자 예제

+ +

이 예제에서는 그림자가 있는 글자를 그립니다.

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

+ +

다음 장에서 텍스트 그리기에 대한 font 속성과 fillText 메소드를 살펴 보겠습니다.

+ +

캔버스 채우기 규칙

+ +

fill (혹은 {{domxref("CanvasRenderingContext2D.clip", "clip")}} 및 {{domxref("CanvasRenderingContext2D.isPointInPath", "isPointinPath")}})을 사용할 때 한 점이 경로 안쪽 또는 바깥에 있는지 그리고 따라서 채워지는지 여부를 결정하기 위한 채우기 규칙 알고리즘을 선택적으로 제공 할 수 있습니다. 경로가 교차하거나 중첩 된 경우에 유용합니다.
+
+ 다음 두가지 값을 사용할 수 있습니다:

+ + + +

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/ko/web/html/canvas/tutorial/basic_animations/index.html b/files/ko/web/html/canvas/tutorial/basic_animations/index.html new file mode 100644 index 0000000000..457d658172 --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/basic_animations/index.html @@ -0,0 +1,310 @@ +--- +title: 기본 애니메이션 +slug: Web/HTML/Canvas/Tutorial/Basic_animations +tags: + - HTML5 + - 그래픽 + - 캔버스 +translation_of: Web/API/Canvas_API/Tutorial/Basic_animations +--- +

{{HTMLElement("canvas")}} 요소는 자바스크립트로 제어하는 것이므로, 애니메이션도 쉽게 만들 수 있습니다. 복잡한 애니메이션을 만드는 것은 추가 작업이 더 필요하고, 앞으로 그에 대한 페이지도 머지 않아 추가되기를 기대합니다.

+

도형은 한번 만들어 놓으면 그 모습 그대로 있다는 것이 애니메이션을 만들 때의 가장 큰 제약일 것입니다. 그 도형을 움직이고자 하면 그 도형뿐만이 아니라 그 도형이 그려지기 전에 그려진 모든 것을 다시 그려야 합니다. 복잡한 장면을 다시 그리는 것은 시간도 많이 걸리며, 코드를 실행하는 컴퓨터의 능력에 따라 달라집니다.

+

기본 애니메이션 단계

+

한 장면을 그리려면 아래와 같은 단계를 밟습니다.

+
    +
  1. 캔버스를 비웁니다.
    + 그리려는 도형이 (배경 이미지를 만들 때처럼) 캔버스를 가득 채우는 것이 아니라면, 이전에 그려진 모든 도형을 지울 필요가 있습니다. 가장 쉬운 방법은 clearRect() 메소드를 사용하는 것입니다.
  2. +
  3. 캔버스 상태를 저장합니다.
    + 캔버스 상태에 영향을 주는 (스타일 변경, 모양 변형 등의) 설정값을 바꾸려고 하고, 바뀐 값을 각 장면마다 사용하려고 한다면, 원래 상태를 저장할 필요가 있습니다.
  4. +
  5. 애니메이션할 도형을 그립니다.
    + 실제 장면을 그리는 단계입니다.
  6. +
  7. 캔버스 상태를 복원합니다.
    + 새로운 장면을 그리기 전에 저장된 상태를 복원합니다.
  8. +
+

애니메이션 제어하기

+

캔버스 메소드를 사용하거나 사용자 함수를 사용하여 캔버스에 도형들을 그립니다. 보통의 경우에서는, 코드 실행이 완료되면 캔버스에 나타나는 결과만을 보게 됩니다. 예를 들어,  for 반복문 안에서 애니메이션을 실행하는 것은 불가능합니다.

+

그래서 정해진 시간마다 그리기 함수를 실행하는 방법이 필요한 것입니다. 아래와 같이 애니메이션을 제어하는 두 가지 방법이 있습니다.

+

예정된 변경

+

정해진 시간마다 특정 함수를 부를 때 사용할 수 있는  {{domxref("window.setInterval()")}}과 {{domxref("window.setTimeout()")}} 함수가 있습니다.

+
+

알아둘 것: 현재는 애니메이션을 만드는 방법으로  {{domxref("window.requestAnimationFrame()")}} 메소드를 추천합니다. 이에 대한 튜토리얼은 곧 업데이트할 것입니다.

+
+
+
+ setInterval(function, delay)
+
+ delay 밀리세컨드(1,000분의 1초)마다 function 함수 반복 실행을 시작합니다.
+
+ setTimeout(function, delay)
+
+ delay 밀리세컨드(1,000분의 1초) 경과후, function 함수를 실행합니다.
+
+

사용자의 제어를  필요로 하지 않는 반복 실행에는  setInterval() 함수가 알맞을 것입니다.

+

사용자 상호 작용 변경

+

애니메이션을 제어하는 두번째 방법은 사용자 입력입니다. 게임을 만들려고 한다면, 애니메이션을 제어하기 위해 키보드나 마우스 이벤트를 사용할 수 있을 것입니다.  {{domxref("EventListener")}}를 설정하여, 사용자와 상호 작용하여 애니메이션 함수를 실행합니다.

+

사용자 상호 작용이 필요하다면, 우리가 만든 애니메이션용 프레임웍(framework)최소 기능 버전 또는 최대 기능 버전을 사용할 수 있을 것입니다.

+
var myAnimation = new MiniDaemon(null, animateShape, 500, Infinity);
+

또는

+
var myAnimation = new Daemon(null, animateShape, 500, Infinity);
+

아래 예제에서는, 애니메이션을 제어하기 위해 {{domxref("window.setInterval()")}}을 사용할 것입니다. 페이지 제일 아래쪽에 {{domxref("window.setTimeout()")}}을 사용한 예제 링크도 있습니다.

+

태양계 애니메이션

+

이 예제에서는 달이 지구를 돌고 지구가 태양을 도는 애니메이션을 만듭니다.

+
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';
+  setInterval(draw,100);
+}
+
+function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  ctx.globalCompositeOperation = 'destination-over';
+  ctx.clearRect(0,0,300,300); // 캔버스를 비운다
+
+  ctx.fillStyle = 'rgba(0,0,0,0.4)';
+  ctx.strokeStyle = 'rgba(0,153,255,0.4)';
+  ctx.save();
+  ctx.translate(150,150);
+
+  // 지구
+  var time = new Date();
+  ctx.rotate( ((2*Math.PI)/60)*time.getSeconds() + ((2*Math.PI)/60000)*time.getMilliseconds() );
+  ctx.translate(105,0);
+  ctx.fillRect(0,-12,50,24); // Shadow
+  ctx.drawImage(earth,-12,-12);
+
+  // 달
+  ctx.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); // 지구 궤도
+  ctx.stroke();
+
+  ctx.drawImage(sun,0,0,300,300);
+}
+
+ +

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

+

시계 애니메이션

+

이 예제에서는, 현재 시각을 보여주는 움직이는 시계를 만듭니다.

+
function init(){
+  clock();
+  setInterval(clock,1000);
+}
+
+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";
+
+  // 시계판 - 시
+  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();
+
+  // 시계판 - 분
+  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";
+
+  // 시간 표시 - 시
+  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();
+
+  // 시간 표시 - 분
+  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();
+
+  // 시간 표시 - 초
+  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();
+}
+ +

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

+

움직이는 파노라마 사진

+

이 예제에서는, 움직이는 파노라마 사진을 만듭니다. 사용할 그림은 위키피디어(Wikipedia)에서 구한 요세미티 국립공원입니다. 캔버스보다 큰 그림을 사용할 수도 있습니다.

+
var img = new Image();
+
+// 변수
+// 스크롤될 이미지, 방향, 속도를 바꾸려면 변수값을 바꾼다.
+
+img.src = 'https://mdn.mozillademos.org/files/4553/Capitan_Meadows,_Yosemite_National_Park.jpg';
+var CanvasXSize = 800;
+var CanvasYSize = 200;
+var speed = 30; // 값이 작을 수록 빨라진다
+var scale = 1.05;
+var y = -4.5; // 수직 옵셋
+
+// 주요 프로그램
+
+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) { x = CanvasXSize-imgW; } // 캔버스보다 큰 이미지
+    if (imgW > CanvasXSize) { clearX = imgW; } // 캔버스보다 큰 이미지
+    else { clearX = CanvasXSize; }
+    if (imgH > CanvasYSize) { clearY = imgH; } // 캔버스보다 큰 이미지
+    else { clearY = CanvasYSize; }
+    // 캔버스 요소 얻기
+    ctx = document.getElementById('canvas').getContext('2d');
+    // 새로 그리기 속도 설정
+    return setInterval(draw, speed);
+}
+
+function draw() {
+    // 캔버스를 비운다
+    ctx.clearRect(0,0,clearX,clearY);
+    // 이미지가 캔버스보다 작거나 같다면 (If image is <= Canvas Size)
+    if (imgW <= CanvasXSize) {
+        // 재설정, 처음부터 시작
+        if (x > (CanvasXSize)) { x = 0; }
+        // 추가 이미지 그리기
+        if (x > (CanvasXSize-imgW)) { ctx.drawImage(img,x-CanvasXSize+1,y,imgW,imgH); }
+    }
+    // 이미지가 캔버스보다 크다면 (If image is > Canvas Size)
+    else {
+        // 재설정, 처음부터 시작
+        if (x > (CanvasXSize)) { x = CanvasXSize-imgW; }
+        // 추가 이미지 그리기
+        if (x > (CanvasXSize-imgW)) { ctx.drawImage(img,x-imgW+1,y,imgW,imgH); }
+    }
+    // 이미지 그리기
+    ctx.drawImage(img,x,y,imgW,imgH);
+    // 움직임 정도
+    x += dx;
+}
+
+

예제에 사용된 {{HTMLElement("canvas")}}의 크기는 아래와 같다. 캔버스의 너비가 변수 CanvasXSize값과 같고, 캔버스의 높이는 변수 CanvasYSize값과 같다는 것에 주목하라.

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

Live sample

+

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

+

또 다른 예제들

+
+
+ Gartic
+
+ 다중 사용자 지원 그리기 놀이.
+
+ Canvascape
+
+ 3D 어드벤처 게임 (1인칭 슈팅).
+
+ A basic ray-caster
+
+ 키보드를 사용한 애니메이션 제어 방법에 대한 좋은 예제.
+
+ canvas adventure
+
+ 키보드 제어를 사용하는 또다른 좋은 예제.
+
+ An interactive Blob
+
+ 물방울 갖고 놀기.
+
+ Flying through a starfield
+
+ 별, 동그라미, 네모가 떠다니는 우주를 누벼라.
+
+ iGrapher
+
+ 주식 시장 자료 차트 예제.
+
+

이것도 보세요

+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Compositing", "Web/Guide/HTML/Canvas_tutorial/Optimizing_canvas")}}

diff --git a/files/ko/web/html/canvas/tutorial/basic_usage/index.html b/files/ko/web/html/canvas/tutorial/basic_usage/index.html new file mode 100644 index 0000000000..f455563e87 --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/basic_usage/index.html @@ -0,0 +1,154 @@ +--- +title: 캔버스(Canvas) 기본 사용법 +slug: Web/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")}} 엘리먼트를 살펴보는 것으로 이 튜토리얼을 시작해 보겠습니다. 이 페이지의 끝에서 캔버스 2D 컨텍스트를 설정하는 방법을 알게되고, 여러분의 브라우저에서 첫 번째 예제를 그리게 될 것입니다.

+
+ +

<canvas> 요소

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

{{HTMLElement ( "canvas")}}는 처음에는 src 및 alt 속성이 없다는 점만 제외하면 {{HTMLElement ( "img")}} 요소처럼 보입니다. 실제로 <canvas> 요소에는 {{htmlattrxref ( "width", "canvas")}}와 {{htmlattrxref ( "height", "canvas")}}의 두 속성만 있습니다. 이것들은 모두 선택사항이며 {{Glossary ( "DOM")}} 프로퍼티를 사용하여 설정할 수도 있습니다. width 및 height 속성을 지정하지 않으면 캔버스의 처음 너비는 300 픽셀이고 높이는 150 픽셀입니다. 요소는 {{Glossary ( "CSS")}}에 의해 임의로 크기를 정할 수 있지만 렌더링하는 동안 이미지는 레이아웃 크기에 맞게 크기가 조정됩니다. CSS 크기 지정이 초기 캔버스의 비율을 고려하지 않으면 왜곡되어 나타납니다 .

+ +
+

노트: 만약 렌더링이 왜곡된 것처럼 보이는 경우 CSS를 사용하지 않고 <canvas> 속성에서 widthheight 속성을 명시적으로 지정하십시오.

+
+ +

 

+ +

id 속성(어트리뷰트)는  <canvas> 요소에 국한되지 않는 글로벌HTML 속성 (global HTML attributes )중 하나로,  모든 HTML 요소에 적용 ( class 등등)될 수 있습니다.  대체로 항상 id 속성을 사용해 주는것이 좋은데, 이는 스크립트 내에서 구분을 쉽게 해 줄 수 있기 때문입니다.

+ +

<canvas>요소는 일반적인 이미지 ({{cssxref("margin")}}, {{cssxref("border")}}, {{cssxref("background")}}…) 처럼 스타일을 적용시킬 수 있습니다. 하지만 이 방법은 실제 캔버스 위에 그리는 것에는 영향을 끼치지 않습니다.  이 방법이 어떻게 사용되는지는 해당 챕터에서 확인 할 수 있습니다.  캔버스에 스타일링이 따로 지정 되있지 않았다면, 캔버스 스타일은 투명으로 설정되어있습니다.

+ +
+

대체 콘텐츠

+ +

<canvas> 요소는 {{HTMLElement("video")}}, {{HTMLElement("audio")}} 혹은 {{HTMLElement("picture")}}처럼 {{HTMLElement("img")}}와는 달리, 인터넷 익스플로러 9 이하의 버전이나 텍스트기반 브라우저 등과 같은, 캔버스를 지원하지 않는 오래된 브라우저들을 위한 대체 컨텐츠를 정의하기 쉽습니다. 여러분은 그러한 브라우저들을 위한 대체 컨텐츠를 제공해야 합니다.

+ +

대체 컨텐츠를 제공하는 것은 매우 간단합니다. <canvas>태그 안에  대체 컨텐츠를 삽입합니다. <canvas>태그 를 지원하지 않는 브라우저는 컨테이너를 무시하고 컨테이너 내부의 대체 콘텐츠를 렌더링 합니다. <canvas>를 지원하는 브라우저는 컨테이너 내부의 내용을 무시하고 캔버스를 정상적으로 렌더링합니다.

+ +

예를 들어, 캔버스 내용에 대한 텍스트 설명을 제공하거나 동적으로 렌더링 된 내용의 정적 이미지를 제공 할 수 있습니다. 이것은 다음과 같이 보일 수있습니다:

+ +
<canvas id="stockGraph" width="150" height="150">
+  current stock price: $3.15 +0.15
+</canvas>
+
+<canvas id="clock" width="150" height="150">
+  <img src="images/clock.png" width="150" height="150" alt=""/>
+</canvas>
+
+ +

사용자에게 캔버스를 지원하는 다른 브라우저를 사용하도록 하는 것은 캔버스를 해석하지 못하는 사용자에게 전혀 도움이 되지 않습니다. 유용한 대체 텍스트나 하위 DOM을 제공하는 것이 캔버스에 더 쉽게 접근할수 있도록 도움이 될 것입니다.

+ +

</canvas> 태그 필수

+ +

대체 컨텐츠가 제공되는 방식때문에, {{HTMLElement("img")}} 요소와 달리, {{HTMLElement("canvas")}} 요소는 닫는 태그(</canvas>)가 필요합니다. 닫는 태그가 없다면, 문서의 나머지 부분이 대체 컨텐츠로 간주되고 보이지 않을 것입니다.

+ +

대체 컨텐츠가 필요하지 않다면, 단순히 <canvas id="foo" ...></canvas>가 모든 미지원 브라우저에서 완전하게 호환됩니다.

+ +

렌더링 컨텍스트

+ +

{{HTMLElement("canvas")}} 엘리먼트는 고정 크기의 드로잉 영역을 생성하고 하나 이상의 렌더링 컨텍스(rendering contexts)를 노출하여, 출력할 컨텐츠를 생성하고 다루게 됩니다. 본 튜토리얼에서는, 2D 렌더링 컨텍스트를 집중적으로 다룹니다. 다른 컨텍스트는 다른 렌더링 타입을 제공합니다. 예를 들어, WebGL은 OpenGL ES 을 기반으로 하는 3D 컨텍스트를 사용합니다.

+ +

캔버스는 처음에 비어있습니다. 무언가를 표시하기 위해서, 어떤 스크립트가 랜더링 컨텍스트에 접근하여 그리도록 할 필요가 있습니다. {{HTMLElement("canvas")}} 요소는 {{domxref("HTMLCanvasElement.getContext", "getContext()")}} 메서드를 이용해서, 랜더링 컨텍스트와 (렌더링 컨텍스트의) 그리기 함수들을 사용할 수 있습니다.  getContext() 메서드는 렌더링 컨텍스트 타입을 지정하는 하나의 파라메터를 가집니다. 본 튜토리얼에서 다루고 있는 2D 그래픽의 경우, {{domxref("CanvasRenderingContext2D")}}을 얻기위해 "2d"로 지정합니다.

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

첫 번째 줄의 스크립트는  {{domxref ( "document.getElementById()")}} 메서드를 호출하여 {{HTMLElement ( "canvas")}} 요소를 표시할 DOM을 검색합니다.  요소가 있으면 getContext() 메서드를 사용하여 드로잉 컨텍스트에 액세스 할 수 있습니다.

+ +
+

지원여부 검사

+ +

대체 콘텐츠는 {{HTMLElement ( "canvas")}}를 지원하지 않는 브라우저에 표시됩니다. 스크립트 역시 간단하게 getContext() 메소드의 존재 여부를 테스트함으로써 프로그래밍 방식으로 지원하는지를 확인할 수 있습니다. 위의 코드 예제는 다음과 같이 될 수 있습니다:

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

템플릿 뼈대

+ +

다음은 이후의 예제들에서 시작점으로 사용될 수 있는 가장 최소한의 템플릿입니다.

+ +
+

알아두기: HTML 내에 스크립트(script)를 사용하는것은 좋은 연습 방법이 아닙니다. 다음의 예시에서는 간결하게 나타내기 위해 사용 한 것입니다.

+
+ +
<!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() 함수 문서가 호출되었는데, 이는 문서가 {{event("load")}} 이벤트를 수신하여 페이지 로딩이 완료될 때 한번 실행됩니다. 이 함수 혹은 이와 유사한 함수는, 페이지가 처음 로딩되는 한, {{domxref("WindowTimers.setTimeout", "window.setTimeout()")}}, {{domxref("WindowTimers.setInterval", "window.setInterval()")}}, 혹은 또 다른 이벤트 핸들러 등을 이용하여 호출될 수 있습니다.

+ +

다음은 템플릿이 실제로 어떻게 실행되는지를 보여줍니다. 보이는 바와 같이, 초기에 blank 로 보여집니다.

+ +

{{EmbedLiveSample("A_skeleton_template", 160, 160)}}

+ +

기본 예제

+ +

먼저 두 개의 직사각형을 그린 간단한 예제를 보도록하겠습니다. 그 중 하나는 투명도(alpha transparency)를가집니다. 나중에 이 예제가 어떻게 작동하는지 자세히 살펴 보겠습니다.

+ +
<!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("A_simple_example", 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/ko/web/html/canvas/tutorial/compositing/example/index.html b/files/ko/web/html/canvas/tutorial/compositing/example/index.html new file mode 100644 index 0000000000..e3d74f5220 --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/compositing/example/index.html @@ -0,0 +1,293 @@ +--- +title: 도형 합성 예제 +slug: Web/HTML/Canvas/Tutorial/Compositing/Example +tags: + - HTML5 + - 그래픽 + - 예제 + - 캔버스 +translation_of: Web/API/Canvas_API/Tutorial/Compositing/Example +--- +
{{CanvasSidebar}}
+ +

이 샘플 프로그램에서는 여러 가지 도형 합성 방법을 보여줍니다. 출력은 다음과 같습니다:

+ +

{{ EmbedLiveSample('도형_합성_예제', '100%', '7250', '', 'Web/HTML/Canvas/Tutorial/Compositing/Example') }}

+ +

도형 합성 예제

+ +

다음 코드에서는 프로그램의 나머지 부분에서 사용할 전역 값을 설정합니다.

+ +
var canvas1 = document.createElement("canvas");
+var canvas2 = document.createElement("canvas");
+var gco = [ 'source-over','source-in','source-out','source-atop',
+            'destination-over','destination-in','destination-out','destination-atop',
+            'lighter', 'copy','xor', 'multiply', 'screen', 'overlay', 'darken',
+            'lighten', 'color-dodge', 'color-burn', 'hard-light', 'soft-light',
+            'difference', 'exclusion', 'hue', 'saturation', 'color', 'luminosity'
+          ].reverse();
+var gcoText = [
+'기본 설정으로, 새로운 도형이 원래 도형 위에 그려집니다.',
+'새로운 도형이 원래 도형과 겹치는 부분에만 그려지며, 나머지는 투명하게 설정됩니다.',
+'새로운 도형이 원래 도형과 겹치지 않는 부분에만 그려집니다.',
+'새로운 도형이 원래 도형과 겹치는 부분에만 그려집니다.',
+'새로운 도형이 원래 도형 아래에 그려집니다.',
+'원래 도형 중 새로운 도형과 겹치는 부분이 유지되며, 나머지는 투명하게 설정됩니다.',
+'원래 도형 중 새로운 도형과 겹치지 않는 부분이 유지됩니다.',
+'원래 도형 중 새로운 도형과 겹치는 부분만 유지됩니다. 새로운 도형은 원래 도형 아래에 그려집니다.',
+'두 도형이 겹치는 곳의 색상이 두 색상값을 합한 값으로 결정됩니다.',
+'새로운 도형만 그려집니다.',
+'두 도형이 겹치는 곳이 투명하게 변하며, 나머지는 평범하게 그려집니다.',
+'위쪽 레이어의 픽셀값이 아래쪽 레이어의 해당하는 픽셀값과 곱해지며, 결과적으로 어두운 이미지가 생성됩니다.',
+'픽셀값을 뒤집고 곱한 다음 도로 뒤집습니다. 결과적으로 밝은 이미지가 생성됩니다(multiply의 반대).',
+'multiply와 screen의 조합입니다. 아래쪽 레이어의 어두운 부분은 더 어두워지고, 밝은 부분은 더 밝아집니다.',
+'두 레이어 중 어두운 픽셀값을 취합니다.',
+'두 레이어 중 밝은 픽셀값을 취합니다.',
+'아래쪽 레이어의 픽셀값을 위쪽 레이어의 뒤집힌 픽셀값으로 나눕니다.',
+'아래쪽 레이어의 뒤집힌 픽셀값을 위쪽 레이어의 픽셀값으로 나누고, 그 값을 도로 뒤집습니다.',
+'overlay와 같이 multiply와 screen의 조합이지만, 위아래 레이어의 순서가 바뀐 상태입니다.',
+'조금 더 부드러운 hard-light입니다. 완전한 검은색/흰색에서 무조건 완전한 검은색/흰색이 나오지 않습니다.',
+'한쪽 레이어의 픽셀값에서 다른 쪽 레이어의 픽셀값을 뺍니다. 빼는 순서는 결과값이 양수가 나오는 순서입니다.',
+'difference와 비슷하지만 대비가 덜합니다.',
+'아래쪽 레이어의 채도(chroma)와 명도(luma)를 보존하고 위쪽 레이어의 색상(hue)을 적용합니다.',
+'아래쪽 레이어의 색상과 명도를 보존하고 위쪽 레이어의 채도를 적용합니다.',
+'아래쪽 레이어의 명도를 보존하고 위쪽 레이어의 색상과 채도를 적용합니다.',
+'아래쪽 레이어의 색상과 채도를 보존하고 위쪽 레이어의 명도를 적용합니다.'
+          ].reverse();
+var width = 320;
+var height = 340;
+
+ +

메인 프로그램

+ +

페이지를 불러오고 나면 다음 코드에서 예제를 준비하고 실행합니다:

+ +
window.onload = function() {
+    // lum in sRGB
+    var lum = {
+        r: 0.33,
+        g: 0.33,
+        b: 0.33
+    };
+    // 캔버스 크기 변경
+    canvas1.width = width;
+    canvas1.height = height;
+    canvas2.width = width;
+    canvas2.height = height;
+    lightMix()
+    colorSphere();
+    runComposite();
+    return;
+};
+
+ +

또한 다음 코드의 runComposite()가 여러 가지 작업을 처리하며, 어려운 부분은 보조 함수를 사용합니다.

+ +
function createCanvas() {
+    var canvas = document.createElement("canvas");
+    canvas.style.background = "url("+op_8x8.data+")";
+    canvas.style.border = "1px solid #000";
+    canvas.style.margin = "5px";
+    canvas.width = width/2;
+    canvas.height = height/2;
+    return canvas;
+}
+
+function runComposite() {
+    var dl = document.createElement("dl");
+    document.body.appendChild(dl);
+    while(gco.length) {
+        var pop = gco.pop();
+        var dt = document.createElement("dt");
+        dt.textContent = pop;
+        dl.appendChild(dt);
+        var dd = document.createElement("dd");
+        var p = document.createElement("p");
+        p.textContent = gcoText.pop();
+        dd.appendChild(p);
+
+        var canvasToDrawOn = createCanvas();
+        var canvasToDrawFrom = createCanvas();
+        var canvasToDrawResult = createCanvas();
+
+        var ctx = canvasToDrawResult.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas1, 0, 0, width/2, height/2);
+        ctx.globalCompositeOperation = pop;
+        ctx.drawImage(canvas2, 0, 0, width/2, height/2);
+        ctx.globalCompositeOperation = "source-over";
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText(pop, 5, height/2 - 5);
+        ctx.restore();
+
+        var ctx = canvasToDrawOn.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas1, 0, 0, width/2, height/2);
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText('기존 도형', 5, height/2 - 5);
+        ctx.restore();
+
+        var ctx = canvasToDrawFrom.getContext('2d');
+        ctx.clearRect(0, 0, width, height)
+        ctx.save();
+        ctx.drawImage(canvas2, 0, 0, width/2, height/2);
+        ctx.fillStyle = "rgba(0,0,0,0.8)";
+        ctx.fillRect(0, height/2 - 20, width/2, 20);
+        ctx.fillStyle = "#FFF";
+        ctx.font = "14px arial";
+        ctx.fillText('새로운 도형', 5, height/2 - 5);
+        ctx.restore();
+
+        dd.appendChild(canvasToDrawOn);
+        dd.appendChild(canvasToDrawFrom);
+        dd.appendChild(canvasToDrawResult);
+
+        dl.appendChild(dd);
+    }
+};
+
+ +

보조 함수

+ +

이 프로그램에서는 몇몇 보조 함수를 사용합니다.

+ +
var lightMix = function() {
+    var ctx = canvas2.getContext("2d");
+    ctx.save();
+    ctx.globalCompositeOperation = "lighter";
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(255,0,0,1)";
+    ctx.arc(100, 200, 100, Math.PI*2, 0, false);
+    ctx.fill()
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(0,0,255,1)";
+    ctx.arc(220, 200, 100, Math.PI*2, 0, false);
+    ctx.fill()
+    ctx.beginPath();
+    ctx.fillStyle = "rgba(0,255,0,1)";
+    ctx.arc(160, 100, 100, Math.PI*2, 0, false);
+    ctx.fill();
+    ctx.restore();
+    ctx.beginPath();
+    ctx.fillStyle = "#f00";
+    ctx.fillRect(0,0,30,30)
+    ctx.fill();
+};
+
+ +
var colorSphere = function(element) {
+    var ctx = canvas1.getContext("2d");
+    var width = 360;
+    var halfWidth = width / 2;
+    var rotate = (1 / 360) * Math.PI * 2; // per degree
+    var offset = 0; // scrollbar offset
+    var oleft = -20;
+    var otop = -20;
+    for (var n = 0; n <= 359; n ++) {
+        var gradient = ctx.createLinearGradient(oleft + halfWidth, otop, oleft + halfWidth, otop + halfWidth);
+        var color = Color.HSV_RGB({ H: (n + 300) % 360, S: 100, V: 100 });
+        gradient.addColorStop(0, "rgba(0,0,0,0)");
+        gradient.addColorStop(0.7, "rgba("+color.R+","+color.G+","+color.B+",1)");
+        gradient.addColorStop(1, "rgba(255,255,255,1)");
+        ctx.beginPath();
+        ctx.moveTo(oleft + halfWidth, otop);
+        ctx.lineTo(oleft + halfWidth, otop + halfWidth);
+        ctx.lineTo(oleft + halfWidth + 6, otop);
+        ctx.fillStyle = gradient;
+        ctx.fill();
+        ctx.translate(oleft + halfWidth, otop + halfWidth);
+        ctx.rotate(rotate);
+        ctx.translate(-(oleft + halfWidth), -(otop + halfWidth));
+    }
+    ctx.beginPath();
+    ctx.fillStyle = "#00f";
+    ctx.fillRect(15,15,30,30)
+    ctx.fill();
+    return ctx.canvas;
+};
+
+ +
// HSV (1978) = H: Hue / S: Saturation / V: Value
+Color = {};
+Color.HSV_RGB = function (o) {
+    var H = o.H / 360,
+        S = o.S / 100,
+        V = o.V / 100,
+        R, G, B;
+    var A, B, C, D;
+    if (S == 0) {
+        R = G = B = Math.round(V * 255);
+    } else {
+        if (H >= 1) H = 0;
+        H = 6 * H;
+        D = H - Math.floor(H);
+        A = Math.round(255 * V * (1 - S));
+        B = Math.round(255 * V * (1 - (S * D)));
+        C = Math.round(255 * V * (1 - (S * (1 - D))));
+        V = Math.round(255 * V);
+        switch (Math.floor(H)) {
+            case 0:
+                R = V;
+                G = C;
+                B = A;
+                break;
+            case 1:
+                R = B;
+                G = V;
+                B = A;
+                break;
+            case 2:
+                R = A;
+                G = V;
+                B = C;
+                break;
+            case 3:
+                R = A;
+                G = B;
+                B = V;
+                break;
+            case 4:
+                R = C;
+                G = A;
+                B = V;
+                break;
+            case 5:
+                R = V;
+                G = A;
+                B = B;
+                break;
+        }
+    }
+    return {
+        R: R,
+        G: G,
+        B: B
+    };
+};
+
+var createInterlace = function (size, color1, color2) {
+    var proto = document.createElement("canvas").getContext("2d");
+    proto.canvas.width = size * 2;
+    proto.canvas.height = size * 2;
+    proto.fillStyle = color1; // top-left
+    proto.fillRect(0, 0, size, size);
+    proto.fillStyle = color2; // top-right
+    proto.fillRect(size, 0, size, size);
+    proto.fillStyle = color2; // bottom-left
+    proto.fillRect(0, size, size, size);
+    proto.fillStyle = color1; // bottom-right
+    proto.fillRect(size, size, size, size);
+    var pattern = proto.createPattern(proto.canvas, "repeat");
+    pattern.data = proto.canvas.toDataURL();
+    return pattern;
+};
+
+var op_8x8 = createInterlace(8, "#FFF", "#eee");
diff --git a/files/ko/web/html/canvas/tutorial/compositing/index.html b/files/ko/web/html/canvas/tutorial/compositing/index.html new file mode 100644 index 0000000000..108c493d9d --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/compositing/index.html @@ -0,0 +1,106 @@ +--- +title: 도형 합성 +slug: Web/HTML/Canvas/Tutorial/Compositing +tags: + - HTML5 + - 그래픽 + - 캔버스 +translation_of: Web/API/Canvas_API/Tutorial/Compositing +--- +

이전 페이지들에서 나온 모든 예제에서, 새로 그리는 도형은 언제나 이미 그려진 도형의 위에 그려졌습니다. 대부분의 상황에서는 이렇게 하는 것이 적절하지만, 도형을 합성하기 위한 순서를 제한하게 되는데,  globalCompositeOperation 속성을 설정함으로써 이러한 상태를 바꿀 수 있습니다.

+ +

globalCompositeOperation

+ +

기존 도형 뒤에 새로운 도형을 그릴 수 있을 뿐만 아니라, 도형의 일정 영역을 가려 보이지 않게 하거나 캔버스의 특정 부분을 지우는 (clearRect() 메소드는 사각형의 영역만을 지우지만, 이같은 제한도 없다.) 등의 효과를 얻을 수도 있습니다.

+ +
+
globalCompositeOperation = type
+
새로운 도형을 그릴 때, 도형 합성 방법을 설정합니다. type은 다음 26종류의 합성 방법 중에서 선택할 수 있습니다.
+
+ +

다음 예제의 코드를 확인하려면 도형 합성 예제를 확인해 주세요.

+ +

{{ EmbedLiveSample('도형_합성_예제', 750, 6750, '', 'Web/HTML/Canvas/Tutorial/Compositing/Example') }}

+ +

잘라내기 경로(Clipping path)

+ +

 잘라내기 경로는 다른 캔버스 도형과 비슷하지만, 다른 도형에서 원하지 않는 부분을 가리는 가면과 같은 역할을 합니다. 오른쪽에 있는 그림을 보면 어떤 역할을 하는지 알 수 있을 것입니다. 붉은 별 모양이 잘라내기 경로입니다. 이 경로 밖에 있는 모든 것은 캔버스에 그려지지 않을 것입니다.

+ +

잘라내기 경로와 위에서 살펴본  globalCompositeOperation 속성을 비교해 보면,   source-insource-atop에서 비슷한 효과가 보입니다. 이들과 잘라내기 경로와의 가장 중요한 차이점은, 잘라내기 경로 자체는 캔버스에 전혀 그려지지 않는다는 것입니다. 잘라내기 경로는 제한된 영역 안에서 여러 가지 도형을 그리는 데에 적합합니다.

+ +

캔버스에 도형 그리기에서는 stroke()fill() 메소드만을 설명했었는데, clip()이라는 세 번째 메소드도 있습니다.

+ +
+
clip()
+
현재 그려지는 경로를 현재 잘라내기 경로로 만듭니다.
+
+ +

경로를 닫기 위해 closePath() 대신 clip()을 사용하고, 경로를 채우거나 윤곽선을 만드는 대신 잘라내기 경로로 만들 수 있습니다.

+ +

{{HTMLElement("canvas")}} 요소의 초기 설정값으로써, 캔버스는 캔버스와 똑같은 크기의 잘라내기 경로를 가집니다. 크기가 똑같기 때문에 잘라내기 효과는 나타나지 않습니다.

+ +

clip 예제

+ +

다음 예제에서는 특정 영역의 별들만 보이도록 동그란 모양의 잘라내기 경로를 사용할 것입니다.

+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+  ctx.fillRect(0,0,150,150);
+  ctx.translate(75,75);
+
+  // 동그란 모양의 잘라내기 경로를 생성한다
+  ctx.beginPath();
+  ctx.arc(0,0,60,0,Math.PI*2,true);
+  ctx.clip();
+
+  // 배경을 그린다
+  var lingrad = ctx.createLinearGradient(0,-75,0,75);
+  lingrad.addColorStop(0, '#232256');
+  lingrad.addColorStop(1, '#143778');
+
+  ctx.fillStyle = lingrad;
+  ctx.fillRect(-75,-75,150,150);
+
+  // 별을 그린다
+  for (var j=1;j<50;j++){
+    ctx.save();
+    ctx.fillStyle = '#fff';
+    ctx.translate(75-Math.floor(Math.random()*150),
+                  75-Math.floor(Math.random()*150));
+    drawStar(ctx,Math.floor(Math.random()*4)+2);
+    ctx.restore();
+  }
+
+}
+
+function drawStar(ctx,r){
+  ctx.save();
+  ctx.beginPath()
+  ctx.moveTo(r,0);
+  for (var i=0;i<9;i++){
+    ctx.rotate(Math.PI/5);
+    if(i%2 == 0) {
+      ctx.lineTo((r/0.525731)*0.200811,0);
+    } else {
+      ctx.lineTo(r,0);
+    }
+  }
+  ctx.closePath();
+  ctx.fill();
+  ctx.restore();
+}
+
+ + + +

코드의 위쪽 몇 줄에서는 배경으로 캔버스 크기와 같은 검은색 네모를 그리고, 가운데로 원점을 옮깁니다. 그런 다음 호를 그리고 clip()을 사용하여 동그란 모양의 잘라내기 경로를 생성합니다. 캔버스 상태를 저장할 때 잘라내기 경로도 같이 저장됩니다. 이전의 잘라내기 경로를 보존하려면, 새로운 잘라내기 경로를 만들기 전에 캔버스 상태를 저장하면 됩니다.

+ +

잘라내기 경로를 만든 후에 그려지는 모든 것들은, 그 경로의 안쪽에서만 보입니다. 이는 그 다음에 그려지는 선형 그라디언트에서 확실히 볼 수 있습니다. 이렇게 하고 나서, drawStar() 함수를 사용하여 위치와 크기가 모두 다른 50개의 별을 그립니다. 이 별들은 잘라내기 경로 안쪽에만 나타납니다.

+ +

{{EmbedLiveSample("A_clip_example", "180", "180", "https://mdn.mozillademos.org/files/208/Canvas_clip.png")}}

+ +

{{PreviousNext("Web/Guide/HTML/Canvas_tutorial/Transformations", "Web/Guide/HTML/Canvas_tutorial/Basic_animations")}}

diff --git a/files/ko/web/html/canvas/tutorial/drawing_shapes/index.html b/files/ko/web/html/canvas/tutorial/drawing_shapes/index.html new file mode 100644 index 0000000000..09df4b829d --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/drawing_shapes/index.html @@ -0,0 +1,577 @@ +--- +title: 캔버스(canvas)를 이용한 도형 그리기 +slug: Web/HTML/Canvas/Tutorial/Drawing_shapes +tags: + - Canvas + - 그래픽 + - 중급 + - 캔버스 + - 튜토리얼 +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 environment)을 완료 하였다면, 이제 어떻게 캔버스에 그릴수 있는지에 대하여 자세하게 알아봅시다. 이 글을 끝내고 난 후, 여러분은 어떻게 사각형, 삼각형, 선, 아치, 곡선 등 의 기본적인 도형을 그릴수 있는지 익히실 수 있을 것 입니다.  캔버스 위에 물체를 그릴 때에는 path를 사용하는것이 필수적이므로 우리는 이것이 어떻게 사용되는지 볼 것입니다.

+
+ +

그리드

+ +

드로잉을 시작 하기에 앞서, 캔버스 그리드 혹은 좌표공간 (coordinate space) 에 대하여 이야기 해보겠습니다. 이전 페이지에서 이야기 했던 HTML 골격(skeleton)는 가로 세로 각각 150 픽셀의 캔버스 요소를 가지고 있습니다. 오른쪽에 보시면, 캔버스와 기본 그리드가 놓인것을 보실 수 있습니다. 기본적으로 그리드의 1단위는 캔버스의 1픽셀과 같습니다. 이 그리드의 원점은 좌측상단의 (0,0) 입니다. 모든 요소들은 이 원점을 기준으로 위치됩니다. 그렇기 때문에, 파란 사각형의 좌측상단은 왼쪽에서 x 픽셀, 위에서 y 픽셀 떨어진 것이라 볼 수 있고, 이 사각형의 좌표는 (x,y)가 됩니다. 이 튜토리얼 후반부에서 어떻게 원점을 이동하며, 그리드를 회전하고 같은 비율로 확대/축소할 수 있는지 살펴볼 것이지만, 지금은 기본에 충실하도록 합시다.

+ +

직사각형 그리기

+ +

{{Glossary("SVG")}} 와는 다르게, {{HTMLElement("canvas")}}는 오직 하나의 원시적인 도형만을 제공합니다. 바로 직사각형 입니다. 다른 모든 도형들은 무조건 하나 혹은 하나 이상의 path 와 여러 점으로 이어진 선으로 만들어집니다. 다행히도, 우리는 여러 path drawing 함수(function)들을 통해 아주 어려운 도형들도 그릴수 있습니다.

+ +

첫번째로, 직사각형을 봅시다. 캔버스 위에 직사각형을 그리는데에는 세가지 함수(function)가 있습니다:

+ +
+
{{domxref("CanvasRenderingContext2D.fillRect", "fillRect(x, y, width, height)")}}
+
색칠된 직사각형을 그립니다.
+
{{domxref("CanvasRenderingContext2D.strokeRect", "strokeRect(x, y, width, height)")}}
+
직사각형 윤곽선을 그립니다.
+
{{domxref("CanvasRenderingContext2D.clearRect", "clearRect(x, y, width, height)")}}
+
특정 부분을 지우는 직사각형이며, 이 지워진 부분은 완전히 투명해집니다.
+
+ +

각각의 세 함수는 모두 같은 변수를 가집니다. xy는 캔버스의 좌측상단에서 사각형의 (원점으로부터 상대적인) 위치를 뜻하며,  width 와 height는 사각형의 크기를 뜻하게 됩니다.

+ +

전 페이지에서 보여드렸던 draw() 함수(function)를 이용하여 위의 세가지 함수를 아래의 예제에 적용해 보았습니다.

+ +

직사각형 도형 예제

+ + + +
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() 함수는 가로 세로 100 픽셀 사이즈의 검정 사각형을 그립니다. 이후 clearRect() 함수가 60x60 픽셀의 사각형 크기로 도형 중앙을 지우게 되고, strokeRect()은 이 빈 사각형 공간 안에 50x50 픽셀 사이즈의 윤곽선만 있는 사각형을 만들게 됩니다.

+ +

다음 페이지에서, 우리는 clearRect()를 대신하는 두개의 함수에 대해 살펴보고, 만들어진 도형의 색이나 윤곽선의 스타일을 바꾸는 방법들에 대하여 알아보도록 하겠습니다.

+ +

우리가 다음 섹션에서 보게될 path 함수와 다르게 세개의 직사각형 함수는 캔버스에 바로 그릴 수 있습니다.

+ +

경로 그리기

+ +

경로(path)는 직사각형 이외의 유일한 원시적인(primitive) 도형입니다. 경로는 점들의 집합이며, 선의 한 부분으로 연결되어 여러가지 도형, 곡선을 이루고 두께와 색을 나타내게 됩니다. 경로나 하위 경로(sub-path)는 닫힐 수 있습니다. 경로를 이용하여 도형을 만들 때에는 몇가지 추가적인 단계를 거쳐야 합니다:

+ +
    +
  1. 경로를 생성합니다.
  2. +
  3. 그리기 명령어를 사용하여 경로상에 그립니다.
  4. +
  5. 경로가 한번 만들어졌다면, 경로를 렌더링 하기 위해서 윤곽선을 그리거나 도형 내부를 채울수 있습니다.
  6. +
+ +

다음은 위의 단계들을 실행하기 위해 사용되는 함수입니다:

+ +
+
{{domxref("CanvasRenderingContext2D.beginPath", "beginPath()")}}
+
새로운 경로를 만듭니다. 경로가 생성됬다면, 이후 그리기 명령들은 경로를 구성하고 만드는데 사용하게 됩니다.
+
Path 메소드 (Path methods)
+
물체를 구성할 때 필요한 여러 경로를 설정하는데 사용하는 함수입니다.
+
{{domxref("CanvasRenderingContext2D.closePath", "closePath()")}}
+
현재 하위 경로의 시작 부분과 연결된 직선을 추가합니다.
+
{{domxref("CanvasRenderingContext2D.stroke", "stroke()")}}
+
윤곽선을 이용하여 도형을 그립니다.
+
{{domxref("CanvasRenderingContext2D.fill", "fill()")}}
+
경로의 내부를 채워서 내부가 채워진 도형을 그립니다.
+
+ +

경로를 만들기 위한 첫번째 단계는 beginPath() 메소드를 사용하는 것 입니다. 내부적으로, 경로는 도형을 이루는 하위경로(선, 아치 등)들의 집합으로 이루어져있습니다. 이 메소드가 호출될 때 마다, 하위 경로의 모음은 초기화되며, 우리는 새로운 도형을 그릴 수 있게 됩니다.

+ +
참고:  현재 열린 path가  비어있는 경우 ( beginPath() 메소드를 사용한 직 후, 혹은캔버스를 새로 생성한 직후), 첫 경로 생성 명령은 실제 동작에 상관 없이 moveTo()로 여겨지게 됩니다. 그렇기 때문에 경로를 초기화한 직후에는 항상 명확하게 시작 위치를 설정해 두는것이 좋습니다.
+ +

두번째 단계는 실제로 경로가 그려지는 위치를 설정하는 메소드를 호출하는 것 입니다. 이 내용에 대해서는 곧 보실수 있습니다.

+ +

세번째 단계는 선택사항으로 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")}}

+ +

펜(pen) 이동하기

+ +

가장 유용한 함수중에 실제로 어떤 것도 그리지 않지만 위에서 언급한 경로의 일부가 되는  moveTo() 함수가 있습니다. 이는 펜이나 연필을 종이위에서 들어 옆으로 옮기는것이라고 보시면 됩니다.

+ +
+
{{domxref("CanvasRenderingContext2D.moveTo", "moveTo(x, y)")}}
+
펜을  x와 y 로 지정된 좌표로 옮깁니다.
+
+ +

캔버스가 초기화 되었거나 beginPath() 메소드가 호출되었을 때, 특정 시작점 설정을 위해 moveTo() 함수를 사용하는것이 좋습니다. 또한 moveTo()  함수는 연결되지 않은 경로를 그리는데에도 사용 할 수 있습니다. 아래의 스마일 아이콘을 봅시다.

+ +

코드 snippet을 사용해하여 직접 시도하여 보세요. 앞에서 보았던 draw() 함수(function)를 붙혀넣기 해 보세요.

+ + + +
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); // Outer circle
+    ctx.moveTo(110, 75);
+    ctx.arc(75, 75, 35, 0, Math.PI, false);  // Mouth (clockwise)
+    ctx.moveTo(65, 65);
+    ctx.arc(60, 65, 5, 0, Math.PI * 2, true);  // Left eye
+    ctx.moveTo(95, 65);
+    ctx.arc(90, 65, 5, 0, Math.PI * 2, true);  // Right eye
+    ctx.stroke();
+  }
+}
+
+ +

결과는 다음과 같습니다:

+ +

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

+ +

 moveTo()를 사용한 코드라인을 지우면 연결된 선들을 확인 할 수 있습니다

+ +
+

참고: arc() function에 대하여 더 알아보고 싶다면 아래의  {{anch("Arcs")}} 를 확인하세요.

+
+ +

+ +

직선을 그리기 위해서는 lineTo() 메소드를 사용할 수 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.lineTo", "lineTo(x, y)")}}
+
현재의 드로잉 위치에서 x와 y로 지정된 위치까지 선을 그립니다.
+
+ +

이 메소드는 선의 끝점의 좌표가 되는 x와 y의 두개의 인자가 필요합니다. 시작점은 이전에 그려진 경로에 의해 결정 되며, 이전 경로의 끝점이 다음 그려지는 경로의 시작점이 됩니다. 또한 시작점은 moveTo() 메소드를 통해 변경될 수 있습니다.

+ +

아래의 예시는 하나의 두 삼각형 (윤곽선 삼각형, 색칠된 삼각형)을 그립니다.

+ + + +
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() 메소드를 가지고 시작점을 원하는 위치로 새롭게 지정 해 줍니다. 다음은, 두선을 그어 삼각형의 두 면을 그려줍니다.

+ +

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

+ +

여러분은 채워진 삼각형과 윤곽선 삼각형의 차이를 확인 하셨을 겁니다. 위에 언급했던 것 처럼, 경로가 채워지게 되면 그 도형은 자동으로 닫히게 되지만 윤곽선 삼각형에서는 그렇지 않기 때문입니다. 만약에 closePath() 메소드를 윤곽선 삼각형 코드에서 지운다면, 오직 두 선만 그려지게 되며 완벽한 삼각형으로 만들어지지 않습니다.

+ +

호(arc)

+ +

호나 원을 그리기위해서는 arc() 혹은 arcTo() 메소드를 사용합니다..

+ +
+
{{domxref("CanvasRenderingContext2D.arc", "arc(x, y, radius, startAngle, endAngle, anticlockwise)")}}
+
(x, y) 위치에 원점을 두면서, 반지름 r을 가지고,  startAngle 에서 시작하여 endAngle 에서 끝나며 주어진 anticlockwise 방향으로 향하는 (기본값은 시계방향 회전) 호를 그리게 됩니다.
+
{{domxref("CanvasRenderingContext2D.arcTo", "arcTo(x1, y1, x2, y2, radius)")}}
+
주어진 제어점들과 반지름으로 호를 그리고,  이전 점과 직선으로 연결합니다.
+
+ +

arc 메소드의 여섯개의 매개변수에 대하여 좀 더 자세하게 알아봅시다: xy는 호를 그릴 때 필요한 원점 좌표입니다. 반지름(radius) 은 말 그대로 호의 반지름을 뜻합니다. startAngleendAngle 매개 변수는 원의 커브를 따라 호의 시작점과 끝점을 라디안 단위로 정의합니다. 이 변수들은 x축을 기준으로 계산됩니다. Boolean 값을 가지는 anticlockwise 변수는 true일 때 호를 반시계 방향으로 그리게 되며, 그렇지 않을 경우에는 시계 방향으로 그리게 됩니다.

+ +
+

참고: arc 함수에서 각도는 각이 아닌 라디안 값을 사용합니다. 각도를 라디안으로 바꾸려면 다음의 자바스크립트(JavaScript) 코드를 사용하실 수 있습니다: radians = (Math.PI/180)*degrees.

+
+ +

다음의 예제는 우리가 이제껏 봐 왔던 예제들 보다 약간 더 복잡합니다. 이 예제는 12가지의 다양한 각도로 채워진 각기 다른 호를 그립니다.

+ +

두개의  for loops은 루프를 통해 호(arc)들의 행과 열을 읽기 위해 사용되었습니다. beginPath()를 사용해 각 호의 새로운 경로를 만듭니다. 코드 내에서, 각각의 매개변수들을 명확하게 보여주기 위해 변수로 정의 하였지만, 실제로 사용할때 꼭 필요한 것은 아닙니다.

+ +

xy 좌표는 충분히 명확하게 표기되어야 합니다.  radius 와 startAngle은 고정되어 있습니다. endAngle는 처음 180도 (반원) 에서 시작하고 이후 매번 90도씩 증가하다가 마지막 열에서 완벽한 원을 그립니다.

+ +

clockwise 매개 변수를 지정한 결과로 첫번째와 세번째 줄은 시계방향으로 원호들이 그려졌고 두번째와 네번째 줄에는 반시계방향의 원호들이 그려졌습니다. 마지막으로 if 문은 위 반쪽이 윤곽선으로, 아래 반쪽이 색으로 채워진 호들을 만들어 냅니다.

+ +
+

참고: 이 예제는 다른 예제들 보다 더 큰사이즈의 캔버스가 필요합니다: 150 x 200 픽셀

+
+ + + +
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 coordinate
+        var y = 25 + i * 50; // y coordinate
+        var radius = 20; // Arc radius
+        var startAngle = 0; // Starting point on circle
+        var endAngle = Math.PI + (Math.PI * j) / 2; // End point on circle
+        var anticlockwise = i % 2 == 0 ? false : true; // clockwise or anticlockwise
+
+        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")}}

+ +

베지어(Bezier) 곡선과 이차(Quadratic )곡선

+ +

다음 경로 타입은 베지어 곡선 (Bézier curves)으로, 삼차(cubic)와 이차(quadric) 변수가 모두 가능합니다. 이 타입은 대게 복잡한 유기체적 형태 (organic shape)를 그리는데 사용됩니다.

+ +
+
{{domxref("CanvasRenderingContext2D.quadraticCurveTo", "quadraticCurveTo(cp1x, cp1y, x, y)")}}
+
cp1xcp1y로 지정된 제어점을 사용하여 현재 펜의 위치에서 x와 y로 지정된 끝점까지 이차 베지어 곡선을 그립니다.
+
{{domxref("CanvasRenderingContext2D.bezierCurveTo", "bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)")}}
+
(cp1x, cp1y) 및 (cp2x, cp2y)로 지정된 제어점을 사용하여 현재 펜 위치에서 xy로 지정된 끝점까지 삼차 베지어 곡선을 그립니다.
+
+ +

오른쪽의 사진은 두 곡선의 차이를 가장 잘 설명해주고 있습니다. 이차 베지에 곡선은 시작점과 끝점 (파란색 점) 그리고 하나의 제어점 (control point, 빨간 점으로 표시)을 가지고 있지만, 삼차 베지에 곡선은 두개의 제어점을 사용하고 있습니다.

+ +

두 메소드에 모두 사용되는 xy 변수는 모두 끝점의 좌표를 나타냅니다. 첫번째 제어점은 cp1x 와 cp1y 좌표로, 두번째 제어점은 cp2x 와 cp2y  좌표로 표시되었습니다.

+ +

이차 및 삼차 베지어 곡선을 사용하는 것은 매우 어려울 수 있습니다. Adobe Illustrator와 같은 벡터 드로잉 소프트웨어와는 달리, 우리는 현재 수행중인 작업에 대해 직접적인 시각적 피드백을 받을 수 없기 때문입니다. 이런 점은 복잡한 모양을 그리기 어렵도록 합니다. 다음 예제에서 우리는 간단한 유기체적 형태만 그리도록 하겠지만, 여러분이 연습과 시간을 투자 하신다면, 이후에 더욱 복잡한 도형을 그릴수 있게 될 것입니다.

+ +

이 예제는 아주 어려운 점은 없습니다. 두 경우 모두 연속된 곡선이 그려지면서 최종 모양이 완성됩니다.

+ +

이차 베지에 곡선(Quadratic Bezier curves)

+ +

이 예제는 여러개의 이차 베지어 곡선을 이용해 말풍선을 만들어 냅니다.

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    // Quadratric curves example
+    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")}}

+ +

삼차 베지어 곡선 (Cubic Bezier curves)

+ +

이 예제는 삼차 곡선을 이용하여 하트를 그립니다.

+ + + +
function draw() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    // Cubic curves example
+    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")}}

+ +

직사각형

+ +

직사각형을 캔버스에 직접 그리는 {{anch("직사각형 그리기")}}에서 본 세 가지 메소드 외에 rect() 메소드도 있습니다. 이 메소드는 현재 열린 패스에 직사각형 경로를 추가합니다.

+ +
+
{{domxref("CanvasRenderingContext2D.rect", "rect(x, y, width, height)")}}
+
좌측상단이 (x, y)이고 폭과 높이가 widthheight인 직사각형을 그립니다.
+
+ +

이 메소드가 실행되기 전에, (x,y) 매개변수를 가진 moveTo() 메소드가 자동으로 호출됩니다. 즉, 현재의 펜위치가 자동으로 기본 좌표로 초기화 됩니다.

+ +

조합하기

+ +

이제까지 이 페이지의 예제들은 각각의 도형마다 하나의 path 함수를 가지고 있었습니다. 하지만 도형을 만드는데에 사용되는 경로의 종류와 개수는 제한이 없습니다. 그렇기 때문에 이 마지막 예제에서는 모든 경로 함수를 합쳐 여러 게임 캐릭터들을 그려보도록 하겠습니다.

+ + + +
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();
+  }
+}
+
+// A utility function to draw a rectangle with rounded corners.
+
+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 오브젝트 (Path2D objects)

+ +

마지막 예제에서 보았 듯이, 캔버스에 객체를 그리는 일련의 경로와 그리기 명령이 있을 수 있습니다. 코드를 단순화하고 성능을 향상시키기 위해 최근 버전의 브라우저에서 사용할 수있는 {{domxref("Path2D")}} 객체를 사용하여 이러한 드로잉 명령을 캐시하거나 기록 할 수 있습니다. 이로써 여러분은 경로를 빠르게 다시 실행 시킬 수 있습니다.

+ +

어떻게 Path2D object를 생성 할 수 있는지 확인해 봅시다:

+ +
+
{{domxref("Path2D.Path2D", "Path2D()")}}
+
Path2D() 생성자는 새로운 Path2D 객체를 반환합니다. 선택적으로 다른 경로를 인수로 받거나(복사본을 생성), SVG 경로 데이터로 구성된 문자열을 받아서 객체로 반환합니다.
+
+ +
new Path2D();     // empty path object
+new Path2D(path); // copy from another Path2D object
+new Path2D(d);    // path from SVG path data
+ +

moveTo, rect, arc 혹은 quadraticCurveTo 등과 같은 모든 경로 메소드 (path methods)들은  Path2D 객체에서 사용 가능합니다.

+ +

Path2D API는 또한 addPath 메소드를 사용하여 경로를 결합하는 방법을 추가합니다. 예를 들자면, 여러 요소를 사용하는 오브젝트를 만들 때 유용하게 사용 될 수 있습니다.

+ +
+
{{domxref("Path2D.addPath", "Path2D.addPath(path [, transform])")}}
+
옵션으로 변환 행렬(transformation matrix)을 사용하여 현재 경로에 경로를 추가합니다.
+
+ +

Path2D 예제

+ +

이 예제에서는, 직사각형과 원을 만들어 볼 것입니다. 나중에 사용할 것을 고려하여, 두 도형 모두 Path2D object로 저장 될 것입니다. 새로운 버전의 Path2D API에서는 여러 메소드들이 지금 사용하고있는 path가 아닌 Path2D object를 옵션으로 선택하여 사용 할 수 있도록 업데이트 되었습니다. 아래의 예제에서 보시면, stroke 와 fill 메소드가 오브젝트를 캔버스 위에 그리도록 path 변수와 함께 사용되었습니다.

+ + + +
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 paths 사용하기

+ +

새로운 캔버스 path2D API 또다른 강력한 특징 중 하나는, 캔버스의 path를 초기화 하기 위해 SVG path data를 사용한다는 것입니다. 이는 path 데이터를 이동시키며, SVG와 canvas 에서 재사용 할 수 있도록 해줍니다. 

+ +

path는 (M10 10) 점으로 이동한 다음, 수평하게 오른쪽으로 으로 80 포인트 (h 80)  만큼 이동합니다. 이후 수직으로 80포인트 (v 80) 내려간 다음, 80 포인트 왼쪽으로 (h -80) 수평하게 이동하고 다시 시작점 (z)으로 돌아갑니다. 예시는 이곳( Path2D constructor )에서 확인하실 수 있습니다.

+ +
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/ko/web/html/canvas/tutorial/finale/index.html b/files/ko/web/html/canvas/tutorial/finale/index.html new file mode 100644 index 0000000000..1241680c5c --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/finale/index.html @@ -0,0 +1,51 @@ +--- +title: Finale +slug: Web/HTML/Canvas/Tutorial/Finale +tags: + - 그래픽 + - 캔버스 + - 튜토리얼 +translation_of: Web/API/Canvas_API/Tutorial/Finale +--- +
{{CanvasSidebar}} {{PreviousNext("Web/API/Canvas_API/Tutorial/Optimizing_canvas")}}
+ +
+

축하합니다 Canvas 튜토리얼을 모두 끝마쳤습니다! 이 정보는 웹에서 더 나은 2D 그래픽을 만드는데 도움이 됩니다.

+
+ +

더 많은 예시와 튜토리얼

+ +

이 사이트에는 다양한 데모와 canvas에 대한 추가 설명이 있다.

+ +
+
Codepen.io
+
프론트 엔드 개발자 playground 및 브라우저의 코드 편집기.
+
HTML5 Canvas Tutorials
+
대부분 canvas API의 예시
+
Game development
+
게임은 가장 인기있는 컴퓨터 활동 중 하나이다. 어떤 표준 규격의 웹 브라우저에서도 실행할 수 있는 더 나은 게임을 개발할 수 있도록 하기 위한 신기술이 끊임없이 등장하고 있다.
+
+ +

기타 웹API

+ +

이 API들는 canvas 및 그래픽으로 작업할 때 유용하다.

+ +
+
WebGL
+
3D를 포함한 복잡한 그래픽 렌더링을 위한 고급 API.
+
SVG
+
확장 가능한 Vector Graphics는 이미지를 벡터(선)과 형태의 집합으로 묘사하여 이미지를 그리는 크기에 상관없이 원활하게 확장할 수 있다.
+
Web Audio
+
Web Audio API는 개발자들이 오디오 소스 선택, 오디오에 효과 추가, 오디오 시각화 생성, 공간 효과 적용(예: 패닝)등을 할 수 있도록 웹 상에서 오디오를 제어하기 위한 다양하고 좋은 시스템을 제공한다.
+
+ +

문의사항

+ +
+
Stack Overflow
+
"canvas"가 태그된 문의사항.
+
Comments about this tutorial – the MDN documentation community
+
이 튜토리얼에 대해 의견이 있으시거나 저희에게 감사를 표하고 싶다면 언제든지 연락해주세요!
+
+ +

{{PreviousNext("Web/API/Canvas_API/Tutorial/Optimizing_canvas")}}

diff --git a/files/ko/web/html/canvas/tutorial/hit_regions_and_accessibility/index.html b/files/ko/web/html/canvas/tutorial/hit_regions_and_accessibility/index.html new file mode 100644 index 0000000000..e720af3159 --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/hit_regions_and_accessibility/index.html @@ -0,0 +1,97 @@ +--- +title: 히트(Hit) 영역과 접근성 +slug: Web/HTML/Canvas/Tutorial/Hit_regions_and_accessibility +translation_of: Web/API/Canvas_API/Tutorial/Hit_regions_and_accessibility +--- +
{{CanvasSidebar}} {{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
+ +
{{HTMLElement("canvas")}} 엘리먼트는 비트맵이며 그려진 객체에 대한 정보는 제공하지 않습니다. 캔버스 컨텐츠는 시멘틱 HTML과 같은 접근성 도구에 노출되지 않습니다. 일반적으로 접근성을 위한 웹 사이트 또는 앱에서는 캔버스를 사용하지 않는 것이 좋습니다. 본 가이드라인은 접근성이 향상된 캔버스를 만드는데 도움이 될 것입니다.
+ +

대체 컨텐츠

+ +

<canvas> ... </ canvas> 태그 안의 내용은 캔버스 렌더링을 지원하지 않는 브라우저의 대체 컨텐츠로 사용할 수 있습니다. 또한 하위 DOM을 읽고 해석 할 수있는 보조 기술 사용자 (스크린 리더와 같은)에게도 매우 유용합니다. html5accessibility.com의 좋은 예가 이를 수행 할 수있는 방법을 보여줍니다.

+ +
<canvas>
+  <h2>Shapes</h2>
+  <p>A rectangle with a black border.
+   In the background is a pink circle.
+   Partially overlaying the <a href="http://en.wikipedia.org/wiki/Circle" onfocus="drawCircle();" onblur="drawPicture();">circle</a>.
+   Partially overlaying the circle is a green
+   <a href="http://en.wikipedia.org/wiki/Square" onfocus="drawSquare();" onblur="drawPicture();">square</a>
+   and a purple <a href="http://en.wikipedia.org/wiki/Triangle" onfocus="drawTriangle();" onblur="drawPicture();">triangle</a>,
+   both of which are semi-opaque, so the full circle can be seen underneath.</p>
+</canvas> 
+ +

Steve Faulkner의 NVDA가 이 예제를 어떻게 읽는지를 보여주는 동영상을 참고하시기 바랍니다.

+ +

ARIA 규칙

+ +

ARIA(Accessible Rich Internet Application)는 장애인이 사용자가 웹 콘텐츠 및 웹 응용 프로그램을보다 쉽게 사용할 수 있도록하는 방법을 정의합니다. ARIA 속성을 사용하여 캔버스 엘리먼트의 동작 및 용도를 설명 할 수 있습니다. 자세한 내용은 ARIAARIA 기술을 참조하십시오.

+ +
<canvas id="button" tabindex="0" role="button" aria-pressed="false" aria-label="Start game"></canvas>
+
+ +

히트(Hit) 영역

+ +

마우스 좌표가 캔버스의 특정 영역 내에 있는지 여부는 문제를 해결하는 데 공통적입니다. 히트 영역 API를 사용하면 캔버스 영역을 정의 할 수 있으며 캔버스에 대화형 컨텐츠를 접근성 도구에 표시 할 수 있습니다. 히트 영역 API는 여러분이 히트 감지를 쉽게 할 수 있도록 하며 DOM 엘리먼트에 이벤트를 전달할 수 있도록 합니다. API에는 다음 세 가지 메소드가 있습니다 (현재 웹 브라우저에서는 아직 실험 중이며 브라우저 호환성 테이블을 확인하십시오).

+ +
+
{{domxref("CanvasRenderingContext2D.addHitRegion()")}} {{experimental_inline}}
+
히트 영역을 캔버스에 추가합니다.
+
{{domxref("CanvasRenderingContext2D.removeHitRegion()")}} {{experimental_inline}}
+
캔버스에서 해당 id를 가진 히트 영역을 제거합니다.
+
{{domxref("CanvasRenderingContext2D.clearHitRegions()")}} {{experimental_inline}}
+
캔버스에서 모든 히트 영역을 제거합니다.
+
+ +

경로에 히트 영역을 추가하고 {{domxref("MouseEvent.region")}} 속성을 확인하여 마우스가 영역을 히트하는지 테스트 할 수 있습니다.

+ +
<canvas id="canvas"></canvas>
+<script>
+var canvas = document.getElementById('canvas');
+var ctx = canvas.getContext('2d');
+
+ctx.beginPath();
+ctx.arc(70, 80, 10, 0, 2 * Math.PI, false);
+ctx.fill();
+ctx.addHitRegion({id: 'circle'});
+
+canvas.addEventListener('mousemove', function(event) {
+  if (event.region) {
+    alert('hit region: ' + event.region);
+  }
+});
+</script>
+ +

addHitRegion() 메소드는 control 옵션을 이용하여 이벤트를 엘리먼트(즉, 캔버스의 자식으로)로 전달합니다.

+ +
ctx.addHitRegion({control: element});
+ +

예를 들어 {{HTMLElement("input")}} 엘리먼트로 전달하는 데 유용 할 수 있습니다. codepen 데모를 참조하십시오.

+ +

포커스 링(Focus rings)

+ +

키보드로 작업 할 때 포커스 링은 페이지 탐색에 도움이되는 편리한 표시기입니다. 캔버스 드로잉에 포커스 링을 그리려면 drawFocusIfNeeded 속성을 사용할 수 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.drawFocusIfNeeded()")}} {{experimental_inline}}
+
지정된 엘리먼트에 포커스가있는 경우,이 메소드는 현재 경로 주위에 포커스 링을 그립니다.
+
+ +

또한 scrollPathIntoView() 메서드를 사용하여 포커스가있는 경우 엘리먼트를 화면에 표시 할 수 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.scrollPathIntoView()")}} {{experimental_inline}}
+
현재 경로 또는 지정된 경로를 뷰로 스크롤합니다.
+
+ +

See also

+ + + +
{{ PreviousNext("Web/API/Canvas_API/Tutorial/Pixel_manipulation_with_canvas", "Web/API/Canvas_API/Tutorial/Optimizing_canvas") }}
diff --git a/files/ko/web/html/canvas/tutorial/index.html b/files/ko/web/html/canvas/tutorial/index.html new file mode 100644 index 0000000000..03077163aa --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/index.html @@ -0,0 +1,62 @@ +--- +title: 캔버스 튜토리얼 +slug: Web/HTML/Canvas/Tutorial +tags: + - Canvas + - Graphic + - Guide + - HTML + - HTML5 + - Intermediate + - Web +translation_of: Web/API/Canvas_API/Tutorial +--- +
{{CanvasSidebar}}
+ +
+ +
+

<canvas>는 HTML 요소 중 하나로서, 스크립트(보통은 자바스크립트)를 사용하여 그림을 그리는 데에 사용됩니다. 예를 들면, 그래프를 그리거나 사진을 합성하거나, 간단한(혹은 복잡할 수도 있는) 애니메이션을 만드는 데에 사용될 수 있습니다. 오른쪽에 보이는 이미지들은 앞으로 설명하게 될 <canvas>를 사용하여 만들 수 있는 것들의 일부입니다.

+
+ +

이 튜토리얼은 <canvas> 요소를 사용하여 2D 그래픽을 어떻게 그리는지 기초부터 설명합니다. 예제들을 통하여 캔버스로 할 수 있는 것이 무엇인지 알려주며, 바로 사용할 수 있도록 코드도 제공합니다.

+ +

<canvas>는 Apple의 Webkit에 처음 도입되어 Mac OS X 대시보드(Dashboard)에 사용되었고, 이후 다른 브라우저에도 구현되어 왔습니다. 현재 대부분의 주요 브라우저에서 지원됩니다.

+ +

시작하기 전 알아두어야 할 것

+ +

<canvas> 요소를 사용하는 것이 어려운 일은 아니지만, HTML자바스크립트에 대한 기본 지식을 갖추고 있어야 합니다. 몇몇 오래된 브라우저는 <canvas> 요소를 지원하지 않지만, 최근 버전의 주요 브라우저들은 모두 지원하고 있습니다. 캔버스의 크기는 300px * 150px (너비 * 높이)가 초기 설정값이며, HTML heightwidth 속성을 사용하여 바꿀 수 있습니다. 캔버스에 그림을 그리려면 자바스크립트 컨텍스트 오브젝트를 사용하며, 즉석에서 그림을 생성할 수 있습니다.

+ +

튜토리얼 내용

+ + + +

같이 보기

+ + + + + +
{{ Next("Web/API/Canvas_API/Tutorial/Basic_usage") }}
diff --git a/files/ko/web/html/canvas/tutorial/optimizing_canvas/index.html b/files/ko/web/html/canvas/tutorial/optimizing_canvas/index.html new file mode 100644 index 0000000000..460b5e893f --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/optimizing_canvas/index.html @@ -0,0 +1,110 @@ +--- +title: 캔버스 최적화 +slug: Web/HTML/Canvas/Tutorial/Optimizing_canvas +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 API를 한계치까지 사용하면 성능이 저하되기 시작합니다. 이 글에서는 그래픽이 잘 동작하도록 보장하기 위해 캔버스 엘리먼트의 사용을 최적화하기위한 제안 사항을 제공합니다.

+
+ +

성능 팁

+ +

다음은 캔버스 성능을 개선하기 위한 팁 모음입니다.

+ +

캔버스에 표시되지 않는 비슷한 원시 혹은 반복 객체를 미리 그려라

+ +

만약 당신이 캔버스에 애니메이션 프레임을 그리면서 반복적인 작업이 발견된다면, 눈에 보이지 않는 숨겨진 캔버스 요소를 새로 만들고 그 캔버스에 미리 그려 넣는 방법을 고려하세요. 그렇게 하면 필요한 순간에 숨긴 캔버스에 그려진 이미지를 다시 주 캔버스 이미지에 그려넣어, 불필요한 렌더링 반복 작업을 줄여 성능 향상을 꾀할 수 있습니다.

+ +
myCanvas.offscreenCanvas = document.createElement('canvas');
+myCanvas.offscreenCanvas.width = myCanvas.width;
+myCanvas.offscreenCanvas.height = myCanvas.height;
+
+myCanvas.getContext('2d').drawImage(myCanvas.offScreenCanvas, 0, 0);
+ +

부동 소수점 좌표를 피하고 대신 정수를 사용하라.

+ +

정수값들 없이 캔버스 상의 객체를 렌더링할 때 부가적인 픽셀 렌더링이 발생합니다.

+ +
ctx.drawImage(myImage, 0.3, 0.5);
+
+ +

이렇게하면 앤티 앨리어싱(anti-aliasing) 효과를 만들기 위해 브라우저에서 추가 연산을 수행해야합니다. 예제에서 이를 방지하려면 {{jsxref("Math.floor()")}}를 사용하여 {{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}} 호출에 사용된 모든 좌표를 반올림해야합니다.

+ +

drawImage에서 이미지 크기를 조정하지 마라.

+ +

{{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}}에서 즉시 크기를 조정하지 말고 다양한 이미지 크기를 오프스크린(offscreen) 캔버스에 캐시하십시오.

+ +

복잡한 장면에 여러 개의 레이어 캔버스를 사용하라.

+ +

어플리케이션에서 일부 객체는 자주 이동하거나 변경해야하지만 다른 객체는 상대적으로 고정 위치에 남아야 합니다. 이런 상황에서 대응 가능한 최적화는 여러 <canvas> 엘리먼트를 사용하여 항목을 겹쳐서 만드는 것입니다.

+ +

예를 들어 상단에 UI, 중간에 게임 플레이 액션, 하단에 정적 배경이있는 게임이 있다고 가정 해 보겠습니다. 이 경우 게임을 세 개의 <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를 사용하라.

+ +

정적 배경 이미지가있는 경우 CSS {{cssxref("background")}} 속성을 사용하여 일반 {{HTMLElement("div")}} 요소에 그릴 수 있으며 캔버스 아래에 배치 할 수 있습니다. 이렇게하면 모든 틱 마다 배경을 캔버스에 렌더링 할 필요가 없어집니다.

+ +

CSS 변환(transform)을 사용하여 캔버스 크기 조정하라.

+ +

CSS 변환(transform)은 GPU를 사용하기 때문에 더 빠릅니다. 가장 좋은 경우는 캔버스를 스케일링하지 않거나, 큰 캔버스를 축소하기보다 작은 캔버스를 확대하는 것입니다.

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

투명도를 사용하지 마라.

+ +

응용 프로그램이 캔버스를 사용하고 투명 배경을 필요로하지 않는 경우 HTMLCanvasElement.getContext()를 사용하여 드로잉 컨텍스트를 만들 때 alpha 옵션을 false로 설정합니다. 이 정보는 렌더링을 최적화하기 위해 브라우저에서 내부적으로 사용할 수 있습니다.

+ +
var ctx = canvas.getContext('2d', { alpha: false });
+ +

추가 팁들

+ + + +

See also

+ + + +

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

diff --git a/files/ko/web/html/canvas/tutorial/using_images/index.html b/files/ko/web/html/canvas/tutorial/using_images/index.html new file mode 100644 index 0000000000..d9aae1c993 --- /dev/null +++ b/files/ko/web/html/canvas/tutorial/using_images/index.html @@ -0,0 +1,347 @@ +--- +title: Using images +slug: Web/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" )}}
+ +
+

지금까지 우리는 Canvas를 가지고 스스로 도형을 만들고 그 도형에 스타일 적용 해 보았습니다. 이미지를 사용 하는 기능은 {{HTMLElement("canvas")}}의 가장 흥미로운 기능중 하나입니다. 이 기능은 게임의 그래픽 배경이나 혹은 다이나믹한 사진 도음들을 위해 사용 될 수 있습니다. PNG,GIF, JPEG등 브라우저에서 지원되는 포맷형태라면 어떠한 외부 이미지라도 사용 될 수 있습니다. 같은 페이지 소스에서 다른 Canvas요소로 만들어진 이미지 또한 사용할수 있습니다!

+
+ +

이미지를 캔버스로 불러오는것은 기본적으로 두 단계를 필요로 합니다:

+ +
    +
  1. {{domxref("HTMLImageElement")}} object를 참조하거나 다른 캔버스 요소를 소스로 사용합니다. 이는 URL을 가지고 이미지를 사용 할 수 있습니다.
  2. +
  3. drawImage() function을 사용하여 캔버스에 나타난 이미지 위에 그림을 그립니다.
  4. +
+ +

이 과정이 어떻게 되는지 봅시다.

+ +

이미지 불러오기

+ +

canvas API는 아래의 데이터 타입을 이미지 소스로 사용 할 수 있습니다:

+ +
+
{{domxref("HTMLImageElement")}}
+
{{HTMLElement("img")}} element와 마찬가지로, Image() constructor를 통해 만들어진 이미지입니다.
+
+ +
+
{{domxref("SVGImageElement")}}
+
{{SVGElement("image")}} element 를 사용해 불러온 이미지입니다.
+
+ + + +
+
{{domxref("HTMLVideoElement")}}
+
HTML {{HTMLElement("video")}} 요소를 이미지 소스로 사용하여 비디오의 현재 프레임을 이미지로 불러옵니다.
+
{{domxref("HTMLCanvasElement")}}
+
다른 {{HTMLElement("canvas")}} 요소를 이미지 소스로 사용합니다.
+
+ +

이렇게 얻은 소스들은 {{domxref("CanvasImageSource")}}.를 사용하여 불러 올 수 있습니다.

+ +

다음은 캔버스에 놓인 이미지를 사용하는 여러가지 방법입니다.

+ +

같은 페이지의 이미지 사용하기

+ +

우리는 다음을 사용하여 같은 페이지에 있는 캔버스나 이미지를 참고 할 수 있습니다.

+ + + +

다른 도메인의 이미지 사용하기

+ +

Using the {{htmlattrxref("crossorigin", "img")}} attribute of an {{HTMLElement("img")}} element (reflected by the {{domxref("HTMLImageElement.crossOrigin")}} property), you can request permission to load an image from another domain for use in your call to drawImage(). If the hosting domain permits cross-domain access to the image, the image can be used in your canvas without tainting it; otherwise using the image will taint the canvas.

+ +

다른 캔버스 요소 (canvas elements) 사용하기

+ +

Just as with normal images, we access other canvas elements using either the {{domxref("document.getElementsByTagName()")}} or {{domxref("document.getElementById()")}} method. Be sure you've drawn something to the source canvas before using it in your target canvas.

+ +

One of the more practical uses of this would be to use a second canvas element as a thumbnail view of the other larger canvas.

+ +

처음부터 이미지 만들기

+ +

Another option is to create new {{domxref("HTMLImageElement")}} objects in our script. To do this, you can use the convenient Image() constructor:

+ +
var img = new Image();   // Create new img element
+img.src = 'myImage.png'; // Set source path
+
+ +

When this script gets executed, the image starts loading.

+ +

If you try to call drawImage() before the image has finished loading, it won't do anything (or, in older browsers, may even throw an exception). So you need to be sure to use the load event so you don't try this before the image has loaded:

+ +
var img = new Image();   // Create new img element
+img.addEventListener('load', function() {
+  // execute drawImage statements here
+}, false);
+img.src = 'myImage.png'; // Set source path
+
+ +

If you're only using one external image this can be a good approach, but once you need to track more than one we need to resort to something more clever. It's beyond the scope of this tutorial to look at image pre-loading tactics, but you should keep that in mind.

+ +

데이터를 사용하여 이미지 불러오기Embedding an image via data: URL

+ +

Another possible way to include images is via the data: url. Data URLs allow you to completely define an image as a Base64 encoded string of characters directly in your code.

+ +
var img = new Image();   // Create new img element
+img.src = 'data:image/gif;base64,R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==';
+
+ +

One advantage of data URLs is that the resulting image is available immediately without another round trip to the server. Another potential advantage is that it is also possible to encapsulate in one file all of your CSS, JavaScript, HTML, and images, making it more portable to other locations.

+ +

Some disadvantages of this method are that your image is not cached, and for larger images the encoded url can become quite long.

+ +

비디오 프레임 사용하기Using frames from a video

+ +

You can also use frames from a video being presented by a {{HTMLElement("video")}} element (even if the video is not visible). For example, if you have a {{HTMLElement("video")}} element with the ID "myvideo", you can do this:

+ +
function getMyVideo() {
+  var canvas = document.getElementById('canvas');
+  if (canvas.getContext) {
+    var ctx = canvas.getContext('2d');
+
+    return document.getElementById('myvideo');
+  }
+}
+
+ +

This returns the {{domxref("HTMLVideoElement")}} object for the video, which, as covered earlier, is one of the objects that can be used as a CanvasImageSource.

+ +

이미지 그리기

+ +

Once we have a reference to our source image object we can use the drawImage() method to render it to the canvas. As we will see later the drawImage() method is overloaded and has several variants. In its most basic form it looks like this:

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, x, y)")}}
+
Draws the CanvasImageSource specified by the image parameter at the coordinates (x, y).
+
+ +
+

SVG images must specify a width and height in the root <svg> element.

+
+ +

예제: 기본 선 그래프

+ +

In the following example, we will use an external image as the backdrop for a small line graph. Using backdrops can make your script considerably smaller because we can avoid the need for code to generate the background. In this example, we're only using one image, so I use the image object's load event handler to execute the drawing statements. The drawImage() method places the backdrop at the coordinate (0, 0), which is the top-left corner of the 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';
+}
+ +

The resulting graph looks like this:

+ +

{{EmbedLiveSample("Example_A_simple_line_graph", 220, 160, "https://mdn.mozillademos.org/files/206/Canvas_backdrop.png")}}

+ +

비례 크기 조정

+ +

The second variant of the drawImage() method adds two new parameters and lets us place scaled images on the canvas.

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, x, y, width, height)")}}
+
This adds the width and height parameters, which indicate the size to which to scale the image when drawing it onto the canvas.
+
+ +

예제: 이미지를 타일처럼 배치

+ +

In this example, we'll use an image as a wallpaper and repeat it several times on the canvas. This is done simply by looping and placing the scaled images at different positions. In the code below, the first for loop iterates over the rows. The second for loop iterates over the columns. The image is scaled to one third of its original size, which is 50x38 pixels.

+ +
+

Note: Images can become blurry when scaling up or grainy if they're scaled down too much. Scaling is probably best not done if you've got some text in it which needs to remain legible.

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

The resulting canvas looks like this:

+ +

{{EmbedLiveSample("Example_Tiling_an_image", 160, 160, "https://mdn.mozillademos.org/files/251/Canvas_scale_image.png")}}

+ +

이미지 자르기

+ +

The third and last variant of the drawImage() method has eight parameters in addition to the image source. It lets us cut out a section of the source image, then scale and draw it on our canvas.

+ +
+
{{domxref("CanvasRenderingContext2D.drawImage", "drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)")}}
+
Given an image, this function takes the area of the source image specified by the rectangle whose top-left corner is (sx, sy) and whose width and height are sWidth and sHeight and draws it into the canvas, placing it on the canvas at (dx, dy) and scaling it to the size specified by dWidth and dHeight.
+
+ +

To really understand what this does, it may help to look at the image to the right. The first four parameters define the location and size of the slice on the source image. The last four parameters define the rectangle into which to draw the image on the destination canvas.

+ +

Slicing can be a useful tool when you want to make compositions. You could have all elements in a single image file and use this method to composite a complete drawing. For instance, if you want to make a chart you could have a PNG image containing all the necessary text in a single file and depending on your data could change the scale of your chart fairly easily. Another advantage is that you don't need to load every image individually, which can improve load performance.

+ +

예제: 이미지 프레임 넣기

+ +

In this example, we'll use the same rhino as in the previous example, but we'll slice out its head and composite it into a picture frame. The picture frame image is a 24-bit PNG which includes a drop shadow. Because 24-bit PNG images include a full 8-bit alpha channel, unlike GIF and 8-bit PNG images, it can be placed onto any background without worrying about a matte color.

+ +
<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');
+
+  // Draw slice
+  ctx.drawImage(document.getElementById('source'),
+                33, 71, 104, 124, 21, 20, 87, 104);
+
+  // Draw frame
+  ctx.drawImage(document.getElementById('frame'), 0, 0);
+}
+ +

We took a different approach to loading the images this time. Instead of loading them by creating new {{domxref("HTMLImageElement")}} objects, we included them as {{HTMLElement("img")}} tags directly in our HTML source and retrieved the images from those. The images are hidden from output by setting the CSS property {{cssxref("display")}} to none for those images.

+ +

{{EmbedLiveSample("Example_Framing_an_image", 160, 160, "https://mdn.mozillademos.org/files/226/Canvas_drawimage2.jpg")}}

+ +

The script itself is very simple. Each {{HTMLElement("img")}} is assigned an ID attribute, which makes them easy to select using {{domxref("document.getElementById()")}}. We then simply use drawImage() to slice the rhino out of the first image and scale him onto the canvas, then draw the frame on top using a second drawImage() call.

+ +

아트 갤러리 예제

+ +

In the final example of this chapter, we'll build a little art gallery. The gallery consists of a table containing several images. When the page is loaded, a {{HTMLElement("canvas")}}  element is inserted for each image and a frame is drawn around it.

+ +

In this case, every image has a fixed width and height, as does the frame that's drawn around them. You could enhance the script so that it uses the image's width and height to make the frame fit perfectly around it.

+ +

The code below should be self-explanatory. We loop through the {{domxref("document.images")}} container and add new canvas elements accordingly. Probably the only thing to note, for those not so familiar with the DOM, is the use of the {{domxref("Node.insertBefore")}} method. insertBefore() is a method of the parent node (a table cell) of the element (the image) before which we want to insert our new node (the canvas element).

+ +
<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>
+
+ +

And here's some CSS to make things look nice:

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

Tying it all together is the JavaScript to draw our framed images:

+ +
function draw() {
+
+  // Loop through all images
+  for (var i = 0; i < document.images.length; i++) {
+
+    // Don't add a canvas for the frame image
+    if (document.images[i].getAttribute('id') != 'frame') {
+
+      // Create canvas element
+      canvas = document.createElement('canvas');
+      canvas.setAttribute('width', 132);
+      canvas.setAttribute('height', 150);
+
+      // Insert before the image
+      document.images[i].parentNode.insertBefore(canvas,document.images[i]);
+
+      ctx = canvas.getContext('2d');
+
+      // Draw image to canvas
+      ctx.drawImage(document.images[i], 15, 20);
+
+      // Add frame
+      ctx.drawImage(document.getElementById('frame'), 0, 0);
+    }
+  }
+}
+ +

{{EmbedLiveSample("Art_gallery_example", 725, 400)}}

+ +

이미지 비율 습성(scaling behavior) 제어하기

+ +

As mentioned previously, scaling images can result in fuzzy or blocky artifacts due to the scaling process. You can use the drawing context's {{domxref("CanvasRenderingContext2D.imageSmoothingEnabled", "imageSmoothingEnabled")}} property to control the use of image smoothing algorithms when scaling images within your context. By default, this is true, meaning images will be smoothed when scaled. You can disable this feature like this:

+ +
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/ko/web/html/canvas/tutorial/\353\263\200\355\230\225/index.html" "b/files/ko/web/html/canvas/tutorial/\353\263\200\355\230\225/index.html" new file mode 100644 index 0000000000..b93747b581 --- /dev/null +++ "b/files/ko/web/html/canvas/tutorial/\353\263\200\355\230\225/index.html" @@ -0,0 +1,286 @@ +--- +title: 변형 (transformations) +slug: Web/HTML/Canvas/Tutorial/변형 +tags: + - CSS + - HTML + - 이동 + - 축소 + - 캔버스 + - 크기변형 + - 트랜스폼 + - 확대 +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의 크기를 바꾸기만 했습니다. Transformation(변형)에는 그리드를 원점에서 다른 위치로 옮기고, 회전하며, 확대·축소까지 하는 더 강력한 방법들이 있습니다.
+ +

상태(state)의 저장과 복원

+ +

변형(transformation) 메소드을 살펴보기 전에 두 가지 다른 메소드를 보도록 하지요. 일단 여러분이 더 복잡한 그림(drawings)을 그리기 시작하면 반드시 있어야 하는 메소드들입니다.

+ +
+
{{domxref("CanvasRenderingContext2D.save", "save()")}}
+
canvas의 모든 상태를 저장합니다.
+
{{domxref("CanvasRenderingContext2D.restore", "restore()")}}
+
가장 최근에 저장된 canvas 상태를 복원합니다.
+
+ +

Canvas 상태는 스택(stack)에 쌓입니다. save() 메소드가 호출될 때마다 현재 drawing 상태가 스택 위로 푸시됩니다. drawing 상태는 다음과 같이 이루어집니다.

+ + + +

여러분은 원하는 만큼 save() 메소드를 많이 호출할 수 있습니다. restore() 메소드를 호출할 때마다 마지막으로 저장된 상태가 스택에서 튀어나와 저장된 설정들을 모두 복원시킵니다.

+ +

save와 restore canvas 상태(state) 예제

+ +

사각형 세트를 연이어 그려서 drawing 상태를 가진 스택이 어떻게 기능하는지를 이 예제에서 설명하고자 합니다.

+ +
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);   // 복원된 설정으로 사각형 그리기
+}
+ + + +

첫 단계로 기본 설정으로 커다란 사각형을 그립니다. 그다음에는 이 상태를 저장하고 fill color를 바꿉니다. 그런 후에 두 번째이자 크기가 더 작은 파란 사각형을 그리고 그 상태를 저장합니다. 다시 한번 일부 drawing 설정을 바꾸고 세 번째 반투명한 흰 사각형을 그립니다. 

+ +

여기까지는 이전 섹션에서 했던 작업과 매우 유사합니다. 하지만 일단 첫 번째 restore() 문을 호출하면 스택에서 맨 위의 drawing 상태가 지워지고 설정이 복원됩니다. 만일 save()로 저장하지 않았다면, 이전 상태로 되돌리기 위해 fill color와 투명도를 일일이 바꿔주어야 했을 것입니다. 두 속성이라서 간단했을 테지만 그보다 더 많았으면 코드가 급속히 길어졌겠지요. 

+ +

두 번째 restore()문이 호출될 때, 초기 상태( 처음으로 save를 호출하기 전에 설정한 상태)가 복원되고 마지막 사각형은 한번 더 검게 그려집니다.

+ +

{{EmbedLiveSample("A_save_and_restore_canvas_state_example", "180", "180", "https://mdn.mozillademos.org/files/249/Canvas_savestate.png")}}

+ +

이동(translating)

+ +

우리가 살펴볼 첫 번째 변형 메소드는 translate()입니다.  이 메소드는 그리드에서 canvas를 원점에서 다른 점으로 옮기는 데 사용됩니다. 

+ +
+
{{domxref("CanvasRenderingContext2D.translate", "translate(x, y)")}}
+
그리드에서 canvas와 그 원점을 이동합니다. x는 이동시킬 수평 거리를 가리키고, y는 그리드에서 수직으로 얼마나 멀리 떨어지는지를 표시합니다. 
+
+ +

변형하기 전에 canvas 상태를 저장하는 것이 좋습니다. 대다수의 경우, 원래 상태로 되돌리려고 역이동(reverse translation)을 시키는 것보다 restore 메소드를 호출하는 것이 더욱 간편합니다. 게다가 루프(loop) 안에서 이동하는 거라면 canvas 상태를 저장하고 복원하지 마세요. canvas 모서리 밖에서 그려지는 바람에 drawing의 일부를 잃어버리게 될지 모릅니다. 

+ +

translate 예제

+ +

이 예제에서 canvas 원점의 이동에 관한 좋은 점을 일부 보여드리겠습니다. translate() 메소드를 쓰지 않으면 모든 사각형은 같은 위치 (0, 0)에 그려집니다. 또한, translate() 메소드는 사각형을 fillRect() function에서 좌표를 일일이 적으며 바꾸지 않아도 어디에나 위치할 수 있게 해줍니다. 이렇게 하면 이해하고 사용하기가 좀 더 쉽습니다. 

+ +

 draw() function에서 두 개의 루프(loops)를 이용해 fillRect() function을 아홉 번 호출합니다. 루프마다 canvas가 이동하고 사각형이 그려지며, canvas는 원래 상태로 되돌아 갑니다. fillRect()로의 호출이 translate()에 의지해 drawing 위치를 바꾸는데 어떻게 매번 같은 좌표를 사용하는지 눈여겨 보세요.

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

+ +

회전(rotating)

+ +

두 번째 변형 메소드는 rotate()입니다. canvas를 현재의 원점 둘레로 회전하는 데 사용합니다.

+ +
+
{{domxref("CanvasRenderingContext2D.rotate", "rotate(angle)")}}
+
canvas를 현재 원점을 기준으로 라디안의 angle 숫자만큼 시계방향으로 회전시킵니다.
+
+ +

회전의 중심점은 언제나 canvas 원점입니다. 중심점을 바꾸려면 translate() 메소드를 써서 canvas를 이동해야 합니다.

+ +

rotate 예제

+ +

이 예제는 사각형을 canvas 원점에서 먼저 회전하고 그다음에 translate()의 도움을 받아 사각형 자체의 중심에서 회전하는 데 rotate()를 사용합니다.

+ +
+

주의: 각도의 단위는 도(degree)가 아닌 라디안(radian)입니다.   변환하려면 radians = (Math.PI/180)*degrees.를 사용합니다.

+
+ +
function draw() {
+  var ctx = document.getElementById('canvas').getContext('2d');
+
+  // 좌측 사각형, canvas 원점에서 회전하기
+  ctx.save();
+  // 파란 사각형
+  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();
+
+  // 우측 사각형, 사각형 중심에서 회전하기
+  // 파란 사각형 그리기
+  ctx.fillStyle = '#0095DD';
+  ctx.fillRect(150, 30, 100, 100);
+
+  ctx.translate(200, 80); // 사각형 중심으로 이동하기
+                          // x = x + 0.5 * width
+                          // y = y + 0.5 * height
+  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")}}

+ +

확대·축소(scaling)

+ +

다음 변형 메소드는 확대·축소(scaling)입니다. canvas 그리드에서 단위(units)를 키우거나 줄이는 데 사용합니다. 이는 벡터 모양과 비트맵(bitmaps) 요소를 축소하거나 확대해서 그리는 데 사용될 수 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.scale", "scale(x, y)")}}
+
canvas 단위를 수평으로 x만큼, 수직으로 y만큼 크기를 확대·축소합니다. 둘의 매개 변수는 실수입니다. 1.0보다 작은 값이면 단위의 크기를 축소하고, 1.0보다 큰 값이면 단위의 크기를 확대합니다. 값이 1.0이면 단위의 크기는 그대로입니다.
+
+ +

음수를 이용해서 축을 대칭 시킬 수 있습니다(가령 translate(0,canvas.height); scale(1,-1);로 쓰는 것처럼 말이죠. 좌측 하단 모서리에 있는 원점을 이용한, 잘 알려진 카르테시안 좌표계(Cartesian coordinate)인 것이지요.

+ +

기본적으로 canvas에서 하나의 단위는 정확히 1픽셀입니다. 예를 들어 0.5라는 확대·축소 비율을 적용한다면, 결과로 나오는 단위는 0.5 픽셀이 될 것이고, 고로 모양도 절반 크기로 그려질 것입니다. 이런 방식으로 크기 비율을 2.0으로 잡으면 단위 크기가 확대되어 하나의 단위는 이제 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")}}

+ +

변형(transforms)

+ +

마지막으로, 다음의 변형(transform) 메소드들은 변환 행렬(transformation matrix)로 변경할 사항을 즉시 적용할 수 있습니다.

+ +
+
{{domxref("CanvasRenderingContext2D.transform", "transform(a, b, c, d, e, f)")}}
+
인수(arguments)에 표시된 행렬을 이용해 현재 변환 행렬을 곱합니다. 변환 행렬은 다음과 같이 작성됩니다. 
+ [acebdf001]\left[ \begin{array}{ccc} a & c & e \\ b & d & f \\ 0 & 0 & 1 \end{array} \right]
+
+ +
+
만일 인수 중에 Infinity가 있다면, 변환 행렬은 예외 처리하는 메소드 대신에 반드시 infinite로 표시되어야 합니다.
+
+ +

이 function의 매개 변수들은 다음과 같습니다.

+ +
+
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); 호출과 같습니다.
+
+ +

transform과 setTransform 예제

+ +
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/ko/web/html/cors_enabled_image/index.html b/files/ko/web/html/cors_enabled_image/index.html new file mode 100644 index 0000000000..5d3dfae121 --- /dev/null +++ b/files/ko/web/html/cors_enabled_image/index.html @@ -0,0 +1,112 @@ +--- +title: 교차 출처 이미지와 캔버스 허용하기 +slug: Web/HTML/CORS_enabled_image +translation_of: Web/HTML/CORS_enabled_image +--- +

HTML은 이미지 처리를 위해 {{Glossary("CORS")}} header를 포함하고 있는 {{ htmlattrxref("crossorigin", "img") }} 속성을 제공합니다. 이는 {{ HTMLElement("img") }} 요소에서 정의된, 외부 origin으로 부터 가져오는 이미지가 {{HTMLElement("canvas")}}에서 사용할 수 있도록 해줍니다. 마치 현재 origin에서 가져온 것처럼 말입니다

+ +

crossorigin 속성이 어떻게 사용되는지 자세히 알고 싶다면, CORS settings attributes 를 참고하세요.

+ +

보안과 오염된 canvas들

+ +

다른 호스트들에 있는 이미지나 비디오를 포함한 canvas 비트맵의 픽셀들은 다양한 출처로 부터 가져오기 때문에, 보안과 관련된 문제를 피할 수 없습니다.

+ +

CORS를 통하지 않고, 다른 origin으로 부터 가져온 데이터들은 canvas에 그려지는 즉시 canvas는 오염됩니다. 오염된 canvas는 더 이상 안전하지 않은 것으로 여겨지고, canvas 이미지에서 데이터를 가져오려는 어떤 시도든 exception이 발생합니다.

+ +

만약 외부 출처 콘텐츠가 HTML {{HTMLElement("img")}} 또는 SVG {{SVGElement("svg")}} 요소라면, canvas의 콘텐츠를 가져오려는 시도는 허용되지 않습니다.

+ +

만약 외부 출처 콘텐츠가 {{domxref("HTMLCanvasElement")}} 또는 {{domxref("ImageBitMap")}} 로부터 오는 이미지이고, 이미지의 source가 동일 출처 원칙과 맞지 않는다면 canvas의 콘텐츠를 읽으려는 시도는 막힙니다.

+ +

Calling any of the following on a tainted canvas will result in an error:

+ + + +

Attempting any of these when the canvas is tainted will cause a SecurityError to be thrown. This protects users from having private data exposed by using images to pull information from remote web sites without permission.

+ +

Storing an image from a foreign origin

+ +

In this example, we wish to permit images from a foreign origin to be retrieved and saved to local storage. Implementing this requires configuring the server as well as writing code for the web site itself.

+ +

Web server configuration

+ +

The first thing we need is a server that's configured to host images with the {{HTTPHeader("Access-Control-Allow-Origin")}} header configured to permit cross-origin access to image files.

+ +

Let's assume we're serving our site using Apache. Consider the HTML5 Boilerplate Apache server configuration file for CORS images, shown below:

+ +
<IfModule mod_setenvif.c>
+  <IfModule mod_headers.c>
+    <FilesMatch "\.(bmp|cur|gif|ico|jpe?g|png|svgz?|webp)$">
+      SetEnvIf Origin ":" IS_CORS
+      Header set Access-Control-Allow-Origin "*" env=IS_CORS
+    </FilesMatch>
+  </IfModule>
+</IfModule>
+ +

In short, this configures the server to allow graphic files (those with the extensions ".bmp", ".cur", ".gif", ".ico", ".jpg", ".jpeg", ".png", ".svg", ".svgz", and ".webp") to be accessed cross-origin from anywhere on the internet.

+ +

Implementing the save feature

+ +

Now that the server has been configured to allow retrieval of the images cross-origin, we can write the code that allows the user to save them to local local storage, just as if they were being served from the same domain the code is running on.

+ +

The key is to use the {{htmlattrxref("crossorigin")}} attribute by setting {{domxref("HTMLImageElement.crossOrigin", "crossOrigin")}} on the {{domxref("HTMLImageElement")}} into which the image will be loaded. This tells the browser to request cross-origin access when trying to download the image data.

+ +

Starting the download

+ +

The code that starts the download (say, when the user clicks a "Download" button), looks like this:

+ +
function startDownload() {
+  let imageURL = "https://cdn.glitch.com/4c9ebeb9-8b9a-4adc-ad0a-238d9ae00bb5%2Fmdn_logo-only_color.svg?1535749917189";
+
+  downloadedImg = new Image;
+  downloadedImg.crossOrigin = "Anonymous";
+  downloadedImg.addEventListener("load", imageReceived, false);
+  downloadedImg.src = imageURL;
+}
+ +

We're using a hard-coded URL here (imageURL), but that could easily come from anywhere. To begin downloading the image, we create a new {{domxref("HTMLImageElement")}} object by using the {{domxref("HTMLImageElement.Image", "Image()")}} constructor. The image is then configured to allow cross-origin downloading by setting its crossOrigin attribute to "Anonymous" (that is, allow non-authenticated downloading of the image cross-origin). An event listener is added for the {{event("load")}} event being fired on the image element, which means the image data has been received.

+ +

Finally, the image's {{domxref("HTMLImageElement.src", "src")}} attribute is set to the URL of the image to download; this triggers the download to begin.

+ +

Receiving and saving the image

+ +

The code that handles the newly-downloaded image is found in the imageReceived() method:

+ +
function imageReceived() {
+  let canvas = document.createElement("canvas");
+  let context = canvas.getContext("2d");
+
+  canvas.width = downloadedImg.width;
+  canvas.height = downloadedImg.height;
+
+  context.drawImage(downloadedImg, 0, 0);
+  imageBox.appendChild(canvas);
+
+  try {
+    localStorage.setItem("saved-image-example", canvas.toDataURL("image/png"));
+  }
+  catch(err) {
+    console.log("Error: " + err);
+  }
+}
+ +

imageReceived() is called to handle the "load" event on the HTMLImageElement that receives the downloaded image. This event is triggered once the downloaded data is all available. It begins by creating a new {{HTMLElement("canvas")}} element that we'll use to convert the image into a data URL, and by getting access to the canvas's 2D drawing context ({{domxref("CanvasRenderingContext2D")}}) in the variable context.

+ +

The canvas's size is adjusted to match the received image, then the image is drawn into the canvas using {{domxref("CanvasRenderingContext2D.drawImage", "drawImage()")}}. The canvas is then inserted into the document so the image is visible.

+ +

Now it's time to actually save the image locally. To do this, we use the Web Storage API's local storage mechanism, which is accessed through the {{domxref("Window.localStorage", "localStorage")}} global. The canvas method {{domxref("HTMLCanvasElement.toDataURL", "toDataURL()")}} is used to convert the image into a data:// URL representing a PNG image, which is then saved into local storage using {{domxref("Storage.setItem", "setItem()")}}.

+ +

You can try out or remix this example on Glitch.

+ +

See also

+ + + +
{{QuickLinksWithSubpages("/en-US/docs/Web/HTML/")}}
diff --git a/files/ko/web/html/element/a/index.html b/files/ko/web/html/element/a/index.html new file mode 100644 index 0000000000..680f85b9b6 --- /dev/null +++ b/files/ko/web/html/element/a/index.html @@ -0,0 +1,489 @@ +--- +title: +slug: Web/HTML/Element/a +tags: + - Element + - HTML + - HTML text-level semantics + - Reference + - Web +translation_of: Web/HTML/Element/a +--- +
{{HTMLRef}}
+ +

HTML <a> 요소(앵커 요소)는 {{htmlattrxref("href", "a")}} 특성을 통해 다른 페이지나 같은 페이지의 어느 위치, 파일, 이메일 주소와 그 외 다른 URL로 연결할 수 있는 하이퍼링크를 만듭니다. <a> 안의 콘텐츠는 링크 목적지의 설명을 나타내야 합니다.

+ +
{{EmbedInteractiveExample("pages/tabbed/a.html")}}
+ + + +

특성

+ +

이 요소는 전역 특성을 포함합니다.

+ +
+
{{htmlattrdef("download")}}
+
링크로 이동하는 대신 사용자에게 URL을 저장할지 물어봅니다. 값을 지정할 수도 있고, 지정하지 않을 수도 있습니다. +
    +
  • 값이 없으면 파일 이름과 확장자는 브라우저가 다양한 인자로부터 생성해 제안합니다. +
      +
    • {{HTTPHeader("Content-Disposition")}} HTTP 헤더
    • +
    • URL 경로의 마지막 조각
    • +
    • {{glossary("MIME type", "미디어 유형")}} ({{HTTPHeader("Content-Type")}} 헤더, data: URL의 시작 부분, blob: URL의 {{domxref("Blob.type")}}에서 알아냄)
    • +
    +
  • +
  • 값을 지정하면 저장할 때의 파일 이름으로서 제안합니다. /\ 문자는_로 변환합니다. 파일시스템에서 다른 문자도 제한할 수 있으므로, 필요한 경우 브라우저가 추가로 이름을 조정할 수 있습니다.
  • +
+ +
참고: + +
    +
  • download동일 출처 URLblob:, data: 스킴에서만 작동합니다.
  • +
  • Content-Dispositionfilenamedownload와 다를 땐 헤더가 우선권을 가집니다. (Content-Disposition: inline일 때, Firefox는 헤더를 우선하고 Chrome은 download를 우선합니다.)
  • +
+
+
+
{{HTMLAttrDef("href")}}
+
+

하이퍼링크가 가리키는 URL. 링크는 HTTP 기반 URL일 필요는 없고, 브라우저가 지원하는 모든 URL 스킴을 사용할 수 있습니다.

+ +
    +
  • 페이지 구획을 가리키는 프래그먼트 URL
  • +
  • 미디어 파일 일부를 가리키는 미디어 프래그먼트
  • +
  • tel: URL을 사용하는 전화번호
  • +
  • mailto: URL을 사용하는 이메일 주소
  • +
  • 웹 브라우저는 다른 URL 스킴을 지원하지 않지만, 웹사이트는 {{domxref("Navigator.registerProtocolHandler()")}}를 통해 지원할 수 있습니다.
  • +
+
+
{{htmlattrdef("hreflang")}}
+
링크 URL의 인간 언어에 대한 힌트. 특별한 내장 기능은 없습니다. 가능한 값은 전역 lang 특성과 동일합니다.
+
{{HTMLAttrDef("ping")}}
+
하나의 스페이스로 구분하는 URL 목록. 링크를 클릭해 따라갈 경우, 브라우저가 URL 각각에 {{HTTPMethod("POST")}} 요청을 전송합니다. 대개 추적 용도로 사용합니다.
+
{{htmlattrdef("referrerpolicy")}} {{experimental_inline}}
+
URL을 가져올 때 사용할 리퍼러. {{httpheader("Referrer-Policy")}} 문서에서 가능한 값과 효과를 확인하세요.
+
{{htmlattrdef("rel")}}
+
하나의 스페이스로 구분하는, 연결한 URL과의 관계를 나타내는 링크 유형 목록.
+
{{htmlattrdef("target")}}
+
링크한 URL을 표시할 위치. 가능한 값은 브라우징 맥락으로, 즉 탭, 창, <iframe>의 이름이나 특정 키워드입니다. 다음 키워드는 특별한 뜻을 가지고 있습니다. +
    +
  • _self: URL을 현재 브라우징 맥락에 표시합니다. 기본값.
  • +
  • _blank: URL을 새로운 브라우징 맥락에 표시합니다. 보통 새 탭이지만, 사용자가 브라우저 설정을 통해 새 창으로 바꿀 수 있습니다.
  • +
  • _parent: URL을 현재 브라우징 맥락의 부모에 표시합니다. 부모가 존재하지 않으면 _self와 동일하게 행동합니다.
  • +
  • _top: URL을 최상단 브라우징 맥락(현재 맥락의 부모면서 자신의 부모가 존재하지 않는, 제일 높은 맥락)에 표시합니다. 부모가 존재하지 않으면 _self와 동일하게 행동합니다.
  • +
+ +
+

참고: target을 사용할 때, rel="noreferrer"를 추가해 window.opener API의 악의적인 사용을 방지하는걸 고려하세요.

+
+ +
+

참고: 최근의 브라우저(Firefox 79+ 등)에서는 target="_blank"를 지정하면 rel="noopener"를 적용한 것과 같은 동작을 합니다.

+
+
+
{{htmlattrdef("type")}}
+
링크 URL의 {{Glossary("MIME type")}}에 대한 힌트. 특별한 내장 기능은 없습니다.
+
+ + + +

속성

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
콘텐츠 카테고리플로우 콘텐츠, 구문 콘텐츠, 대화형 컨텐츠, 뚜렷한 콘텐츠.
가능한 콘텐츠투명함. 플로우 콘텐츠(대화형 콘텐츠 제외) 또는 구문 콘텐츠.
태그 생략{{no_tag_omission}}
가능한 부모 요소 +

구문 콘텐츠를 허용하는 모든 요소, 또는 플로우 콘텐츠를 허용하는 모든 요소. 단, 다른 <a> 요소는 불가능.

+
암시적 ARIA 역할href 특성이 존재하면 {{ariarole("link")}}, 그 외의 경우 대응하는 역할 없음
가능한 ARIA 역할 +

href 특성이 존재할 경우,

+ +
    +
  • {{ARIARole("button")}}
  • +
  • {{ARIARole("checkbox")}}
  • +
  • {{ARIARole("menuitem")}}
  • +
  • {{ARIARole("menuitemcheckbox")}}
  • +
  • {{ARIARole("menuitemradio")}}
  • +
  • {{ARIARole("option")}}
  • +
  • {{ARIARole("radio")}}
  • +
  • {{ARIARole("switch")}}
  • +
  • {{ARIARole("tab")}}
  • +
  • {{ARIARole("treeitem")}}
  • +
+ +

href 특성이 존재하지 않을 경우,

+ +
    +
  • 모두
  • +
+
DOM 인터페이스{{domxref("HTMLAnchorElement")}}
+ +

예제

+ +

절대 URL로 연결

+ +

HTML

+ +
<a href="https://www.mozilla.com">
+  Mozilla
+</a>
+ +

결과

+ +

{{EmbedLiveSample('절대_URL로_연결')}}

+ +

상대 URL로 연결

+ +

HTML

+ +
<a href="//example.com">Scheme-relative URL</a>
+<a href="/en-US/docs/Web/HTML">Origin-relative URL</a>
+<a href="./p">Directory-relative URL</a>
+
+ + + +

결과

+ +

{{EmbedLiveSample('상대_URL로_연결')}}

+ +

같은 페이지의 요소로 연결

+ +
<!-- <a> 요소로 아래의 구획에 연결 -->
+<p><a href="#Section_further_down">
+  아래 제목으로 건너뛰기
+</a></p>
+
+<!-- 링크가 향할 제목 -->
+<h2 id="Section_further_down">아래의 제목</h2>
+
+ +
+

참고: href="#top"이나 빈 프래그먼트(href="#")를 사용하면 현재 페이지의 최상단으로 이동하는 링크를 생성할 수 있습니다. HTML 명세를 확인하세요.

+
+ +

이메일 주소로 연결

+ +

사용자의 이메일 프로그램을 통해 새로운 메일을 보낼 수 있는 링크를 생성하려면 mailto: 스킴을 사용하세요.

+ +
<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>
+ +

제목과 본문 포함 등, mailto: URL에 관한 자세한 내용은 이메일 링크와 {{RFC(6068)}}을 참고하세요.

+ +

전화번호로 연결

+ + + +
<a href="tel:+49.157.0156">+49 157 0156</a>
+<a href="tel:+1(555)5309">(555) 5309</a>
+ +

tel: 링크는 장치의 능력에 따라 행동이 바뀝니다.

+ + + +

tel: URL의 구문, 추가 기능, 그 외 더 자세한 정보는 {{RFC(3966)}}을 참고하세요.

+ +

download 특성으로 <canvas>를 PNG로 저장하기

+ +

{{htmlattrxref("download", "a")}} 특성과 data: URL을 사용해 {{HTMLElement("canvas")}} 요소의 콘텐츠를 이미지로 저장할 수 있습니다.

+ +

저장 링크를 가진 그림판 예제

+ +
HTML
+ +
<p>마우스 드래그로 그림을 그려보세요.
+  <a href="" download="my_painting.png">다운로드</a>
+</p>
+
+<canvas width="300" height="300"></canvas>
+
+ +
CSS
+ +
html {
+  font-family: sans-serif;
+}
+canvas {
+  background: #fff;
+  border: 1px dashed;
+}
+a {
+  display: inline-block;
+  background: #69c;
+  color: #fff;
+  padding: 5px 10px;
+}
+ +
JavaScript
+ +
var canvas = document.querySelector('canvas'),
+    c = canvas.getContext('2d');
+c.fillStyle = 'hotpink';
+
+function draw(x, y) {
+  if (isDrawing) {
+    c.beginPath();
+    c.arc(x, y, 10, 0, Math.PI*2);
+    c.closePath();
+    c.fill();
+  }
+}
+
+canvas.addEventListener('mousemove', event =>
+  draw(event.offsetX, event.offsetY)
+);
+canvas.addEventListener('mousedown', () => isDrawing = true);
+canvas.addEventListener('mouseup', () => isDrawing = false);
+
+document.querySelector('a').addEventListener('click', event =>
+  event.target.href = canvas.toDataURL()
+);
+
+ +
결과
+ +

{{EmbedLiveSample('저장_링크를_가진_그림판_예제', '100%', '400')}}

+ +

보안과 개인정보

+ +

<a> 요소는 사용자의 보안과 개인정보에 중요한 영향을 줄 수 있습니다. Referer 헤더: 개인정보와 보안 고려사항 문서에서 자세한 내용을 알아보세요.

+ +

target="_blank"rel="noreferrer"rel="noopener" 없이 사용하면 웹사이트가 {{domxref("Window.opener", "window.opener")}} API 악용 공격에 취약해집니다. (취약점 설명) 다만, 최근 브라우저(Firefox 79+ 등)는 target="_blank"를 지정하면 임의로 rel="noopener" 설정과 동일한 보호 수준을 적용합니다.

+ +

접근성

+ +

강한 링크 텍스트

+ +

링크 안의 콘텐츠는, 맥락에서 벗어나더라도 링크가 향하는 곳을 설명해야 합니다.

+ +

접근성 떨어지는 약한 링크 텍스트

+ +

심각하게 흔한 실수는 "여기를 클릭"이나 "여기"라는 단어에 링크를 한다는 것입니다.

+ +
<p>
+  저희의 제품을 더 알아보시려면 <a href="/products">여기</a>를 클릭하세요.
+</p>
+
+ +

강한 링크 텍스트

+ +

다행히도 쉽게 수정할 수 있는 데다가, 접근성이 떨어지는 버전보다 더 짧습니다!

+ +
<p>
+  저희의 <a href="/products">제품을 더 알아보세요</a>.
+</p>
+ +

접근성 보조 기술은 페이지 안의 모든 링크를 나열하는 단축키가 있습니다. 그러나 강한 링크 텍스트가 보조 기술 사용자에게만 도움을 주는 것은 아닙니다. 모든 링크 나열 단축키는 시각적 사용자가 페이지를 빠르게 훑는 것을 흉내 내는 것이기 때문입니다.

+ +

onclick 이벤트

+ +

앵커 요소의 href#이나 javascript:void(0)으로 지정해 페이지 새로고침을 막고, click 이벤트 처리기를 등록해서 가짜 버튼을 만드는 방식으로 남용하는 경우가 많습니다.

+ +

이런 가짜 href 값은 링크를 복사하거나 드래그할 때, 링크를 새 탭이나 새 창에서 열 때, 즐겨찾기에 추가할 때와 JavaScript를 불러오고 있거나 스크립트 오류가 발생했을 때, 아니면 비활성화했을 때 예측하지 못한 동작을 유발합니다. 또한 스크린 리더 등 보조 기술에도 잘못된 의미를 전달합니다.

+ +

대신 {{HTMLElement("button")}}을 사용하세요. 하이퍼링크는 진짜 URL로의 탐색 용도로만 사용해야 합니다.

+ +

외부 링크와 비 HTML 리소스 링크

+ +

target="_blank"로 인해 새 탭/창을 여는 링크와, 파일을 다운로드하는 링크는, 링크를 클릭했을 때 무슨 일이 발생할건지 명시해야 합니다.

+ +

시력이 나쁘거나 스크린 리더로 탐색하는 사용자, 혹은 지각 능력이 낮은 사용자는 예상하지 못한 상황에서 새 탭, 새 창, 다른 앱이 켜지는 순간 혼란스러울 수 있습니다. 오래된 스크린 리더는 이런 상황을 아예 알려주지 못할 수도 있습니다.

+ +

새로운 탭/창을 여는 링크

+ +
<a target="_blank" href="https://ko.wikipedia.org">
+  위키백과 (새 탭에서 열림)
+</a>
+
+ +

비 HTML 리소스 링크

+ +
<a href="2017-annual-report.ppt">
+  2017 연간 보고서 (PowerPoint)
+</a>
+
+ +

아이콘을 사용해 링크의 행동을 강조할 땐 {{HTMLAttrxRef("alt", "img", "대체 텍스트", 1)}}를 꼭 지정하세요.

+ +
<a target="_blank" href="https://ko.wikipedia.org">
+  위키백과
+  <img alt="(새 탭에서 열림)" src="newtab.svg">
+</a>
+
+<a href="2017-annual-report.ppt">
+  2017 연간 보고서
+  <img alt="(PowerPoint 파일)" src="ppt-icon.svg">
+</a>
+ + + +

건너뛰기 링크

+ +

건너뛰기 링크(skip link)는 {{HTMLElement("body")}} 콘텐츠에서 가능한 앞쪽에 배치하는 링크로, 페이지의 주요 콘텐츠 시작점을 가리킵니다. 건너뛰기 링크는 보통 포커스 전까지 숨겨집니다.

+ +
<body>
+  <a href="#content">내용으로 건너뛰기</a>
+
+  <header>
+    …
+  </header>
+
+  <main id="content"> <!-- 여기로 건너뜀 -->
+
+ +
.skip-link {
+  position: absolute;
+  top: -3em;
+  background: #fff;
+}
+.skip-link:focus {
+  top: 0;
+}
+ +

건너뛰기 링크는 헤더 내비게이션과 같이 여러 페이지에서 반복되는 콘텐츠를 키보드 사용자가 쉽게 생략할 수 있도록 도와줍니다.

+ +

건너뛰기 링크는 스위치 조작, 음성 명령, 마우스 스틱/헤드 완드처럼 반복 콘텐츠를 건너뛰기 힘든 보조 기술 사용자에게 큰 도움이 됩니다.

+ + + +

크기와 간격

+ +

크기

+ +

링크와 같은 대화형 요소는 상호작용하기 충분한 크기의 활성화 영역을 가져야 합니다. 충분한 크기는 운동 조절 장애를 가진 사용자와, 터치스크린처럼 정확하지 않은 입력 도구 사용자처럼 다양한 사람을 돕습니다. 최소 44x44의 CSS 픽셀 크기를 권고합니다.

+ +

산문 내의 텍스트로만 이루어진 링크는 위 규칙에서 제외할 수 있지만, 그래도 활성화하기 쉬운 크기를 확보하는 것이 좋습니다.

+ + + +

간격

+ +

링크와 같은 대화형 요소 다수를 시각적으로 가까이 배치할 땐 서로를 분리하는 공간을 둬야 합니다. 간격은 운동 조절 장애를 가진 사용자가 원하지 않는 상호작용을 하는걸 방지할 수 있습니다.

+ +

간격은 {{CSSxRef("margin")}}과 같은 CSS 속성으로 설정할 수 있습니다.

+ + + +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("Referrer Policy", "#referrer-policy-delivery-referrer-attribute", "referrer attribute")}}{{Spec2("Referrer Policy")}}Added the referrerattribute.
{{SpecName("HTML WHATWG", "text-level-semantics.html#the-a-element", "<a>")}}{{Spec2("HTML WHATWG")}}
{{SpecName("HTML5 W3C", "text-level-semantics.html#the-a-element", "<a>")}}{{Spec2("HTML5 W3C")}}
{{SpecName("HTML4.01", "struct/links.html#h-12.2", "<a>")}}{{Spec2("HTML4.01")}}
+ +

브라우저 호환성

+ + + +

{{Compat("html.elements.a")}}

+ +

같이 보기

+ + diff --git a/files/ko/web/html/element/abbr/index.html b/files/ko/web/html/element/abbr/index.html new file mode 100644 index 0000000000..7deefb3ce3 --- /dev/null +++ b/files/ko/web/html/element/abbr/index.html @@ -0,0 +1,194 @@ +--- +title: +slug: Web/HTML/Element/abbr +tags: + - Element + - HTML + - HTML text-level semantics + - Reference + - Web +translation_of: Web/HTML/Element/abbr +--- +
{{HTMLRef}}
+ +

HTML <abbr> 요소는 준말 또는 머리글자를 나타냅니다. 선택 속성인 {{htmlattrxref("title")}}을 사용하면 준말의 전체 뜻이나 설명을 제공할 수 있습니다. title 속성은 전체 설명만을 가져야 하며 다른건 포함할 수 없습니다.

+ +
{{EmbedInteractiveExample("pages/tabbed/abbr.html", "tabbed-shorter")}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
콘텐츠 카테고리플로우 콘텐츠, 구문 콘텐츠, 뚜렷한 콘텐츠.
가능한 콘텐츠구문 콘텐츠
태그 생략{{no_tag_omission}}
가능한 부모 요소구문 콘텐츠를 허용하는 모든 요소.
암시적 ARIA 역할대응하는 역할 없음
가능한 ARIA 역할모두
DOM 인터페이스{{domxref("HTMLElement")}}
+ +

특성

+ +

이 요소는 전역 특성만 포함합니다. 단, 다른 요소와 달리 <abbr> 요소에서의 {{htmlattrxref("title")}} 특성은 특정한 의미를 가지며, title은 준말에 대한 설명 혹은 확장 형태를 사람이 읽을 수 있는 형태를 값으로 가져야 합니다. 브라우저는 title의 값을 보통 마우스 커서를 올렸을 때 나타나는 툴팁으로 보여줍니다.

+ +

각각의 <abbr> 요소는 서로 독립적입니다. 하나의 요소에 title을 제공한다고 나머지에 지정하지 않아도 되는 것은 아닙니다.

+ +

사용 일람

+ +

많이 쓰이는 곳

+ +

당연히 모든 준말을 <abbr>로 표시해야 하는 것은 아닙니다. 그러나 표시할 경우 도움이 될, 다음과 같은 경우가 있습니다.

+ + + +

문법 고려사항

+ +

수량이 문법에 영향을 미치는 언어(one apple vs. two apples)의 경우, <abbr> 요소의 텍스트와 title 특성의 내용이 같은 형태를 따르도록 하세요. 아랍어처럼 두 개 이상의 복수형 구분을 두는 언어에서 특히 중요하나, 영어도 해당합니다.

+ +

기본 스타일

+ +

<abbr>의 목적은 오로지 HTML 작성자의 편리함을 위함이며, 모든 브라우저는 기본적으로 인라인({{cssxref('display')}}: inline)으로 렌더링 합니다. 그러나 기본 스타일은 브라우저마다 다를 수 있습니다.

+ + + +

예제

+ +

준말임을 나타내기

+ +

설명 없이, 단순히 특정 단어가 준말임을 나타내기만 하고자 하면 <abbr>을 다른 특성 없이 사용하세요.

+ +

HTML

+ +
<p>Using <abbr>HTML</abbr> is fun and easy!</p>
+ +

결과

+ +

{{EmbedLiveSample("준말임을_나타내기")}}

+ +

준말 스타일링

+ +

CSS를 사용해 준말에 적용할 사용자 지정 스타일을 적용할 수 있습니다.

+ +

HTML

+ +
<p>Using <abbr>CSS</abbr>, you can style your abbreviations!</p>
+ +

CSS

+ +
abbr {
+  font-variant: all-small-caps;
+}
+ +

결과

+ +

{{EmbedLiveSample("준말_스타일링")}}

+ +

펼친 형태 보여주기

+ +

{{htmlattrxref("title")}} 특성을 사용하면 준말과 머리글자를 펼친 원래 형태를 보여줄 수 있습니다.

+ +

HTML

+ +
<p>Ashok's joke made me <abbr title="Laugh Out Loud">LOL</abbr> big
+time.</p>
+ +

결과

+ +

{{EmbedLiveSample("펼친_형태_보여주기")}}

+ +

준말 정의하기

+ +

<abbr>과 {{HTMLElement("dfn")}}을 사용하면 준말을 정식으로 정의할 수 있습니다.

+ +

HTML

+ +
<p><dfn id="html"><abbr title="HyperText Markup Language">HTML</abbr>
+</dfn> is a markup language used to create the semantics and structure
+of a web page.</p>
+
+<p>A <dfn id="spec">Specification</dfn>
+(<abbr title="Specification">spec</abbr>) is a document that outlines
+in detail how a technology or API is intended to function and how it is
+accessed.</p>
+ +

결과

+ +

{{EmbedLiveSample("준말_정의하기", 600, 120)}}

+ +

접근성 고려사항

+ +

준말과 머리글자가 처음 사용될 때, 그 뜻을 풀어 설명하면 독자가 문서를 이해하기 쉬워집니다. 특히 콘텐츠가 기술이나 산업에 관련된 전문적인 내용인 경우 더욱 그렇습니다.

+ +

예제

+ +
<p>JavaScript Object Notation(<abbr>JSON</abbr>)은 경량의 데이터 교환 형식입니다.</p>
+
+ +

무엇보다 용어나 개념에 익숙하지 않은 사람, 언어를 새로 접한 사람, 그리고 인지력 문제를 겪고 있는 사용자에게 큰 도움이 됩니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'semantics.html#the-abbr-element', '<abbr>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'textlevel-semantics.html#the-abbr-element', '<abbr>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'struct/text.html#edef-ABBR', '<abbr>')}}{{Spec2('HTML4.01')}}
+ +

브라우저 호환성

+ + + +

{{Compat("html.elements.abbr")}}

diff --git a/files/ko/web/html/element/address/index.html b/files/ko/web/html/element/address/index.html new file mode 100644 index 0000000000..cd43856ceb --- /dev/null +++ b/files/ko/web/html/element/address/index.html @@ -0,0 +1,128 @@ +--- +title:
+slug: Web/HTML/Element/address +tags: + - Element + - HTML + - HTML sections + - 'HTML:Flow content' + - 'HTML:Palpable Content' + - Reference + - Web +translation_of: Web/HTML/Element/address +--- +
{{HTMLRef}}
+ +

HTML <address> 요소는 가까운 HTML 요소의 사람, 단체, 조직 등에 대한 연락처 정보를 나타냅니다.

+ +
{{EmbedInteractiveExample("pages/tabbed/address.html", "tabbed-standard")}}
+ + + +

<address> 요소의 콘텐츠가 제공하는 연락처 정보는 현재 맥락에 적절한 아무 형태나 취할 수 있으며, 물리적 주소, URL, 이메일 주소, 전화번호, SNS 식별자, 좌표 등 어떠한 정보라도 포함할 수 있습니다. 반드시 포함해야 하는 정보는 연락처가 가리키는 개인, 조직, 단체의 이름입니다.

+ +

<address>는 다양한 맥락에서 사용할 수 있습니다. 사업체 연락 방법을 페이지 헤더에 배치할 때도 쓸 수 있고, {{HTMLElement("article")}} 내부에 배치해서 글의 작성자를 나타낼 수도 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
콘텐츠 카테고리플로우 콘텐츠, 뚜렷한 콘텐츠.
가능한 콘텐츠플로우 콘텐츠. 단, 다음의 요소는 사용할 수 없습니다.
+ 다른 <address>, 제목 콘텐츠 ({{HTMLElement("hgroup")}}, {{HTMLElement("h1")}}, {{HTMLElement("h2")}}, {{HTMLElement("h3")}}, {{HTMLElement("h4")}}, {{HTMLElement("h5")}}, {{HTMLElement("h6")}}), 구획 콘텐츠 ({{HTMLElement("article")}}, {{HTMLElement("aside")}}, {{HTMLElement("section")}}, {{HTMLElement("nav")}}), {{HTMLElement("header")}}, {{HTMLElement("footer")}} 요소.
태그 생략{{no_tag_omission}}
가능한 부모 요소플로우 콘텐츠를 허용하는 모든 요소. 단, <address> 요소 제외.
암시적 ARIA 역할대응하는 역할 없음
가능한 ARIA 역할없음
DOM 인터페이스{{domxref("HTMLElement")}}
+ +

특성

+ +

이 요소는 전역 특성만 포함합니다.

+ +

사용 일람

+ +
    +
  • 기존 명세에서의 <address> 요소는 문서 작성자의 연락처만 나타내는 요소였습니다. 그러나 최신 명세에서 임의의 연락처를 포함할 수 있도록 수정됐습니다.
  • +
  • 연락처 외의 정보(출판일 등)를 담아서는 안됩니다.
  • +
  • 보통, 현재 구획에 {{htmlelement("footer")}} 요소가 존재하면 <address>를 그 안에 배치할 수 있습니다.
  • +
+ +

예제

+ +

다음 예제는 <address>를 사용해 글 작성자의 연락처를 구별하는 모습을 보입니다.

+ +
<address>
+  You can contact author at <a href="http://www.somedomain.com/contact">
+  www.somedomain.com</a>.<br>
+  If you see any bugs, please <a href="mailto:webmaster@somedomain.com">
+  contact webmaster</a>.<br>
+  You may also want to visit us:<br>
+  Mozilla Foundation<br>
+  331 E Evelyn Ave<br>
+  Mountain View, CA 94041<br>
+  USA
+</address>
+
+ +

결과

+ +

{{EmbedLiveSample("예제", "300", "200")}}

+ +

비록 겉보기는 {{HTMLElement("i")}}나 {{HTMLElement("em")}} 요소와 같지만, <address> 요소는 자체적인 의미를 갖고 있으므로 연락처 표기에는 <address>가 더 적합합니다.

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('HTML WHATWG', 'sections.html#the-address-element', '<address>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'grouping-content.html#the-address-element', '<address>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'struct/global.html#h-7.5.6', '<address>')}}{{Spec2('HTML4.01')}}
+ +

브라우저 호환성

+ + + +

{{Compat("html.elements.address")}}

diff --git a/files/ko/web/html/element/applet/index.html b/files/ko/web/html/element/applet/index.html new file mode 100644 index 0000000000..274b0635db --- /dev/null +++ b/files/ko/web/html/element/applet/index.html @@ -0,0 +1,115 @@ +--- +title: +slug: Web/HTML/Element/applet +translation_of: Web/HTML/Element/applet +--- +
{{obsolete_header}}
+ +

개요

+ +

HTML의 Applet 태그 (<applet>) 는 자바 애플릿을 보이게 하는 곳에 쓰입니다.

+ +
+

사용시 참고: This element has been removed in HTML5 and shouldn't be used anymore. Instead web developers should use the more generic {{HTMLElement("object")}} element.

+
+ +

Attributes

+ +
+
{{htmlattrdef("align")}}
+
This attribute is used to position the applet on the page relative to content that might flow around it. The HTML 4.01 specification defines values of bottom, left, middle, right, and top, whereas Microsoft and Netscape also might support absbottom, absmiddle, baseline, center, and texttop.
+
{{htmlattrdef("alt")}}
+
This attribute causes a descriptive text alternate to be displayed on browsers that do not support Java. Page designers should also remember that content enclosed within the <applet> element may also be rendered as alternative text.
+
{{htmlattrdef("archive")}}
+
This attribute refers to an archived or compressed version of the applet and its associated class files, which might help reduce download time.
+
{{htmlattrdef("code")}}
+
This attribute specifies the URL of the applet's class file to be loaded and executed. Applet filenames are identified by a .class filename extension. The URL specified by code might be relative to the codebase attribute.
+
{{htmlattrdef("codebase")}}
+
This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are stored.
+
{{htmlattrdef("datafld")}}
+
This attribute, supported by Internet Explorer 4 and higher, specifies the column name from the data source object that supplies the bound data. This attribute might be used to specify the various {{HTMLElement("param")}} elements passed to the Java applet.
+
{{htmlattrdef("datasrc")}}
+
Like datafld, this attribute is used for data binding under Internet Explorer 4. It indicates the id of the data source object that supplies the data that is bound to the {{HTMLElement("param")}} elements associated with the applet.
+
{{htmlattrdef("height")}}
+
This attribute specifies the height, in pixels, that the applet needs.
+
{{htmlattrdef("hspace")}}
+
This attribute specifies additional horizontal space, in pixels, to be reserved on either side of the applet.
+
{{htmlattrdef("mayscript")}}
+
In the Netscape implementation, this attribute allows access to an applet by programs in a scripting language embedded in the document.
+
{{htmlattrdef("name")}}
+
This attribute assigns a name to the applet so that it can be identified by other resources; particularly scripts.
+
{{htmlattrdef("object")}}
+
This attribute specifies the URL of a serialized representation of an applet.
+
{{htmlattrdef("src")}}
+
As defined for Internet Explorer 4 and higher, this attribute specifies a URL for an associated file for the applet. The meaning and use is unclear and not part of the HTML standard.
+
{{htmlattrdef("vspace")}}
+
This attribute specifies additional vertical space, in pixels, to be reserved above and below the applet.
+
{{htmlattrdef("width")}}
+
This attribute specifies in pixels the width that the applet needs.
+
+ +

예제

+ +
<applet code="game.class" align="left" archive="game.zip" height="250" width="350">
+  <param name="difficulty" value="easy">
+  <b>죄송합니다. 이 게임을 플레이하려면 자바가 설치되어 있어야 합니다.</b>
+</applet>
+
+ +

Browser compatibility

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatNo}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE MobileOpera MiniOpera MobileSafari Mobile
Basic support{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +

Notes

+ +

The W3C specification does not encourage the use of <applet> and prefers the use of the {{HTMLElement("object")}} tag. Under the strict definition of HTML 4.01, this element is deprecated and entirely obsolete in HTML5.

+ +
{{HTMLRef}}
diff --git a/files/ko/web/html/element/area/index.html b/files/ko/web/html/element/area/index.html new file mode 100644 index 0000000000..4c3f6d93a7 --- /dev/null +++ b/files/ko/web/html/element/area/index.html @@ -0,0 +1,184 @@ +--- +title: +slug: Web/HTML/Element/area +tags: + - Element + - HTML + - HTML embedded content + - Reference + - Web +translation_of: Web/HTML/Element/area +--- +
{{HTMLRef}}
+ +

HTML <area> 요소는 이미지의 핫스팟 영역을 정의하고 {{glossary("hyperlink", "하이퍼링크")}}를 추가할 수 있습니다. {{htmlelement("map")}} 요소 안에서만 사용할 수 있습니다.

+ +
{{EmbedInteractiveExample("pages/tabbed/area.html", "tabbed-taller")}}
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
콘텐츠 카테고리플로우 콘텐츠, 구문 콘텐츠.
가능한 콘텐츠없음. {{glossary("empty element", "빈 요소")}}입니다.
태그 생략여는 태그는 존재해야 하며 닫는 태그는 존재해선 안됩니다.
가능한 부모 요소구문 콘텐츠를 허용하는 모든 요소. 단, 조상 중 {{htmlelement("map")}} 요소가 존재해야 합니다.
암시적 ARIA 역할{{htmlattrxref("href", "area")}} 특성이 존재하면 {{ariarole("link")}}, 그 외의 경우 대응하는 역할 없음
가능한 ARIA 역할없음
DOM 인터페이스{{domxref("HTMLAreaElement")}}
+ +

특성

+ +

이 요소는 전역 특성을 포함합니다.

+ +
+
{{htmlattrdef("alt")}}
+
이미지를 출력하지 않는 브라우저에서 대신 표시할 대안 텍스트입니다. 텍스트의 내용은 대안 텍스트 없이 이미지만 표시할 때와 동일한 수준의 선택지를 나타낼 수 있어야 합니다. {{htmlattrxref("href", "area")}} 특성이 존재할 경우 필수 사항입니다.
+
+ +
+
{{htmlattrdef("coords")}}
+
핫스팟 영역을 지정하는 일련의 좌표입니다. 값의 수와 의미는 shape 특성의 값에 따라 달라집니다.
+
+
    +
  • rect: 좌상단과 우하단을 나타내는 두 개의 x, y 쌍입니다.
  • +
  • circle: x,y,r로서 x,y는 원의 중심 좌표이며 r은 반지름입니다.
  • +
  • poly: 다각형의 꼭지점을 나타내는 다수의 x, y 쌍(x1,y1,x2,y2,x3,y3,...)입니다.
  • +
+ 값의 단위는 CSS 픽셀입니다.
+
{{htmlattrdef("download")}}
+
특성이 존재할 경우, 이 하이퍼링크는 리소스 다운로드 용도로 사용하는 것을 의도했음을 나타냅니다. {{htmlelement("a")}}의 {{htmlattrxref("download", "a")}} 특성 설명에서 전체 설명을 볼 수 있습니다.
+
+ +
+
{{htmlattrdef("href")}}
+
<area> 하이퍼링크의 대상입니다. 유효한 URL이야 합니다. 생략할 경우, 이 <area> 요소는 하이퍼링크를 나타내지 않습니다.
+
{{htmlattrdef("hreflang")}}
+
연결한 리소스의 언어를 나타냅니다. 가능한 값은 BCP47에 따릅니다. {{htmlattrxref("href", "area")}} 특성이 존재할 때만 사용하세요.
+
{{htmlattrdef("ping")}}
+
하이퍼링크를 따라갈 때, 백그라운드에서 브라우저가 {{HTTPMethod("POST")}} 요청을 본문 PING으로 전송할 URL의 목록입니다. 공백으로 구분하며 주로 추적용으로 사용합니다.
+
+ +
+
{{htmlattrdef("referrerpolicy")}} {{experimental_inline}}
+
A string indicating which referrer to use when fetching the resource: +
    +
  • "no-referrer" meaning that the Referer: header will not be sent.
  • +
  • "no-referrer-when-downgrade" meaning that no Referer: header will be sent when navigating to an origin without TLS (HTTPS). This is a user agent’s default behavior, if no policy is otherwise specified.
  • +
  • "origin" meaning that the referrer will be the origin of the page, that is roughly the scheme, the host and the port.
  • +
  • "origin-when-cross-origin" meaning that navigations to other origins will be limited to the scheme, the host and the port, while navigations on the same origin will include the referrer's path.
  • +
  • "unsafe-url" meaning that the referrer will include the origin and the path (but not the fragment, password, or username). This case is unsafe because it can leak origins and paths from TLS-protected resources to insecure origins.
  • +
+
+
{{htmlattrdef("rel")}}
+
For anchors containing the href attribute, this attribute specifies the relationship of the target object to the link object. The value is a comma-separated list of link types values. The values and their semantics will be registered by some authority that might have meaning to the document author. The default relationship, if no other is given, is void. Use this attribute only if the href attribute is present.
+
{{htmlattrdef("shape")}}
+
관련된 핫 스폿의 모양. The specifications for HTML 5 and HTML 4 define the values rect, which defines a rectangular region; circle, which defines a circular region; poly, which defines a polygon; and default, which indicates the entire region beyond any defined shapes. Many browsers, notably Internet Explorer 4 and higher, support circ, polygon, and rectangle as valid values for shape; these values are {{Non-standard_inline}}.
+
+ +
+
{{htmlattrdef("target")}}
+
이 속성은 링크된 리소스가 어디에 표시될지 지정합니다. HTML4에서 이것은 프레임의 이름이나 키워드가 될수 있습니다. HTML5에서는, 브라우징 컨텍스트(탭,윈도우,인라인 프레임)의 이름이나 키워드가 될수 있습니다. 다음 키워드들은 특별한 의미를 가지고 있습니다. +
    +
  • _self: 결과를 현재 HTML4 프레임 또는 HTML5 브라우징 컨텍스트에 로드합니다. 이 target 속성이 정의되어있지 않은경우 이 값이 기본값이 됩니다.
  • +
  • _blank: 결과를 이름없는 새로운 HTML4 윈도우나 HTML5 브라우징 컨텍스트에 로드합니다.
  • +
  • _parent: 결과를 현재 HTML4 프레임의 부모 프레임셋에 로드하거나 부모 HTML5 브라우징 컨텍스트에 로드합니다. 만약 부모가 없을 경우 _self와 동일하게 여겨집니다.
  • +
  • _top: HTML4에서는, 다른 모든 프레임을 취소하고 결과를 꽉찬 본래의 윈도우에 로드합니다. HTML5에서는, 결과를 최상위 브라우징 컨텍스트에 로드합니다. 만약 부모가 없다면, 이 옵션은 _self와 같이 행동합니다.
  • +
+ 이 속성은 href 속성이 존재할떄만 사용합니다.
+
+ + + +

예제

+ +
<map name="primary">
+  <area shape="circle" coords="200,250,25" href="another.htm" />
+  <area shape="default" nohref />
+</map>
+<img usemap="#primary" src="http://placehold.it/350x150" alt="350 x 150 pic">
+
+ +

결과

+ +

{{EmbedLiveSample('예제', 360, 160)}}

+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrerpolicy attribute')}}{{Spec2('Referrer Policy')}}Added the referrerpolicy attribute.
{{SpecName('HTML WHATWG', 'the-map-element.html#the-area-element', '<area>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5 W3C', 'embedded-content-0.html#the-area-element', '<area>')}}{{Spec2('HTML5 W3C')}}
{{SpecName('HTML4.01', 'struct/objects.html#h-13.6.1', '<area>')}}{{Spec2('HTML4.01')}}
+ +

브라우저 호환성

+ + + +

{{Compat("html.elements.area")}}

diff --git a/files/ko/web/html/element/article/index.html b/files/ko/web/html/element/article/index.html new file mode 100644 index 0000000000..6602a7722e --- /dev/null +++ b/files/ko/web/html/element/article/index.html @@ -0,0 +1,137 @@ +--- +title:
+slug: Web/HTML/Element/article +tags: + - Element + - HTML + - HTML sections + - Reference + - Web +translation_of: Web/HTML/Element/article +--- +
{{HTMLRef}}
+ +

HTML <article> 요소는 문서, 페이지, 애플리케이션, 또는 사이트 안에서 독립적으로 구분해 배포하거나 재사용할 수 있는 구획을 나타냅니다. 사용 예제로 게시판과 블로그 글, 매거진이나 뉴스 기사 등이 있습니다.

+ +
{{EmbedInteractiveExample("pages/tabbed/article.html", "tabbed-standard")}}
+ + + +

하나의 문서가 여러 개의 <article>을 가질 수 있습니다. 예컨대 사용자가 스크롤하면 계속해서 다음 글을 보여주는 블로그의 경우, 각각의 글이 <article> 요소가 되며, 그 안에는 또 여러 개의 {{htmlelement("section")}}이 존재할 수 있습니다.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
콘텐츠 카테고리플로우 콘텐츠, 구획 콘텐츠, 뚜렷한 콘텐츠.
가능한 콘텐츠플로우 콘텐츠.
태그 생략{{no_tag_omission}}
가능한 부모 요소플로우 콘텐츠를 허용하는 모든 요소.
+ <article> 요소는 {{HTMLElement("address")}}의 후손이 될 수 없음에 주의하세요.
암시적 ARIA 역할{{ariarole("article")}}
가능한 ARIA 역할{{ARIARole("application")}}, {{ARIARole("document")}}, {{ARIARole("feed")}}, {{ARIARole("main")}}, {{ARIARole("none")}}, {{ARIARole("presentation")}}, {{ARIARole("region")}}
DOM 인터페이스{{domxref("HTMLElement")}}
+ +

특성

+ +

이 요소는 전역 특성만 포함합니다.

+ +

사용 일람

+ +
    +
  • 각각의 <article>을 식별할 수단이 필요합니다. 주로 제목({{htmlelement('h1')}}-{{htmlelement('h6')}}) 요소를 <article>의 자식으로 포함하는 방법을 사용합니다.
  • +
  • <article> 요소가 중첩되어 있을 때, 안쪽에 있는 요소는 바깥쪽에 있는 요소와 관련된 글을 나타냅니다. 예를 들어 블로그 글의 댓글은, 글을 나타내는 <article> 요소 안에 중첩한 <article>로 나타낼 수 있습니다.
  • +
  • <article> 요소의 작성자 정보를 {{HTMLElement("address")}} 요소를 이용하여 제공할 수 있습니다. 그러나 중첩 <article>에는 적용되지 않습니다.
  • +
  • <article> 요소의 작성일자와 시간은 {{HTMLElement("time")}} 요소의 {{htmlattrxref("datetime", "time")}} 속성을 이용하여 설명할 수 있습니다. 참고로 {{HTMLElement("time")}} 요소의 {{htmlattrxref("pubdate", "time")}} 속성은 더 이상 {{glossary("W3C")}} {{glossary("HTML5")}} 표준안에 포함되지 않습니다.
  • +
+ +

예제

+ +
<article class="film_review">
+  <header>
+    <h2>Jurassic Park</h2>
+  </header>
+  <section class="main_review">
+    <p>Dinos were great!</p>
+  </section>
+  <section class="user_reviews">
+    <article class="user_review">
+      <p>Way too scary for me.</p>
+      <footer>
+        <p>
+          Posted on <time datetime="2015-05-16 19:00">May 16</time> by Lisa.
+        </p>
+      </footer>
+    </article>
+    <article class="user_review">
+      <p>I agree, dinos are my favorite.</p>
+      <footer>
+        <p>
+          Posted on <time datetime="2015-05-17 19:00">May 17</time> by Tom.
+        </p>
+      </footer>
+    </article>
+  </section>
+  <footer>
+    <p>
+      Posted on <time datetime="2015-05-15 19:00">May 15</time> by Staff.
+    </p>
+  </footer>
+</article>
+
+ +

명세

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
명세상태주석
{{SpecName('HTML WHATWG', 'semantics.html#the-article-element', '<article>')}}{{Spec2('HTML WHATWG')}}
{{SpecName('HTML5.1', 'sections.html#the-article-element', '<article>')}}{{Spec2('HTML5.1')}}
{{SpecName('HTML5 W3C', 'sections.html#the-article-element', '<article>')}}{{Spec2('HTML5 W3C')}}
+ +

브라우저 호환성

+ + + +

{{Compat("html.elements.article")}}

diff --git a/files/ko/web/html/element/aside/index.html b/files/ko/web/html/element/aside/index.html new file mode 100644 index 0000000000..416f1d5edc --- /dev/null +++ b/files/ko/web/html/element/aside/index.html @@ -0,0 +1,122 @@ +--- +title: '