eventos javascript svg dom - argo navisargonavis.com.br/cursos/xml/x500/svg 08_script.pdf · •...

21
eventos javascript svg dom Helder da Rocha ([email protected])

Upload: vukhuong

Post on 04-Mar-2018

217 views

Category:

Documents


1 download

TRANSCRIPT

eventosjavascriptsvgdom

HelderdaRocha([email protected])

argo

navi

s.co

m.b

r Eventos

•  SVGpoderesponderaeventosiniciadospelousuárioatravésderecursosdalinguagem•  Movimentodomouseoucliquespodemdispararanimações,scriptsou

realizaçãodehiperlinks,zoomerolagem,mudançasdocursor,etc.

•  AspectosdeSVGafetadosporeventos•  OuvintesdeeventosdoDOM(DOMlisteners)registradosporscripts,eque

chamamoutroscriptquandoexecutados

•  Atributosdeeventosemelementos,queindicamscriptaexecutarquandooeventoacontecer

•  Elementosdeanimaçãopodemcomeçaroupararumaanimaçãocombaseemeventos

•  Atributospermitemligar,desligaroucontrolaraformacomoeventossãotratadosporelementos•  pointer‐events–controlaaspectosdecliques,movimentos

•  zoomAndPan–controlainteraJvidadedezoom

•  cursor–controlaaaparênciadocursor(tambémexisteumelemento<cursor>quepermitedefinirumcursorespecífico)

2

argo

navi

s.co

m.b

r Algunsatributosdeevento

•  onfocusineonfocusout•  Chamadosquandoelementorecebeouperdefoco

(quandoumtextoéselecionado,porexemplo)•  onac>vate

•  ChamadoquandoumelementoéaJvadoatravésdeumcliqueoutecla

•  onclick,onmouseup,onmousedown•  Chamadosquandoummouseéclicadosobreoelemento

•  onmouseover,onmousemove,onmouseout•  Chamadosdeacordocomomovimentodomousesobreumelemento

•  onload,onunload,onerror•  Eventosrelacionadosàcargadoobjetonamemória.

•  onresize,onscroll,onzoom•  Chamadosquandousuárioredimensionaatela,rola,usazoom

•  onbegin,onend,onrepeat•  Eventosrelacionadosaocomportamentodeanimação

3

xxx=>eventoonxxx=>atributo

argo

navi

s.co

m.b

r Scrip>ng

•  Paraespecificaralinguagemusada

•  AtributocontentScriptTypede<svg>(defaultapplica>on/ecmascript)ouatributotypedoelemento<script>(defaulttext/ecmascript)

•  Seoclientenaosuportaralinguagem,nenhumblocoscriptéexecutado

•  Oelemento<script>

•  Aceitadeclaraçãolocaldecódigo<script>...</script>•  Aceitaarquivoexternovia<scriptxlink:href="arquivo.js"/>

4

argo

navi

s.co

m.b

r SVGDocumentObjectModel

•  PermiteusarscriptsparacontrolarcomponentesSVG•  h;p://www.w3.org/TR/SVG/svgdom.html

•  SVGDOMestendeXMLDOM•  InterfacesdoSVGDOMherdamdoXMLDOM

•  Pode‐sefazerquasetudoconhecendo‐seapenasoXMLDOM

•  SVGElementherdadeElement(queherdadeNode)

•  SVGDocumentherdadeDocument(quetambéméNode)

•  Objetosespeciais:•  document(ponteiropara/)

•  evt(ponteiroparaevento)

•  PonteiroparaqualquerelementopeloID:•  document.getElementById("id");

•  Elementoquefoifontedeumevento:•  varelemento=evt.target;

5

argo

navi

s.co

m.b

r SVGDOM

•  PossuiinterfacesespecíficasparacadaobjetodoSVG•  SVGElement,SVGSVGElement,SVGRectElement,

SVGImageElement,SVGPathElement,etc.

•  SVGStyleElementepropriedadestyle(daW3CspecDOM2CSS)

•  Propriedadesclick,mouseover,etc.(W3CspecDOM2Events)

•  SVGColor,SVGPaint,SVGTransform,etc.

•  Amaiorparteapenasexpõepropriedadesdoselementos•  OutroscomoSVGColor,SVGTransformesimilarestêmmétodos

