在SVG中嵌入JavaScript

时间:2014-02-20 08:01:34

标签: javascript svg

我需要制作更具互动性的电路图像。

我的计划是使用标准EDA工具绘制电路并将其存储为SVG文件。然后,任何现代浏览器都可以打开存储为SVG的文件。

我现在要做的是在SVG中添加一些JavaScript代码。当用户将鼠标悬停在电路的某些部分上时,脚本必须弹出描述这些部分的工具提示。例如,当用户将鼠标放在IC顶部时,该IC的描述将立即弹出。

该电路在SVG XML中合理注释。

据我所知,到目前为止,没有自动的JavaScript方法可以找出当前鼠标悬停在哪个盒子/线上。当然,它会发现是否有一个查找表,用电路注释映射图像坐标。

这意味着每次电路改变时,都需要更新查找表。

是否有更容易的方法找出(没有查找表)鼠标悬停在其上的带注释的盒子/线/组件?

1 个答案:

答案 0 :(得分:1)

使用HTML5,您可以将SVG放在HTML中;内联SVG。在那里,你可以添加普通浏览器元素事件的监听器,一切都会正常工作。

我刚才写了一篇关于它的博客,这是来源:

angular.module('yenlo.blog', []);

angular.module('yenlo.blog').controller('ChartController', function($scope, $timeout){

	$scope.items = [
		{ height: 100, color: 'red', content: 'A' },
		{ height: 120, color: 'green', content: 'B' },
		{ height: 140, color: 'blue', content: 'C' }
	];

	setInterval(function(){
		$scope.items.forEach(function(item){
			item.height += ( Math.random() - 0.5 ) * 5;
		});
		$scope.$digest();
	}, 100);

	$scope.selected = $scope.items[0];
	$scope.select = function(item){
		$scope.selected = item;
	};

});
<!DOCTYPE html>
<html>
  <body ng-app="yenlo.blog" ng-controller="ChartController">
	<svg height="200" width="100">
		<rect ng-repeat="item in items"
			ng-attr-x="{{ $index * 33 }}"
			ng-attr-y="{{ 200 - item.height }}"
			ng-attr-height="{{ item.height }}"
			ng-attr-fill="{{ item.color }}"
			ng-click="select(item)"
			width="30"/>
	</svg>
	<p>
		Currently watching {{ selected.content }}, at {{ selected.height }}
	</p>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.12/angular.min.js"></script>
  </body>
</html>