使用 MouseMove 函数通过 svelte 框架移动 svg 中的元素
Using MouseMove function to move elements in svg with svelte framework
如果这是一个愚蠢的问题,我深表歉意,因为我是网络开发的新手,在此先感谢您!
我目前在 svelte 框架内使用 svg。我将我的 svg 定义为 <svg width={svg_width} height={svg_height}>
。整个结构看起来像
<div class="demo-container">
|-<div id="playground-container">
|-<svg>
这是我的 css:
.demo-container {
display:inline-block;
}
#playground-container {
position: relative;
width: 75%;
float: left;
margin-right:5px;
}
我无法将 svg 中的坐标(例如 svg 中形状的位置)与鼠标事件相关联(event.ClientX & event.ClientY)。它们似乎没有线性或仿射关系。此外,当我检查网页时,显示的 svg 尺寸与我定义的尺寸不符。
因此,当我将形状的位置直接设置为 event.ClientX 和 event.ClientY 时,它们就会发疯。我应该如何将鼠标的位置转换为 svg 的位置?
请提供一些帮助。谢谢
您需要在 html 标签中放置 on:mousemove={fixElement}
。
像这样的函数可能会像您描述的那样起作用:
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');
}
假设您的 mousemove
事件处理程序附加到 svg
元素,获取 x
和 y
坐标的方法参考 svg 本身(使用具有坐标 (0,0)
的 svg 左上角和具有坐标 (svg_width, svg_height)
的右下角)是使用 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>
如果这是一个愚蠢的问题,我深表歉意,因为我是网络开发的新手,在此先感谢您!
我目前在 svelte 框架内使用 svg。我将我的 svg 定义为 <svg width={svg_width} height={svg_height}>
。整个结构看起来像
<div class="demo-container">
|-<div id="playground-container">
|-<svg>
这是我的 css:
.demo-container {
display:inline-block;
}
#playground-container {
position: relative;
width: 75%;
float: left;
margin-right:5px;
}
我无法将 svg 中的坐标(例如 svg 中形状的位置)与鼠标事件相关联(event.ClientX & event.ClientY)。它们似乎没有线性或仿射关系。此外,当我检查网页时,显示的 svg 尺寸与我定义的尺寸不符。
因此,当我将形状的位置直接设置为 event.ClientX 和 event.ClientY 时,它们就会发疯。我应该如何将鼠标的位置转换为 svg 的位置?
请提供一些帮助。谢谢
您需要在 html 标签中放置 on:mousemove={fixElement}
。
像这样的函数可能会像您描述的那样起作用:
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');
}
假设您的 mousemove
事件处理程序附加到 svg
元素,获取 x
和 y
坐标的方法参考 svg 本身(使用具有坐标 (0,0)
的 svg 左上角和具有坐标 (svg_width, svg_height)
的右下角)是使用 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>