Movatterモバイル変換


[0]ホーム

URL:


Chapter 15: Scripting and Interactivity

15.1. Introduction

SVG content can be interactive (i.e., responsive touser-initiated events) by utilizing the following features inthe SVG language:

This chapter describes:

Related information can be found in other chapters:

15.2. Supported events

SVG 2 Requirement:Support anchor change events.
Resolution:SVG 2 will consider adding HTML document wide events (including hashchange) apply to SVG documents where they make sense.
Purpose:To allow authors to use the same set of event listener attributes on a root SVG element that they can on an HTML body or root element.
Owner:Cameron (ACTION-3278)
SVG 2 Requirement:Have event listener attributes on an appropriate interface.
Resolution:SVG 2 will move all events listener attributes to Element, in accordance with the similar move in HTML.
Purpose:To align with HTML.
Owner:Cameron (ACTION-3283)
SVG 2 Requirement:Introduce evt as an alias to event in event handlers.
Resolution:We decide to resolve ISSUE-2176 by introducing evt as an alias to event in event handlers.
Purpose:To align with HTML.
Owner:Cameron (ACTION-3093)
SVG 2 Requirement:Support drag & drop functionality.
Resolution:SVG 2 may require drag & drop functionality, and we'll investigate HTML5's functionality for that.
Purpose:To allow easier drag & drop in SVG, and to align with HTML.
Owner:Erik (ACTION-3328)

The following aspects of SVG are affected by events:

A number of events defined in SVG 1.1,SVGLoad,SVGError etc, have been replaced with the equivalentunprefixed events defined inUI EVENTSandHTML.

There should be some more modern examples of using events in svg, e.g touch events (w reference to touch events spec).Device orientation events might also be of interest.

The following table lists the events defined by this specification, or that have further requirements or clarifications compared to the specification(s) where they are defined.

TheEvent name in thefirst column is the name to use within SVG'sanimation elements todefine the events which can start or end animations. TheUI Event name in the second column is the name to use whendefiningDOM event listeners([DOM], section 3.6).

For events not listed in the table, such as events introduced in HTML or UI Events,the respectiveevent type is the name to use within SVG'sanimation elements.

Requirements in the table on whether an event of a given typebubbles or is cancelable apply only to events that are created anddispatched by the user agent. Events of those types created from scriptusing thecreateEvent method on theDocument interface can be made to bubbleor be cancelable with theinitEventmethod.

Event name and descriptionUI Event nameEvent categoryEvent attribute name

load

The load event is dispatched only tostructurally external elements and to theWindow, when the corresponding external resources have finished loading. Note that due to it'srelationship withWindow the load event onsvg elements is only dispatched when all resources in the document have been completely loaded.

The load event and the error event onstructurally external elements are mutually exclusive, only one of these events must be dispatched when processing the element in question.

load events do not bubble and are not cancelable.

In previous SVG specifications the load event was called SVGLoad and could be dispatched immediately after parsing an element but before the related resource(s) were fully loaded.

(same)noneonload

unload

Only applicable tooutermost svg elements. The unload event occurs when the DOM implementation removes a document from a window or frame.

unload events do not bubble and are not cancelable.

(same)noneonunload

error

The error event occurs when astructurally external element does not load properly or when an error occurs during script execution.

error events bubble but are not cancelable.

(same)noneonerror

beginEvent

Occurs when an animation element begins. For details, see the description of Interface TimeEvent in the SMIL Animation specification.

nonenoneonbegin

endEvent

Occurs when an animation element ends. For details, see the description of Interface TimeEvent in the SMIL Animation specification.

nonenoneonend

repeatEvent

Occurs when an animation element repeats. It is raised each time the element repeats, after the first iteration. For details, see the description of Interface TimeEvent in the SMIL Animation specification.

nonenoneonrepeat

Details on the parameters passed to event listeners for theevent types for UI Events can be found in the ([uievents]) and ([DOM]) specifications.For other event types, the parameters passed to event listenersare described elsewhere in this specification.

Likewise,event-value timing specifiersused inanimation elementbegin andendattributes are resolved to concrete times only in response to "bubbling" and"at target" phase events dispatched to the relevant element.

15.2.1. Relationship with UI Events

