SVG zoom with mouse wheel inside HTML document

2019-04-23 22:47发布

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/

2条回答
何必那么认真
2楼-- · 2019-04-23 23:24

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!

查看更多
We Are One
3楼-- · 2019-04-23 23:48

Usually, it's not a great idea to implement this stuff with bare javascript. There are plenty of great libraries that allow you to do this in a few lines, and probably will have much fewer possibilities for errors.

A prominent example that comes to mind is d3. The capabilities in this mashup seem to be pretty much what you want.

If you want to implement something similar for your application, you basically just need to recalculate the transform matrix on zoom events. d3 can give you the mouse event data, and also simplify the process of changing attributes. Check out the source and give it a try!

查看更多
登录 后发表回答