epropriedadesquefacilitamamanipulação

•  Exemplo:SVGStyleElement(igualastyledoHTMLDOM)•  Paraobter,useSVGElement.getStyle()oustyledocument.getElementById("obj").style.fill="yellow"

6

argo

navi

s.co

m.b

r ExemplosdeusodoSVG/XMLDOM

•  document.getElementById(id)varobjeto=document.getElementById("seta");

•  document.documentElementoudocument.rootElementvarfilhos=document.documentElement.childNodes.length;

funcioninit(evt){varsvg=evt.target.ownerDocument.documentRoot;}

•  SVGEvent.targetéumSVGElement:functionprintParent(evt){alert(evt.target.parentNode.nodeName);}

•  Paramanipularatributosevt.target.getAttribute("height");

evt.target.setAttribute("fill","red");

•  Criarelementoeadicioná‐locomofilhode<svg>varrect=document.createElement("rect");rect.setAttribute("width",100);document.rootElement.appendChild(rect); 7

argo

navi

s.co

m.b

r ExemplosimplescomJavaScript

8

<svgwidth="100%"height="100%"xmlns="http://www.w3.org/2000/svg">

<scripttype="text/ecmascript"><![CDATA[functionacende(evt){evt.target.setAttribute("opacity","1.0");}functionapaga(evt){evt.target.setAttribute("opacity","0.4");}]]></script>

<g><rectx="10"y="100"width="45"height="45"fill="red"opacity="0.4"

onmouseover="acende(evt);"onmouseout="apaga(evt);"/><rectx="65"y="100"width="45"height="45"fill="blue"opacity="0.4"

onmouseover="acende(evt);"onmouseout="apaga(evt);"/>...</g></svg>

argo

navi

s.co

m.b

r XML DOM 2: Principais elementos

DocumentFragment

Document

CharacterDataText

Comment

CDATASection

Attr

Element

DocumentType

Notation

Entity

EntityReference

ProcessingInstruction

NodeNodeList

NamedNodeMap

XMLHTTPRequest

SomenteDOM3.0

argo

navi

s.co

m.b

r AlgunsmétodosdainterfaceNode

