⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 helper_functions.js

📁 《SVG开发实践》源代码
💻 JS
📖 第 1 页 / 共 2 页
字号:
 function statusChange(statusText) {	document.getElementById("statusText").firstChild.nodeValue = "Statusbar: " + statusText;}/** * scales an SVG element, requires that the element has an x and y attribute (e.g. circle, ellipse, use element, etc.) * @param {dom::Event} evt		the evt object that triggered the scaling * @param {Number} factor	the scaling factor * @version 1.0 (2007-04-30) */function scaleObject(evt,factor) {	//reference to the currently selected object	var element = evt.currentTarget;	var myX = element.getAttributeNS(null,"x");	var myY = element.getAttributeNS(null,"y");	var newtransform = "scale(" + factor + ") translate(" + (myX * 1 / factor - myX) + " " + (myY * 1 / factor - myY) +")";	element.setAttributeNS(null,'transform', newtransform);}/** * returns the transformation matrix (ctm) for the given node up to the root element * the basic use case is to provide a wrapper function for the missing SVGLocatable.getTransformToElement method (missing in ASV3) * @param {svg::SVGTransformable} node		the node reference for the SVGElement the ctm is queried * @return CTM								the current transformation matrix from the given node to the root element * @type svg::SVGMatrix * @version 1.0 (2007-05-01) * @credits <a href="http://www.kevlindev.com/tutorials/basics/transformations/toUserSpace/index.htm">Kevin Lindsey (toUserSpace)</a> * @see #getTransformToElement */function getTransformToRootElement(node) { 	try {		//this part is for fully conformant players (like Opera, Batik, Firefox, Safari ...)		var CTM = node.getTransformToElement(document.documentElement);	}	catch (ex) {		//this part is for ASV3 or other non-conformant players		// Initialize our CTM the node's Current Transformation Matrix		var CTM = node.getCTM();		// Work our way through the ancestor nodes stopping at the SVG Document		while ( ( node = node.parentNode ) != document ) {			// Multiply the new CTM to the one with what we have accumulated so far			CTM = node.getCTM().multiply(CTM);		}	}	return CTM;}/** * returns the transformation matrix (ctm) for the given dom::Node up to a different dom::Node * the basic use case is to provide a wrapper function for the missing SVGLocatable.getTransformToElement method (missing in ASV3) * @param {svg::SVGTransformable} node			the node reference for the element the where the ctm should be calculated from * @param {svg::SVGTransformable} targetNode	the target node reference for the element the ctm should be calculated to * @return CTM									the current transformation matrix from the given node to the target element * @type svg::SVGMatrix * @version 1.0 (2007-05-01) * @credits <a href="http://www.kevlindev.com/tutorials/basics/transformations/toUserSpace/index.htm">Kevin Lindsey (toUserSpace)</a> * @see #getTransformToRootElement */function getTransformToElement(node,targetNode) {    try {        //this part is for fully conformant players        var CTM = node.getTransformToElement(targetNode);    }    catch (ex) {  		//this part is for ASV3 or other non-conformant players		// Initialize our CTM the node's Current Transformation Matrix		var CTM = node.getCTM();		// Work our way through the ancestor nodes stopping at the SVG Document		while ( ( node = node.parentNode ) != targetNode ) {			// Multiply the new CTM to the one with what we have accumulated so far			CTM = node.getCTM().multiply(CTM);		}    }    return CTM;}/** * converts HSV to RGB values * @param {Number} hue		the hue value (between 0 and 360) * @param {Number} sat		the saturation value (between 0 and 1) * @param {Number} val		the value value (between 0 and 1) * @return rgbArr			the rgb values (associative array or object, the keys are: red,green,blue), all values are scaled between 0 and 255 * @type Object * @version 1.0 (2007-05-01) * @see #rgb2hsv */function hsv2rgb(hue,sat,val) {	var rgbArr = new Object();	if ( sat == 0) {		rgbArr["red"] = Math.round(val * 255);		rgbArr["green"] = Math.round(val * 255);		rgbArr["blue"] = Math.round(val * 255);	}	else {		var h = hue / 60;		var i = Math.floor(h);		var f = h - i;		if (i % 2 == 0) {			f = 1 - f;		}		var m = val * (1 - sat); 		var n = val * (1 - sat * f);		switch(i) {			case 0:				rgbArr["red"] = val;				rgbArr["green"] = n;				rgbArr["blue"] = m;				break;			case 1:				rgbArr["red"] = n;				rgbArr["green"] = val;				rgbArr["blue"] = m;				break;			case 2:				rgbArr["red"] = m;				rgbArr["green"] = val;				rgbArr["blue"] = n;				break;			case 3:				rgbArr["red"] = m;				rgbArr["green"] = n;				rgbArr["blue"] = val;				break;			case 4:				rgbArr["red"] = n;				rgbArr["green"] = m;				rgbArr["blue"] = val;				break;			case 5:				rgbArr["red"] = val;				rgbArr["green"] = m;				rgbArr["blue"] = n;				break;			case 6:				rgbArr["red"] = val;				rgbArr["green"] = n;				rgbArr["blue"] = m;				break;		}		rgbArr["red"] = Math.round(rgbArr["red"] * 255);		rgbArr["green"] = Math.round(rgbArr["green"] * 255);		rgbArr["blue"] = Math.round(rgbArr["blue"] * 255);	}	return rgbArr;}/** * converts RGB to HSV values * @param {Number} red		the hue value (between 0 and 255) * @param {Number} green	the saturation value (between 0 and 255) * @param {Number} blue		the value value (between 0 and 255) * @return hsvArr			the hsv values (associative array or object, the keys are: hue (0-360),sat (0-1),val (0-1)) * @type Object * @version 1.0 (2007-05-01) * @see #hsv2rgb */function rgb2hsv(red,green,blue) {	var hsvArr = new Object();	red = red / 255;	green = green / 255;	blue = blue / 255;	myMax = Math.max(red, Math.max(green,blue));	myMin = Math.min(red, Math.min(green,blue));	v = myMax;	if (myMax > 0) {		s = (myMax - myMin) / myMax;	}	else {		s = 0;	}	if (s > 0) {		myDiff = myMax - myMin;		rc = (myMax - red) / myDiff;		gc = (myMax - green) / myDiff;		bc = (myMax - blue) / myDiff;		if (red == myMax) {			h = (bc - gc) / 6;		}		if (green == myMax) {			h = (2 + rc - bc) / 6;		}		if (blue == myMax) {			h = (4 + gc - rc) / 6;		}	}	else {		h = 0;	}	if (h < 0) {		h += 1;	}	hsvArr["hue"] = Math.round(h * 360);	hsvArr["sat"] = s;	hsvArr["val"] = v;	return hsvArr;}/** * populates an array such that it can be addressed by both a key or an index nr, * note that both Arrays need to be of the same length * @param {Array} arrayKeys		the array containing the keys * @param {Array} arrayValues	the array containing the values * @return returnArray			the resulting array containing both associative values and also a regular indexed array * @type Array * @version 1.0 (2007-05-01) */function arrayPopulate(arrayKeys,arrayValues) {	var returnArray = new Array();	if (arrayKeys.length != arrayValues.length) {		alert("error: arrays do not have the same length!");	}	else {		for (i=0;i<arrayKeys.length;i++) {			returnArray[arrayKeys[i]] = arrayValues[i];		}	}	return returnArray;}/** * Wrapper object for network requests, uses getURL or XMLHttpRequest depending on availability * The callBackFunction receives a XML or text node representing the rootElement * of the fragment received or the return text, depending on the returnFormat.  * See also the following <a href="http://www.carto.net/papers/svg/network_requests/">documentation</a>. * @class this is a wrapper object to provide network request functionality (get|post) * @param {String} url												the URL/IRI of the network resource to be called * @param {Function|Object} callBackFunction						the callBack function or object that is called after the data was received, in case of an object, the method 'receiveData' is called; both the function and the object's 'receiveData' method get 2 return parameters: 'node.firstChild'|text (the root element of the XML or text resource), this.additionalParams (if defined)  * @param {String} returnFormat										the return format, either 'xml' or 'json' (or text) * @param {String} method											the method of the network request, either 'get' or 'post' * @param {String|Undefined} postText								the String containing the post text (optional) or Undefined (if not a 'post' request) * @param {Object|Array|String|Number|Undefined} additionalParams	additional parameters that will be passed to the callBackFunction or object (optional) or Undefined * @return a new getData instance * @type getData * @constructor * @version 1.0 (2007-02-23) */function getData(url,callBackFunction,returnFormat,method,postText,additionalParams) {	this.url = url;	this.callBackFunction = callBackFunction;	this.returnFormat = returnFormat;	this.method = method;	this.additionalParams = additionalParams;	if (method != "get" && method != "post") {		alert("Error in network request: parameter 'method' must be 'get' or 'post'");	}	this.postText = postText;	this.xmlRequest = null; //@private reference to the XMLHttpRequest object} /** * triggers the network request defined in the constructor */getData.prototype.getData = function() {	//call getURL() if available	if (window.getURL) {		if (this.method == "get") {			getURL(this.url,this);		}		if (this.method == "post") {			postURL(this.url,this.postText,this);		}	}	//or call XMLHttpRequest() if available	else if (window.XMLHttpRequest) {		var _this = this;		this.xmlRequest = new XMLHttpRequest();		if (this.method == "get") {			if (this.returnFormat == "xml") {				this.xmlRequest.overrideMimeType("text/xml");			}			this.xmlRequest.open("GET",this.url,true);		}		if (this.method == "post") {			this.xmlRequest.open("POST",this.url,true);		}		this.xmlRequest.onreadystatechange = function() {_this.handleEvent()};		if (this.method == "get") {			this.xmlRequest.send(null);		}		if (this.method == "post") {			//test if postText exists and is of type string			var reallyPost = true;			if (!this.postText) {				reallyPost = false;				alert("Error in network post request: missing parameter 'postText'!");			}			if (typeof(this.postText) != "string") {				reallyPost = false;				alert("Error in network post request: parameter 'postText' has to be of type 'string')");			}			if (reallyPost) {				this.xmlRequest.send(this.postText);			}		}	}	//write an error message if neither method is available	else {		alert("your browser/svg viewer neither supports window.getURL nor window.XMLHttpRequest!");	}	}/** * this is the callback method for the getURL() or postURL() case * @private */getData.prototype.operationComplete = function(data) {	//check if data has a success property	if (data.success) {		//parse content of the XML format to the variable "node"		if (this.returnFormat == "xml") {			//convert the text information to an XML node and get the first child			var node = parseXML(data.content,document);			//distinguish between a callback function and an object			if (typeof(this.callBackFunction) == "function") {				this.callBackFunction(node.firstChild,this.additionalParams);			}			if (typeof(this.callBackFunction) == "object") {				this.callBackFunction.receiveData(node.firstChild,this.additionalParams);			}		}		if (this.returnFormat == "json") {			if (typeof(this.callBackFunction) == "function") {				this.callBackFunction(data.content,this.additionalParams);			}			if (typeof(this.callBackFunction) == "object") {				this.callBackFunction.receiveData(data.content,this.additionalParams);			}					}	}	else {		alert("something went wrong with dynamic loading of geometry!");	}}/** * this is the callback method for the XMLHttpRequest case * @private */getData.prototype.handleEvent = function() {	if (this.xmlRequest.readyState == 4) {		if (this.returnFormat == "xml") {			//we need to import the XML node first			var importedNode = document.importNode(this.xmlRequest.responseXML.documentElement,true);			if (typeof(this.callBackFunction) == "function") {				this.callBackFunction(importedNode,this.additionalParams);			}			if (typeof(this.callBackFunction) == "object") {				this.callBackFunction.receiveData(importedNode,this.additionalParams);			}					}		if (this.returnFormat == "json") {			if (typeof(this.callBackFunction) == "function") {				this.callBackFunction(this.xmlRequest.responseText,this.additionalParams);			}			if (typeof(this.callBackFunction) == "object") {				this.callBackFunction.receiveData(this.xmlRequest.responseText,this.additionalParams);			}					}			}	}/** * Serializes an XML node and returns a string representation. Wrapper function to hide implementation differences.  * This can be used for debugging purposes or to post data to a server or network resource. * @param {dom::Node} node		the DOM node reference * @return textRepresentation	the String representation of the XML node * @type String * @version 1.0 (2007-05-01) * @see getData */function serializeNode(node) {  if (typeof XMLSerializer != 'undefined') {    return new XMLSerializer().serializeToString(node);  }  else if (typeof node.xml != 'undefined') {    return node.xml;  }  else if (typeof printNode != 'undefined') {    return printNode(node);  }  else if (typeof Packages != 'undefined') {    try {      var stringWriter = new java.io.StringWriter();      Packages.org.apache.batik.dom.util.DOMUtilities.writeNode(node,stringWriter);      return stringWriter.toString();    }    catch (e) {       alert("Sorry, your SVG viewer does not support the printNode/serialize function.");       return '';    }  }  else {    alert("Sorry, your SVG viewer does not support the printNode/serialize function.");    return '';  }}/** * Starts a SMIL animation element with the given id by triggering the '.beginElement()' method.  * This is a convenience (shortcut) function.  * @param {String} id		a valid id of a valid SMIL animation element * @version 1.0 (2007-05-01) *///starts an animtion with the given id//this function is useful in combination with window.setTimeout()function startAnimation(id) {		document.getElementById(id).beginElement();}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -