Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG zoom with mouse wheel inside HTML document

I'm attempting to implement a functionality in an HTML document which allows users to drag and zoom in an embedded SVG 'box'...

I found this, but soon enough realised that that script only works with plain SVG files...

Keep in mind that I'm a programmer who has been working exclusively with assembly language for the past half year. Jumping from that to this abstract environment is a huge step.

Right now I'm trying to figure out just the zooming part:

So I made this HTML file:

<html>
<head>
    <title>Forum Risk! v0.0.1</title>
    <script type="text/javascript" src="svglib.js" ></script>
</head>
<body>
    <!-- SVG embedded directly for example purpose... I'm planning to use <embed> -->
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" onmousewheel="mouseWheelHandler(e);">
        <g id="viewport" transform="matrix(1,0,0,1,200,200)" >
            <circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>
        </g>
    </svg>
</body>

And the contents of svglib.js are:

var scrollSensitivity = 0.2

function mouseWheelHandler(e) {

    var evt = window.event || e;
    var scroll = evt.detail ? evt.detail * scrollSensitivity : (evt.wheelDelta / 120) * scrollSensitivity;

    var transform = document.getElementById("viewport").getAttribute("transform").replace(/ /g,"");

    var vector = transform.subString(transform.indexOf("("),transform.indexOf(")")).split(",")

    vector[0] = (parseInt(vector[0]) + scroll) + '';
    vector[3] = vector[0];

    document.getElementById("viewport").setAttribute("transform",
        "matrix(".concat(vector.join(), ")"));

    return true;

}

I used http://www.javascriptkit.com/javatutors/onmousewheel.shtml for reference.

But the problem is that as soon as I open the HTML file with Chrome, the SVG shows up, but nothing happens at all when I scroll with my mouse wheel...

Have I understood all of this completely wrong?

UPD

Fixed version http://jsfiddle.net/dfsq/GJsbD/

like image 980
Vlad Avatar asked Feb 25 '13 17:02

Vlad


1 Answers

Solved! Apparently the onmousewheel attribute doesn't handle the event correctly... at least I had to add an event listener directly through javascript to the SVG canvas to make it work!

like image 87
Vlad Avatar answered Nov 12 '22 15:11

Vlad