The SVG DOM is compatible with all interfaces defined in, andall the event types from,UI Events,and the event types defined inClipboard API and events([uievents], [clipboard-apis]).

All elements in the SVG namespace supportevent attributes for these events;matching IDL properties are included in the baseSVGElement interfacevia theGlobalEventHandlers andDocumentAndElementEventHandlers mixins, respectively.

As part of SVG DOM support, conforming SVG softwaremust support all (non-deprecated, non-obsolete) event typesdefined in these specifications,if the relevant events could occur in the software's use.SVG software that does not support userinteractionshould nonetheless implement support for events that can fire without interaction,such asload anderror events.

SVG animation elements (defined in theSVG Animations Level 2 specification) support additional events and event attributes. The following event types are triggered due to state changes in animations.

Theevent attributes for these animation events have no effect on other elements.

15.3. User interface events

On user agents which support interactivity, it is common forauthors to define SVG documents such that they are responsiveto user interface events. Among the set of possible user eventsarepointer events,keyboard events, and document events.

In response to user interface (UI) events, the author mightstart an animation, perform a hyperlink to another Web page,highlight part of the document (e.g., change the color of thegraphics elements which are under the pointer), initiate a"roll-over" (e.g., cause some previously hidden graphicselements to appear near the pointer) or launch a script whichcommunicates with a remote database.

15.4. Pointer events

User interface events that occur because of user actionsperformed on a pointer device are called pointer events.

Many systems support pointer devices such as a mouse ortrackball. On systems which use a mouse, pointer events consistof actions such as mouse movements and mouse clicks. On systemswith a different pointer device, the pointing device oftenemulates the behavior of the mouse by providing a mechanism forequivalent user actions, such as a button to press which isequivalent to a mouse click.