•  Node appendChild(Node)•  Node cloneNode(boolean)•  NamedNodeMapgetA[ributes() a[ributes•  NodeList getChildNodes() childNodes•  boolean hasA[ributes() •  boolean hasChildNodes()•  Node insertBefore(Node,Node)•  Node removeChild(Node)•  Node replaceChild(Node,Node)•  Node getFirstChild() firstChild•  Node getLastChild() lastChild•  Node getNextSibling() nextSibling•  Node getPreviousSibling() previousSibling•  String getNodeName() nodeName•  short getNodeType() nodeType•  String getNodeValue() nodeValue•  Document getOwnerDocument() ownerDocument•  Node getParentNode() parentNode

10

atalhos!

argo

navi

s.co

m.b

r DOM: tipos de nó

•  DOM usa constantes para identificar tipos de nó (nodeType) Constante (opcional) Tipo valor •  ELEMENT_NODE Element 1 •  ATTRIBUTE_NODE Attr 2 •  TEXT_NODE Text 3 •  CDATA_SECTION_NODE CDATASection 4 •  ENTITY_REFERENCE_NODE EntityReference 5 •  ENTITY_NODE Entity 6 •  PROCESSING_INSTRUCTION_NODE ProcessingInstruction 7 •  COMMENT_NODE Comment 8 •  DOCUMENT_NODE Document 9 •  DOCUMENT_TYPE_NODE DocumentType 10 •  DOCUMENT_FRAGMENT_NODE DocumentFragment 11 •  NOTATION_NODE Notation 12

argo

navi

s.co

m.b

r Métodosparalistasemapas

•  NamedNodeMap•  Node item(int) •  Node getNamedItem(String)•  Node nextNode()•  void reset()•  int getLength() length

•  NodeList•  Node item(int)•  Node nextNode()•  void reset()•  int getLength() length

12

argo

navi

s.co

m.b

r ExemplocomNode

13

<svgxmlns="http://www.w3.org/2000/svg"width="100%"height="100%"onload="numFilhos()"><script><![CDATA[functionnumFilhos(){vardata="Elementoscontidosem<svg>:"+document.documentElement.getChildNodes().length;alert(data);}functioninfoElemento(evt){varatributos=evt.target.attributes;vardata="Element:<"+evt.target.nodeName;for(i=0;i<atributos.length;i++){data+=""+atributos.item(i).name+"='"+atributos.item(i).value+"'";}data+=">\nParent:<"+evt.target.parentNode.nodeName+">";data+="\nPrevioussibling:<"+evt.target.previousSibling.nodeName+">";data+="\nNextsibling:<"+evt.target.nextSibling.nodeName+">";alert(data);}]]></script><g><rectx="50"y="50"height="100"width="100"fill="red"onclick="infoElemento(evt)"/><circlecx="225"cy="100"r="50"fill="blue"onclick="infoElemento(evt)"/><gfont‐size="10pt"><textx="300"y="50">Ubidubiumibilibertas</text></g></g></svg>

argo

navi

s.co

m.b

r InterfaceElement

•  String getA[ribute(String)•  String getA[ributeNS(String,String)•  Akr getA[ributeNode(String)•  Akr getA[ributeNodeNS(String,String)•  NodeList getElementsByTagName(String)•  NodeList getElementsByTagNameNS(String,String)•  String getTagName() tagName•  boolean hasA[ribute(String)•  boolean hasA[ributeNS(String,String)•  void removeA[ribute(String)•  void removeA[ributeNS(String,String)•  void setA[ribute(String,String)•  void setA[ributeNS(String,String,String)

14

argo

navi

s.co

m.b

r InterfacesA[reText

•  Akr•  String getName() name•  Element getOwnerElement() ownerElement•  String getValue() value•  void setValue(String)

•  TexteCharacterData•  void appendData(String)•  String getData() data•  int getLength() length•  void insertData(int,String)•  void replaceData(int,int,String)•  void setData(String)

15

argo

navi

s.co

m.b

r Exemplo:elementoseatributos

16

<svgxmlns="http://www.w3.org/2000/svg"width="100%"height="100%"><script><![CDATA[functiontrocaLugar(){varrect=document.getElementsByTagName("rect").item(0);varcircle=document.getElementsByTagName("circle").item(0);if(rect.getAttribute("x")==50){rect.setAttribute("x","175");circle.setAttribute("cx","100");}else{rect.setAttribute("x","50");circle.setAttribute("cx","225");}}

varangulo=0;functiongira(evt){if(angulo<=360){angulo+=45;}else{angulo=0;}evt.target.setAttribute("transform","rotate("+angulo+",300,50)");}]]></script>

<g><rectx="50"y="50"height="100"width="100"fill="red"onclick="trocaLugar()"/><circlecx="225"cy="100"r="50"fill="blue"/><gfont‐size="10pt"onclick="gira(evt)"><textx="300"y="50">Ubidubiumibilibertas</text></g></g></svg>

argo

navi

s.co

m.b

r SeparandoscriptsdoSVG

•  BoapráJca:façaistosemprequepossível•  Permitereusodasfunçõesporoutrasaplicações(ex:SVG,HTML5,XHTML)•  FacilitadepuraçãodoJS,simplificageraçãodeSVG,aumentaalegibilidade

17

/*funcoesusadasemexemplo2.svg*/

varangulo=0;functiongira(evt){if(angulo<=360){angulo+=45;}else{angulo=0;}evt.target.setAttribute("transform","rotate("+angulo+",300,50)");}

functiontrocaLugar(){varrect=document.getElementsByTagName("rect").item(0);varcircle=document.getElementsByTagName("circle").item(0);if(rect.getAttribute("x")==50){rect.setAttribute("x","175");circle.setAttribute("cx","100");}else{rect.setAttribute("x","50");circle.setAttribute("cx","225");}}

<svgxmlns="http://www.w3.org/2000/svg">

<scripttype="text/ecmascript"xlink:href="script2.js"/>

<g><rectx="50"y="50"height="100"width="100"fill="red"onclick="trocaLugar()"/>...<gfont‐size="10pt"onclick="gira(evt)"><textx="300"y="50">Ubidubiumibilibertas</text></g></g></svg>

script2.js

exemplo2.svg

argo

navi

s.co

m.b

r DOM2.0comnamespaces

•  Usemétodosquelevamemcontaonamespace•  Énecessárioparaacessarelementoseatributosqueusamnamespaces(ex:xlink)

•  ÉnecessárioquandoseusaSVGcomnamespaces(ex:quandousadojuntocomXHTML,XSL‐FO,etc.)

•  EmvezdegetAkribute,getElement,etc.•  UsegetAkributeNS,getElementNS,etc.

18

varsvgNS="http://www.w3.org/2000/svg";varxlinkNS="http://www.w3.org/1999/xlink";

varcircle=document.createElementNS(svgNS,"circle");circle.setAttributeNS(null,"cx",500);circle.setAttributeNS(null,"cy",500);circle.setAttributeNS(xlinkNS,"href","http://www.a/com");

argo

navi

s.co

m.b

r InterfaceDocument

•  Akr createA[ribute(String)

•  Akr createA[ributeNS(String,String)

•  Element createElement(String)

•  Element createElementNS(String,String)

•  Text createTextNode(String)

•  DocumentType getDocType() docType

•  Element getDocumentElement() documentElement

•  Element getDocumentById(String)

•  NodeList getElementsByTagName(String)

•  NodeList getElementsByTagNameNS(String,String)

19

argo

navi

s.co

m.b

r Exemplo:criandoelementos

20

varsvgNS="http://www.w3.org/2000/svg";

functioncriarCirculo(evt){varrandomX=Math.floor(Math.random()*document.rootElement.getAttributeNS(null,"width"));varrandomY=Math.floor(Math.random()*document.rootElement.getAttributeNS(null,"height"));varcolor="rgb("+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+","+Math.floor(Math.random()*256)+")";

varcirculo=document.createElementNS(svgNS,"circle");circulo.setAttributeNS(null,"cx",randomX);circulo.setAttributeNS(null,"cy",randomY);circulo.setAttributeNS(null,"fill",color);circulo.setAttributeNS(null,"r",evt.target.getAttributeNS(null,"r"));

circulo.addEventListener("click",criarCirculo,false);

evt.target.parentNode.appendChild(circulo);}

<svgxmlns="http://www.w3.org/2000/svg"width="500"height="500"><scripttype="text/ecmascript"xlink:href="script_3.js"/><circlecx="125"cy="40"r="5"fill="green"onclick="criarCirculo(evt)"/><circlecx="225"cy="100"r="10"fill="blue"onclick="criarCirculo(evt)"/><circlecx="325"cy="170"r="15"fill="red"onclick="criarCirculo(evt)"/></svg>

script_3.js

argo

navi

s.co

m.b

r AnimaçãousandoSVGDOM

21

<svgwidth="500px"height="500px"viewBox="00500500"xmlns="http://www.w3.org/2000/svg"version="1.1"xmlns:xlink="http://www.w3.org/1999/xlink">

<scripttype="text/ecmascript"xlink:href="script_5.js"/>

<linex1="50"y1="0"x2="50"y2="200"stroke‐width="2"stroke="black"/><linex1="450"y1="0"x2="450"y2="200"stroke‐width="2"stroke="black"/><circlecx="50"cy="100"r="17.64"fill="black"></circle><circlecx="150"cy="100"r="17.64"fill="blue"></circle><circlecx="250"cy="100"r="17.64"fill="red"></circle><circlecx="350"cy="100"r="17.64"fill="green"></circle>

<gid="barquinho"transform="translate(50,140)"onclick="iniciarMovimento(evt)"><pathd="M‐25,‐12.5C‐25,025,025,‐12.5L0,‐100.5z"fill="yellow"stroke="red"stroke‐width="7.06"></path></g></svg>

varx=0.0;varfim=400.0;varbarquinho;

functioniniciarMovimento(evt){barquinho=evt.target;mover();}functionmover(){if(x>=fim){return;}x=x+1;barquinho.setAttributeNS(null,'transform',"translate("+x+",0)");if(x>50){barquinho.setAttributeNS(null,'opacity',(fim‐x)/fim);}setTimeout("mover()",30);}

UsefunçõesrecursivascomsetTimeout()paraanimaçõessimples

script_5.js