Canvas and SVG(Scalable Vector Graphics) 류관희 충북대학교
HTML5 Canvas? (1/2) The HTML5 Canvas is an Immediate Mode bit-mapped area of the screen that can be manipulated with JavaScript and CSS. The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript). The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, characters, and adding images. OpenVG & Canvas - 2D Graphics 2
HTML5 Canvas? (2/2) Features 2D Context Save, Restore : push or pop graphics state stack Transformation Global alpha Shapes : Fill and Stroke Path Canvas State : Fill and Stroke Style, Matrix, Clipping region Image Text Hardware Accelerated Canvas Element OpenVG & Canvas - 2D Graphics 3
Flash vs Canvas Finished Essential guide To Flash Games in March 2010. Steve Jobs refused Flash on the ios just days later. Easy Tools: a web browser, text editor and JavaScript was all that was required. The HTML5 Canvas allowed for a bitmapped graphics, much Flash s bitmapped canvas. Our specific Type Of Game Development translates well (tile sheets, bitmaps) OpenVG & Canvas - 2D Graphics 4
Retained mode vs Immediate Fig1. Retained Mode Fig2. Immediate Mode OpenVG & Canvas - 2D Graphics 5
HTML5 Canvas Support OpenVG & Canvas - 2D Graphics 6
HTML5 Canvas properties & methods width height id <canvas id= MyFirstCanvas width= 600 heght= 200 > This text is displayed if your browser does not support HTML5 Canvas. </canvas> OpenVG & Canvas - 2D Graphics 7
Colors, Styles, and Shadows Property fillstyle strokestyle shadowcolor shadowblur shadowoffsetx shadowoffsety Description Sets or returns the color, gradient, or pattern used to fill the drawing Sets or returns the color, gradient, or pattern used for strokes Sets or returns the color to use for shadows Sets or returns the blur level for shadows Sets or returns the horizontal distance of the shadow from the shape Sets or returns the vertical distance of the shadow from the shape Method createlineargradient() createpattern() createradialgradient() addcolorstop() Description Creates a linear gradient (to use on canvas content) Repeats a specified element in the specified direction Creates a radial/circular gradient (to use on canvas content) Specifies the colors and stop positions in a gradient object OpenVG & Canvas - 2D Graphics 8
Rectangles Method rect() fillrect() strokerect() clearrect() Description Creates a rectangle Draws a "filled" rectangle Draws a rectangle (no fill) Clears the specified pixels within a given rectangle OpenVG & Canvas - 2D Graphics 9
Line Styles Property linecap linejoin linewidth miterlimit Description Sets or returns the style of the end caps for a line Sets or returns the type of corner created, when two lines meet Sets or returns the current line width Sets or returns the maximum miter length OpenVG & Canvas - 2D Graphics 10
Paths Method fill() stroke() beginpath() moveto() closepath() lineto() clip() quadraticcurveto() beziercurveto() arc() arcto() ispointinpath() Description Fills the current drawing (path) Actually draws the path you have defined Begins a path, or resets the current path Moves the path to the specified point in the canvas, without creating a line Creates a path from the current point back to the starting point Adds a new point and creates a line from that point to the last specified point in the canvas Clips a region of any shape and size from the original canvas Creates a quadratic Bézier curve Creates a cubic Bézier curve Creates an arc/curve (used to create circles, or parts of circles) Creates an arc/curve between two tangents Returns true if the specified point is in the current path, otherwise false OpenVG & Canvas - 2D Graphics 11
Transformations Method scale() rotate() translate() transform() settransform() Description Scales the current drawing bigger or smaller Rotates the current drawing Remaps the (0,0) position on the canvas Replaces the current transformation matrix for the drawing Resets the current transform to the identity matrix. Then runs transform() OpenVG & Canvas - 2D Graphics 12
Text Property font textalign textbaseline Description Sets or returns the current font properties for text content Sets or returns the current alignment for text content Sets or returns the current text baseline used when drawing text Method filltext() stroketext() measuretext() Description Draws "filled" text on the canvas Draws text on the canvas (no fill) Returns an object that contains the width of the specified text OpenVG & Canvas - 2D Graphics 13
Images Method drawimage() Description Draws an image, canvas, or video onto the canvas Property width height data Description Returns the width of an ImageData object Returns the height of an ImageData object Returns an object that contains image data of a specified ImageData object Method createimagedata() getimagedata() putimagedata() Description Creates a new, blank ImageData object Returns an ImageData object that copies the pixel data for the specified rectangle on a canvas Puts the image data (from a specified ImageData object) back onto the canvas OpenVG & Canvas - 2D Graphics 14
Compositing & Others Property globalalpha globalcompositeoperation Description Sets or returns the current alpha or transparency value of the drawing Sets or returns how a new image are drawn onto an existing image Method save() restore() createevent() getcontext() todataurl() Description Saves the state of the current context Returns previously saved path state and attributes OpenVG & Canvas - 2D Graphics 15
Example : Two overlapped rectanges <script> var canvas = document.queryselector("canvas"); var context = canvas.getcontext('2d'); context.fillstyle = 'red'; context.fillrect(0,0,800,600); context.fillstyle = 'rgba(255,255,0,0.5)'; context.fillrect(400,200,800,600); </script> OpenVG & Canvas - 2D Graphics 16
Example : Curve <script> var canvas = document.queryselector("canvas"); var context = canvas.getcontext('2d');. // geometry context.save(); context.beginpath(); context.moveto(20,130); context.quadraticcurveto(20,20,130,20); context.strokestyle = colors.path; context.stroke(); context.restore();. </script> OpenVG & Canvas - 2D Graphics 17
Example : Stroke <script> var canvas = document.queryselector("canvas"); var context = canvas.getcontext('2d');. // thick line context.linewidth = 20.0; // join style context.beginpath(); context.linejoin = 'bevel'; context.linejoin = 'round'; context.linejoin = 'miter'; context.moveto(20,130); context.lineto(50,50); context.lineto(80,130); context.stroke();. // cap style context.beginpath(); context.linecap = 'butt'; context.linecap = 'round'; context.linecap = 'square'; context.moveto(50,130); context.lineto(50,50); context.stroke();. </script> OpenVG & Canvas - 2D Graphics 18
Example : Image <script> var canvas = document.getelementbyid('canvas'), context = canvas.getcontext('2d'), image = new Image(); image.src = '../../shared/images/countrypath.jpg'; image.onload = function(e) { context.drawimage(image, 0, 0); }; </script> OpenVG & Canvas - 2D Graphics 19
Canvas Demo http://www.upstreamdown.com/fishtank/ OpenVG & Canvas - 2D Graphics 20
SVG (Scalable Vector Graphics) SVG SVG Characteristic SVG History Tutorial Rectangle <rect>, Circle <circle>, Ellipse <ellipse>, Line <line> Polygon <polygon>, Polyline <polyline> Path <path> Gradient, Text Stroking Etc Exporting 애니메이션효과예제.. 원형차트그리기 SVG 를사용한그래픽라이브러리소개
SVG (Scalable Vector Graphics) :: XML 형식의그래픽을정의하고웹을위한벡터기반의그래픽을정의하기위해사용됨. 확대하거나크기를변화시켜도그래픽이손상되지않음. 다양한해상도와픽셀밀도에대응이가능함. 애니메이션과미디어쿼리지원등을포함하고있음.
SVG 의특징 XML 기반 :: CSS(Cascading Style Sheets), XSL(XML Style Language) 를지원 ( 스타일시트를통한커스터마이징이가능 / XML 기반의다른문서와통합가능 ) 멀티플랫폼 (Multi - Platform) :: 시스템, 운영체제에장애를받지않음. (PC, Mobile, android, ios 등에서모두지원됨 ) 상호작용 (Interactive Graphics) :: 키보드, 마우스입력에대한응답이가능하고 Interactive 그래프등을비교적쉽게구현가능 데이터연동 (Data-Driven Graphics) :: 데이터베이스연동이가능 ( 복잡한데이터의가시화가필요한지리정보, 실시간정보가시화등에효과적 ) 개인화 (Personalized Graphics)::
SVG History 1998 :: Adobe, Sun, Netscape 에서함께벡터그래픽을위한웹문서표준으로 PGML(Precision Graphics Markup Language) 제안 ( 이전에 Microsystem, MacroMedia 에서 VML 을제안해으나그에대응하여 PGML 을제안 ) W3C(World Wide Web Consortium) :: PGML 과 VML 기반의새로운벡터그래픽포맷제정을결정함. VML(vector markup language), PGML(Precision Graphics Markup Language)
SVG History 1998 년 08 월 :: SVG Working Group Adobe, Macromedia, IBM, Corel, Apple, HP, Microsoft, AutoDesk, Netscape, CSIRO, Kodak 1999 년 02 월 :: 초안발표 2001 년 09 월 SVG 1.0 권고 2003 년 01 월 :: SVG 1.1 권고 (W3C 권고안으로발표 ) Mobile SVG Profile 인 SVG Tiny 와 SVG Basic 2008 년 12 월 :: SVGT 1.2 권고
SVG Tutorial Tutorial (http://www.w3schools.com/svg/) Basic Shape :: Rectangle <rect>, Circle <circle>, Ellipse <ellipse>, Line <line> Polygon <polygon>, Polyline <polyline> Path <path> Text Stroking Etc 애니메이션효과예제.. 원형차트그리기 SVG 를사용한그래픽라이브러리소개
HTML Form <Head> JavaScript CSS <script> 내용 </script> <style> 내용 </style> <Body> SVG <svg> 내용 </svg> canvas 정적인 html
Rectangle <rect>
Rectangle <rect> 얼마나둥글게만들것인가 rx = x 축방향 ry = y 축방향
Circle <circle> cx, cy = 중심점 r = 반지름
Ellipse <ellipse> rx = x 축반지름 ry = y 축반지름
Line & Polyline < line > < polyline > Source :: <svg height="210" width="500"> <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2" /> </svg> <polyline points="20,20 40,25 60,40 80,120 120,140 200,180" style="fill:none;stroke:black;stroke-width:3" /> <polyline points="0,40 40,40 40,80 80,80 80,120 120,120 120,160" style="fill:white;stroke:red;stroke-width:4" />
Polyline fill : white or none fill : blue 시작점, 끝점기준 Source :: <polyline points= "0,40 40,40 40,80 80,80 80,120 120,120 120,160" style="fill:white; stroke:red; stroke-width:4" /> => fill: blue;
Path Path property <svg height="210" width="400"> <path d="m150 0 L75 200 L225 200 Z"/> </svg> 도형이닫혀있음 1. 시작 point 2. 다음 point 3. 다음 point
Path <svg height="400" width="450"> <path id="lineab" d="m 100 350 L 150-300" stroke="red" stroke-width="3" fill="none" /> <path id="linebc" d="m 250 50 L 150 300" stroke="red" stroke-width="3" fill="none" /> <path d="m 175 200 L 150 0" stroke="green" stroke-width="3" fill="none" /> <path d="m 100 350 q 150-300 300 0" stroke="blue" stroke-width="5" fill="none" /> <g stroke="black" stroke-width="3" fill="black"> <circle id="pointa" cx="100" cy="350" r="3" /> <circle id="pointb" cx="250" cy="50" r="3" /> <circle id="pointc" cx="400" cy="350" r="3" /> </g> <g font-size="30" font="sans-serif" fill="black" stroke="none" text-anchor="middle"> <text x="100" y="350" dx="-30">a</text> <text x="250" y="50" dy="-10">b</text> <text x="400" y="350" dx="30">c</text> </g> </svg>
Path 대문자 : 절대좌표소문자 : 상대좌표 Path command :: M = moveto L = lineto H = horizontal lineto V = vertical lineto Z = closepath M(x,y) :: 시작점 L (x,y) :: 기준점에서좌표까지직선 H :: 다음포인트까지수평선 V :: 다음포인트까지수직선 Z :: path를닫는다. ( 마지막 point에서 M point로직선 )
Path Curve Curve command :: Q = quadratic Bézier curve T = smooth quadratic Bézier curveto C = Cubic bezier curveto S = smooth curveto A = elliptical Arc => 2 차 Bezier curve Q(x1,y1 x,y) :: 기준점에서 x,y 까지곡선을그려준다.(x1,y1 은 control point) T(x,y) :: 베지어커브에이어서커브를그릴때사용함. => 3 차 Bezier curve C(x2,y2 x1,y1 x,y) :: Q 에서조절점이하나추가 S(x1,y1 x,y) :: 조절점은앞선커브에대칭되는위치에놓이게된다. A(rx,ry x-axis-rotation large-arch-flag, sweepflag x,y) ::
Bezier curve(2 차 ) Source :: <path d="m 30 150 Q240 30 300 200" fill="none" stroke="black"/> <path d="m 30 100 Q140 30 200 200 T350 30" fill="none" stroke="black"/> Q(x1,y1 x,y) :: 기준점에서 x,y 까지곡선을그려준다. T(x,y) :: 연속해서커브를그릴때사용함.
Bezier curve(3 차 ) Source :: <path d="m 30 150 Q240 30 300 200" fill="none" stroke="black"/> <path d="m 30 100 Q140 30 200 200 T350 30" fill="none" stroke="black"/> Q(x1,y1 x,y) :: 기준점에서 x,y 까지곡선을그려준다. T(x,y) :: 연속해서커브를그릴때사용함.
Elliptical Arc A(rx,ry x-axis-rotation large-arch-flag, sweepflag x,y) :: rx, ry :: x, y 방향타원의반지름 x-axis-rotation : x 축주변으로얼마나구부러지는지 (rx 와 ry 의값이다를경우에만효과있음 ) Large-arch-flag : 커브의크기 (0 1) (1 이면크게 ) Sweepflag : 커브의방향 (0 1) (1 이면바깥?) x, y : 종료지점
Elliptical Arc parameter
Gradient Linear Source :: <defs> <ObjectBoundingBox> <userspaceonuse> <lineargradient id ="Exam1" x1="0%" y1="30%" x2="30%" y2="100%"gradientunits=?????????????? "> <stop offset="0%" stop-color="red"/> <stop offset="100%" stop-color="blue"/> </lineargradient> </defs>
Gradient Radial Source :: <defs> <ObjectBoundingBox> <userspaceonuse> <radialgradient id ="Exam1" x1="0%" y1="0%" x2="100%" y2="100%"gradientunits=?????????????????"> <stop offset="0%" stop-color="red"/> <stop offset="100%" stop-color="blue"/> </radialgradient> </defs>
Text Source :: Basic Text form <text x="0" y="15"> I love SVG! => 시작위치, Text message </text> <text x="0" y="15" fill="red"> I love SVG! => 시작위치, fill, Text message </text> Source :: Transform <text x="0" y="15" fill="red transform="rotate(30 20, 40)">I love SVG</text> => transform="rotate(angle) translate(tx, ty) => rotate( angle x, y ) // text를 20, 40 이동시켜서기울기 30의텍스트출력
Text( tspan, link) 속성설명 x="<coordinate>" y="<coordinate>" dx="<length>" dy="<length>" rotate="<angle>" 텍스트의 x 절대좌표값텍스트의 y 절대좌표값텍스트의 x 상대좌표값텍스트의 y 상대좌표값회전각도를지정한다 tspan :: <text x="10" y="20" style="fill:red;">several lines: <tspan x="10" y= 20">First line.</tspan> <tspan x="10" y="70">second line.</tspan> </text> Source :: hyperlink <a xlink:href="http://www.w3schools.com/svg/" target="_blank"> <text x="0" y="15" fill="red">i love SVG!</text> </a> <!-- <a> 지정된 text에 link를걸어준다. -->
Text_Path 웹상의 SVG 를수정 1. Circle 2. Radial Gradient 3. Path 4. Text_Path
Stroke width linecap dasharray 그래픽오브젝트의윤곽을지정하는것 Stroke-width= <length> Stroke-linecap= butt round square stroke-dasharray= 선, 공백, 선, 공백.
SVG Animation 동적인웹환경에적합한형태 시간에따라변화 SVG Animation 의 5 가지요소 animate : 스칼라값을가진속성을시간에따라다른값이할당되도록한다. set : 비수치값을가진속성을애니메이션하는데사용된다. animatemotion : 요소를이동패스에따라움직이게한다. animatecolor : 시간에따라컬러값을변경한다. animatetransform : SVG 변환속성을시간에따라변경한다.
Exporting D3 로작성된 Image 를파일로저장하기 Bitmap Image 로저장 Print_scrin 으로화면을캡쳐한다. PDF 문서로저장 PDF 로인쇄하는기능이있는프로그램사용 맥은별도의프로그램필요없음 ( 운영체제지원 ) SVG 문서로저장 SVG 코드를 Text_Editor 에복사 =>.svg 로저장
References - Canvas Web sites http://diveintohtml5.org/canvas.html https://developer.mozilla.org/en/canvas_tutorial http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvaselement.html http://www.html5canvastutorials.com http://www.w3schools.com http://kineticjs.com/ Books HTML5: Guidelines for Web Developers by Klaus Förster and Bernd Öggl HTML5 Canvas by Steve Fulton, Jeff Fulton OpenVG & Canvas - 2D Graphics 50
참고자료 책 ( 충북대도서관 ) 모바일컨텐츠제작을위한 SVG 프로그래밍 웹 SVG Tool http://svg-edit.googlecode.com/svn/trunk/editor/svg-editor.html http://sqler.pe.kr/biislec/bhtml5/401826 javascript 그래픽라이브러리소개 http://blog.jidolstar.com/872 Pie chart http://jbkflex.wordpress.com/2011/07/28/creating-a-svg-pie-chart-html5/ http://bl.ocks.org/mbostock/3887235