For each pointer event, the SVG user agent determines thetarget element of a given pointer event. The targetelement is the topmost graphics element whose relevantgraphical content is under the pointer at the time of theevent. (See propertypointer-events for a descriptionof how to determine whether an element's relevant graphicalcontent is under the pointer, and thus in which circumstancesthat graphic element can be the target element for a pointerevent.) When an element is not displayed (i.e., when thedisplay property on that elementor one of its ancestors has a value ofnone), that element cannot be thetarget of pointer events.

If a target element for the pointer event exists, thenthe event is dispatched to that element according to thenormalevent flow([uievents], section 3.1).For shadow trees created by theuse element or via script,the event must followDispatching Events [dom]

If a target element for the pointer event does not exist,then the event is ignored.

15.5. Hit-testing and processing order for user interface events

hit-testing
The process of determining whether a pointer intersects a givengraphics element. Hit-testing is used in determining which element to dispatch a mouse event to, which might be done in response to the user moving the pointing device, or by changes in the position, shape and other attributes of elements in the document. Hit-testing is also known ashit detection orpicking. See also the definition of thepointer-events property.

There are two distinct aspects of pointer-device interaction with an element or area:

  1. hit-testing, to determine if a pointer event (such as a mouse movement or mouse click) occurred within the interaction area of an element, and the subsequent DOM event flow;
  2. functional processing of actions associated with any relevant element.

15.5.1. Hit-testing

Determining whether a pointer event results in a positivehit-testdepends upon the position of the pointer, the size and shape of thegraphics element, and the computed value of thepointer-eventsproperty on the element. The definition of thepointer-eventsproperty below describes the exact region that is sensitive to pointerevents for a given type of graphics element.

Note that thesvg element is not agraphics element, and inaConforming SVG Stand-Alone Fileaoutermost svg element will never be the target of pointer events,though events can bubble to this element.If a pointer event does not result in a positivehit-test on agraphics element, then it should evoke any user-agent-specific windowbehavior, such as a presenting a context menu or controls to allow zoomingand panning of an SVG document fragment.

This specification does not define the behavior of pointer events on theoutermost svg element for SVG images which are embedded by referenceor inclusion within another document, e.g., whether theoutermost svg elementembedded in an HTML document intercepts mouse click events; future specificationsmay define this behavior, but for the purpose of this specification, the behavioris implementation-specific.

15.5.2. Event processing

An element which is the target of a user interface event may haveparticular interaction behaviors, depending upon the type of element andwhether it has explicit associated interactions, such as scripted eventlisteners, CSS pseudo-classes matches, or declarative animationswith event-based timing. The algorithm and order for processinguser interface events for a given target element, after dispatching theDOM event, is as follows:

  1. If an event handler registered on this element invokes thepreventDefault() DOM method, then no further processing for this element is performed, and the event follows theevent dispatch and DOM event flow processing ([uievents]);
  2. If the element has an associated title or description, such as atitle element, and the user agent supports the display of such information (e.g. via a tooltip or status-bar message), that information should be displayed, as appropriate to the type of pointer event;
  3. If the element matches any relevantdynamic pseudo-class selectors appropriate to the type of pointer event, such as:hover,:active, or:focus as described in [CSS2], section 5.11, then the relevant class properties are applied;
  4. If the element and the event type are associated with the activation or cancelation of declarative animation though the use ofevent-value timing specifiers, any corresponding instance times must be resolved, and any conseqential actions of this instance time resolution (such as immediately starting or stopping the animation) must be performed;
  5. If the element is a hyperlink (e.g., it is a descendant element of ana element), and the pointer event is of a type that activates that hyperlink (e.g. via a mouse click), and if the hyperlink traversal changes the context of the content (e.g. opens a different document, or moves the pointer away from this element by moving to another part of the same document), then no further processing for this element is performed;
  6. If the element is atext content element, and the event type is one which the user agent recognizes as part of a text-selection operation (e.g., a mouse click and drag, or a double-click), then thetext selection algorithm is performed;
  7. If the event type is one which the user agent associates with the evocation of special user-interface controls (e.g., a right-click or command-click evoking a context menu), the user agent should evoke such user-agent-specific behavior, such as presenting a context menu or controls to allow zooming and panning of an SVG document fragment.

15.6. The ‘pointer-events’ property

In different circumstances, authors may want to controlunder what conditions particular graphic elements can becomethe target of pointer events. For example, the author mightwant a given element to receive pointer events only when thepointer is over the stroked perimeter of a given shape. Inother cases, the author might want a given element to ignorepointer events under all circumstances so that graphicalelements underneath the given element will become the target ofpointer events.

The effects of masking and clipping differ with respect topointer events. A clip path isa geometric boundary, and a given point is clearly either inside or outside thatboundary; thus, pointer events must be captured normally over the rendered areasof a clipped element, but must not be captured over the clipped areas, as describedin the definition ofclipping paths.By contrast, a mask is not a binary transition, but a pixel operation, anddifferent behavior for fully transparent and almost-but-not-fully-transparent maybe confusingly arbitrary; as a consequence, for elements with a mask applied,pointer events must still be captured even in areas where the mask goes to zeroopacity. If an author wishes to achieve an effect where the transparent partsof a mask allow pointer events to pass to an element below, a combination ofmasking and clipping may be used.

Thefilter property has no effect on pointer eventsprocessing, and must in this context be treated as if thefilterwasn't specified.

For example, suppose a circle with astroke ofred (i.e., the outline is solid red) and afill ofnone (i.e., the interior is notpainted) is rendered directly on top of a rectangle with afill ofblue. The author might want the circle to bethe target of pointer events only when the pointer is over the perimeter ofthe circle. When the pointer is over the interior of the circle, the authormight want the underlying rectangle to be the target element of pointerevents.

Thepointer-events property specifies under what circumstances agiven element can be the target element for a pointer event. It affectsthe circumstances under which the following are processed:

Name:pointer-events
Value:bounding-box | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | none
Initial:visiblePainted
Applies to:container elements,graphics elements anduse
Inherited:yes
Percentages:N/A
Media:visual
Computed value:as specified
Animatable:yes
bounding-box
The given element must be a target element for pointer events when the pointer is over thebounding box of the element.
visiblePainted
The given element can be the target element for pointer events when thevisibility property is set tovisible and when the pointer is over a "painted" area. The pointer is over a painted area if it is over the interior (i.e., fill) of the element and thefill property has an actual value other thannone or it is over the perimeter (i.e., stroke) of the element and thestroke property is set to a value other thannone.
visibleFill
The given element can be the target element for pointer events when thevisibility property is set tovisible and when the pointer is over the interior (i.e., fill) of the element. The value of thefill property does not affect event processing.
visibleStroke
The given element can be the target element for pointer events when thevisibility property is set tovisible and when the pointer is over the perimeter (i.e., stroke) of the element. The value of thestroke property does not affect event processing.
visible
The given element can be the target element for pointer events when thevisibility property is set tovisible and the pointer is over either the interior (i.e., fill) or the perimeter (i.e., stroke) of the element. The values of thefill andstroke do not affect event processing.
painted
The given element can be the target element for pointer events when the pointer is over a "painted" area. The pointer is over a painted area if it is over the interior (i.e., fill) of the element and thefill property has an actual value other thannone or it is over the perimeter (i.e., stroke) of the element and thestroke property has an actual value other thannone. The value of thevisibility property does not affect event processing.
fill
The given element can be the target element for pointer events when the pointer is over the interior (i.e., fill) of the element. The values of thefill andvisibility properties do not affect event processing.
stroke
The given element can be the target element for pointer events when the pointer is over the perimeter (i.e., stroke) of the element. The values of thestroke andvisibility properties do not affect event processing.
all
The given element can be the target element for pointer events whenever the pointer is over either the interior (i.e., fill) or the perimeter (i.e., stroke) of the element. The values of thefill,stroke andvisibility properties do not affect event processing.
none
The given element does not receive pointer events.

For text elements, hit-testing is performed on a character cell basis:

For raster images, hit-testing is either performed on awhole-image basis (i.e., the rectangular area for the image isone of the determinants for whether the image receives theevent) or on a per-pixel basis (i.e., the alpha values forpixels under the pointer help determine whether the imagereceives the event):

Note that for raster images, the values of propertiesopacity,fill-opacity,stroke-opacity,fill andstroke do not affect event processing.

15.7. Magnification and panning

SVG 2 Requirement:Support level of detail control.
Resolution:We will support Level of Detail control in SVG 2.
Purpose:Control visibility of elements based on zoom level (useful, for example, in mapping).
Owner:Doug (no action)
Note:SeeTiling and Layering Module for SVG 1.2 Tiny.

Magnification represents a complete, uniformtransformation on an SVG document fragment, where the magnify operation scalesall graphical elements by the same amount. A magnify operationhas the effect of a supplemental scale and translatetransformation placed at the outermost level on the SVGdocument fragment (i.e., outside theoutermost svg element).

Panning represents a translation (i.e., a shift)transformation on an SVG document fragment in response to auser interface action.

SVG user agents that operate in interaction-capable userenvironments are required to support the ability to magnify and pan.

Theoutermost svg elementin an SVG document fragment has attributezoomAndPan, which takes the possiblevalues ofdisable andmagnify, with thedefault beingmagnify.

The zoomAndPan attribute is at risk, it has no known implementationsand is unlikely to be implemented. SeeGithub issue #56.

NameValueInitial valueAnimatable
zoomAndPan[ disable | magnify ]disableno

Ifdisable, the user agent shall disable any magnification and panning controls and not allow the user to magnify or pan on the given document fragment.

Ifmagnify, in environments that support user interactivity, the user agent shall provide controls to allow the user to perform a "magnify" operation on the document fragment.

If azoomAndPan attribute isassigned to an innersvgelement, thezoomAndPan settingon the innersvg elementwill have no effect on the SVG user agent.

15.8. Focus

SVG uses the samefocus model as HTML, modified for SVG as described in this section. At most one element in each document isfocused at a time; if the document as a whole has system focus, this element becomes the target of all keyboard events.

When an element is focused, the element matches theCSS:focus pseudo-class. Interactive user agents must visually indicate focus (usually with an outline) when the focus changes because of a user input event from the keyboard or other non-pointing device and may indicate focus at all times. Authors may use the:focus pseudo-class to replace the visual indication with one more suitable to the graphic, (such as a stroke on a shape) but should not use it to remove visual indications of focus completely.

The following SVG elements arefocusable in an interactive document. Anyinstance of such an element in ause-element shadow tree is also focusable. For the purpose of the HTML focus model, interactive user agents must treat them asfocusable areas whosetabindex focus flag should be set:

In the case of user-agent supplied controls, the element may have more than one focusable area, for each sub-control.

In addition, alla elements that are valid links arefocusable, and theirtabindex focus flag must be setunless the user agent normally provides an alternative method of keyboard traversal of links.

For compatibility with content that used theSVG Tiny 1.2focusable attribute, user agents should treat an element with a value oftrue for that attribute as focusable. In new content, authors should either omit thefocusable attribute or use it only in combination with a correspondingtabindex value of0.

User agents may treat other elements as focusable, particularly if keyboard interaction is the only or primary means of user input. In particular, user agents may support using keyboard focus to revealtitle element text as tooltips, and may allow focus to reach elements which have been assigned listeners for mouse, pointer, or focus events. Authors should not rely on this behavior; all interactive elements should directly support keyboard interaction.

The sequential focus order is generated from the set of allfocusable elements, processingtabindex attributes on SVG elements in the same way astabindex attributes on HTML elements. Content within ause-element shadow tree is inserted in the focus order as if it was child content of theuse element.

Anon-rendered element can never receive focus, regardless of the value of thetabindex attribute, If a script programmatically assigns focus to a non-rendered or otherwise un-focusable element, the focusing call is aborted. Note, however, that an element that is not visible or onscreen may still berendered.

When the user agent supports scrolling or panning of the SVG document, and focus moves to an element that is currently outside the SVG viewport, the user agent should scroll or pan the document until the focused element is within the SVG viewport.

As in HTML, an SVG element that isfocusable but does not have a definedactivation behavior has an activation behaviour that does nothing (unless a script specifically responds to it).

This means that an element that is only focusable because of itstabindex attribute will fire aclick event in response to a non-mouse activation (e.g. hitting the "enter" key while the element hasfocus).

For documents that contain a mix of inline HTML and SVG, focus is handled for the document as a whole (with a combined sequential focus order), not with each inline SVG or HTML fragment as an isolated subdocument.

For example, in the following document, pressing Tab would cycle the focus between elements A, B and C, in that order.

<!DOCTYPE html><button tabindex="1">First thing</button><button tabindex="2">Third thing</button><svg width="200" height="200">  <text tabindex="1" x="100" y="100">Second thing</text></svg>

Note that SVG elements do not have an equivalent of HTML'saccesskeyattribute.

15.9. Event attributes

event attribute
An event attribute always has a name that starts with "on" followed by the name of the event for which it is intended. It specifies some script to run when the event of the given type is dispatched to the element on which the attribute is specified.

For everyevent type that theuser agent supports, SVG supports that as an event attribute, following the same requirements as forevent handler content attributes [HTML]. Theevent attributes are available on allSVG elements.

The contents of event attributes are always interpreted as ECMAScript, as if processed with the media type'application/ecmascript'. [rfc2046][rfc4329]

Event attributes are notanimatable.

Implementors may view the setting of event attributes as the creation and registration of anEventListener on theEventTarget. Such event listeners are invoked only for the "bubbling" and "at target" phases, as if false were specified for theuseCapture argument toaddEventListener. ThisEventListener behaves in the same manner as any other which may be registered on theEventTarget.

If the attribute representing the event listener is changed, this may be viewed as the removal of the previously registeredEventListener and the registration of a new one. Futhermore, no specification is made as to the order in which event attributes will receive the event with regards to the other EventListeners on theEventTarget.

In ECMAScript, one way to establish an event listener is to define a function and pass that function to theaddEventListener method:

function myAction1(evt) {  // process the event}// ... later ...myElement.addEventListener("click", myAction1, false)

In ECMAScript, the character data content of anevent attribute becomes the definition of the ECMAScript function which gets invoked in response to the event. As with all registered ECMAScript event listener functions, this function receives anEvent object as a parameter, and the name of the Event object isevt. For example, it is possible to write:

<rect .../>

which will pass theEvent objectevt into functionMyClickHandler.

15.9.1. Animation event attributes

Below are the definitions for theanimation event attributes. These can be specified on theanimation elements.

Attribute definitions:

NameValueInitial valueAnimatable
onbegin,onend,onrepeat(see below)(none)no
Specifies some script to execute when "bubbling" or "at target" phase listeners for the corresponding event are fired on the element the attribute is specified on. Seesupported events table to determine which event each of these event attributes corresponds to. There are no restrictions on the values of this attribute.

15.10. The‘script’ element

SVG 2 Requirement:Consider allowing async/defer onscript.
Resolution:SVG 2 will allow async/defer on‘script’.
Purpose:To align with HTML.
Owner:Cameron (ACTION-3280)
SVG 2 Requirement:Incorporate SVG Tiny 1.2 script processing model.
Resolution:SVG 2 will define how inline scriptable content will be processed, in a compatible way to HTML5
Purpose:To have consistent script running behavior across HTML and SVG.
Owner:Cameron (ACTION-3282)

Ascript element is equivalent to thescript element in HTML and thus is the place for scripts (e.g., ECMAScript). Any functions defined within anyscript element have a "global" scope across the entire current document.

The script's text content is never directly rendered; thedisplay value for thescript element must always be set tonone by theuser agent style sheet, and this declaration must have importance over any other CSS rule or presentation attribute.

Before attempting to execute thescript element the resolved media type value fortype must be inspected. If theSVG user agent does not support the scripting language then thescript element must not be executed.

This example defines a functioncircle_click which is called by theonclick event attribute on thecircle element. The drawing below on the left is the initial image. The drawing below on the right shows the result after clicking on the circle.

  <?xml version="1.0" standalone="no"?>  <svg width="6cm" height="5cm" viewBox="0 0 600 500"       xmlns="http://www.w3.org/2000/svg">    <desc>Example script01 - invoke an ECMAScript function from an onclick event    </desc>    <!-- ECMAScript to change the radius with each click -->    <script type="application/ecmascript"> <![CDATA[      function circle_click(evt) {        var circle = evt.target;        var currentRadius = circle.getAttribute("r");        if (currentRadius == 100)          circle.setAttribute("r", currentRadius*2);        else          circle.setAttribute("r", currentRadius*0.5);      }    ]]> </script>    <!-- Outline the drawing area with a blue line -->    <rect x="1" y="1" width="598" height="498" fill="none" stroke="blue"/>    <!-- Act on each click event -->    <circle cx="300" cy="225" r="100"            fill="red"/>    <text x="300" y="480"          font-family="Verdana" font-size="35" text-anchor="middle">      Click on circle to change its size    </text>  </svg>
An example demonstrating the effect of theonclick event handler on an SVG shape.
An example demonstrating how to invoke an ECMAScript function from an onclick event — before first click An example demonstrating how to invoke an ECMAScript function from an onclick event — after first click

View this example as SVG (SVG-enabled browsers only)

script
Categories:
Never-rendered element,structurally external element
Content model:
Character data.
Attributes:
DOM Interfaces:

Attribute definitions:

NameValueInitial valueAnimatable
crossorigin[ anonymous | use-credentials ]?(see HTML definition of attribute)yes

The crossorigin attribute is aCORS settings attribute, and unless otherwise specified follows the same processing rules as in html [HTML].

NameValueInitial valueAnimatable
type(see below)application/ecmascriptno
Identifies the scripting language for the givenscript element. The value must be a valid media type, perMultipurpose Internet Mail Extensions (MIME) Part Two [rfc2046]. If atype is not provided, then the default scripting language assumed is ECMAScript, as if processed with the‘application/ecmascript’ media type.
NameValueInitial valueAnimatable
hrefURL[URL](none)no
AnURL reference to an external resource containing the script code. Refer to the common handling defined forURL reference attributes anddeprecated XLink attributes.

The URL is processed and the resource is fetchedas described in the Linking chapter.

15.11. DOM interfaces

15.11.1. Interface SVGScriptElement

AnSVGScriptElement object represents ascript element in the DOM.

[Exposed=Window]interfaceSVGScriptElement :SVGElement {  attribute DOMStringtype;  attribute DOMString?crossOrigin;};SVGScriptElement includesSVGURIReference;

Thetype IDL attributereflects thetype content attribute.

ThecrossOrigin IDLattributereflects thecrossorigin content attribute.


[8]ページ先頭

©2009-2025 Movatter.jp