问题
Say I have a canvas with svg elements drawn on it. Once i click on the element, i need to change the viewport by zooming and focusing on the element clicked. How do i perform this? I have attached the code.
`
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>jQuery SVG</title>
<style type="text/css">
#svgbasics
{
width: 1250px;
height: 500px;
border: 1px solid black;
}
</style>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.svg.js"></script>
<script type="text/javascript">
var selectedItem="";
$(function()
{
$('#viewport').svg({onLoad: drawInitial});
});
function drawInitial(svg)
{
svg.circle(75, 75, 50, {onclick: "clickListener()",fill: 'none', stroke: 'red', 'stroke-width': 3});
var g = svg.group({onclick: "select(evt)",stroke: 'black', 'stroke-width': 2});
svg.line(g, 15, 75, 135, 75,{onclick: "select(evt)"});
svg.line(g, 75, 15, 75, 135,{onclick: "select(evt)"});
}
function clickListener()
{
//code to change the viewport to this element
}
</script>
</head>
<body>
<h1>jQuery SVG</h1>
<div id="svgbasics" tabindex="0" onclick="this.focus()">
<g id="viewport">
<input type="button" value="Click me" onclick="clickListener()"/>
</g>
</div>
<p>
</p>
</body>
</html>
`
回答1:
You can use getBBox() on the element the user clicked and adjust the SVG element's viewBox
accordingly (using preserveAspectRatio="xMidYMid meet"
you don't have to worry about ratio, but you might want to add a border since the bounding box is geometrically tight, ignoring line widths and milters).
function clickListener(event) {
var b = event.target.getBBox();
$('#viewport > svg')[0].setAttribute('viewBox',
[b.x, b.y, b.width, b.height].join(' '));
}
回答2:
Thanks. Implemented using this :
var b = event.target.getBBox();
var svg = document.getElementById('svgcanvas');
svg.setAttribute("viewBox", b.x+" "+b.y+" "+b.width+" "+b.height);
来源:https://stackoverflow.com/questions/9029469/zoom-to-an-element-jquery-svg