Xiaofan Mu
Xiaofan Mu

Reputation: 17

Using MouseMove function to move elements in svg with svelte framework

Apologies if this is a dumb question, as I'm new to web development, and many thanks in advance!

I'm currently using a svg inside svelte framework. I defined my svg as <svg width={svg_width} height={svg_height}>. The whole structure looks like

<div class="demo-container">
|-<div id="playground-container">
  |-<svg>

Here is my css:

.demo-container {
  display:inline-block;
}
#playground-container {
  position: relative;
  width: 75%;
  float: left;
  margin-right:5px;
}

I'm having trouble relating the coordinate in svg (e.g. the location of shapes in the svg) to the mouse event (event.ClientX & event.ClientY). They do not seem to have linear or affine relationship. Additionally, when I inspect the webpage, the dimension of the svg displayed does not match what I defined it to be.

As a result, when I set the location of shapes directly to event.ClientX & event.ClientY, they go nuts. How should I convert the location of the mouse to location of the svg?

Please provide some help. Thanks

Upvotes: 0

Views: 3321

Answers (2)

Thomas Hennes
Thomas Hennes

Reputation: 9939

Assuming your mousemove event handler is attached to the svg element, the way to get x and y coordinates in reference to the svg itself (with the top left corner of the svg having coordinates (0,0) and the bottom right corner having the coordinates (svg_width, svg_height)) is to use getBoundingClientRect:

<script>
  function mouseHandler(e) {
    const rect = e.currentTarget.getBoundingClientRect()
    console.log(`x: ${e.clientX - rect.x}, y: ${e.clientY - rect.y}`)
  }
</script>

<div class="demo-container">
  <div id="playground-container">
    <svg width={svg_width} height={svg_height} on:mousemove={mouseHandler}>
      // svg data (shapes, paths, etc.)
    </svg>
  </div>
</div>

Upvotes: 2

nologin
nologin

Reputation: 1442

You need to place a on:mousemove={fixElement} in your html-tag.

a function like this might work as you discribe:

function fixElement(event) {
        console.log("in");
        let elem = document.querySelector('#playground-container');
        let y = event.clientY;
        let x = event.clientX;
        elem.style.setProperty('position', 'absolute');
        elem.style.setProperty('left', x + 'px');
        elem.style.setProperty('top', y + 'px');
    }

Upvotes: 0

Related Questions