[英]How to draw an SVG onclick in React
我有一個 React 組件,用於顯示 onclick 事件和導入的 SVG 文件的坐標。
如何將完成 onclick 的 SVG 圖像添加到該特定坐標?
import React, { Component } from 'react';
import mySVG from './assets/activeTab.svg';
import './Coordinates.css';
export default class Coordinates extends Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0};
}
_onMouseMove(e) {
this.setState({ x: e.screenX, y: e.screenY });
}
render() {
const { x, y } = this.state;
let { points } = this.state;
return (
<>
<h1>
Mouse coordinates: {x} {y}
</h1>
<img src={mySVG} alt='' />
<div
className='my-content'
onClick={this._onMouseMove.bind(this)}
></div>
</>
);
}
}
您可以使用狀態中的值使用 css 定位圖像。
import React, { Component } from "react";
import mySVG from "./activeTab.svg";
export default class Coordinates extends Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0 };
}
_onMouseMove(e) {
e.persist();
this.setState({ x: e.nativeEvent.layerX, y: e.nativeEvent.layerY });
}
render() {
const { x, y } = this.state;
return (
<>
<h1>
Mouse coordinates: {x} {y}
</h1>
<div
style={{ height: 400, background: "peachpuff", position: "relative" }}
onClick={this._onMouseMove.bind(this)}
>
<img
style={{
position: "absolute",
top: this.state.y,
left: this.state.x,
width: 60,
height: 60
}}
src={mySVG}
alt=""
/>
</div>
</>
);
}
}
如果您想在每次點擊時繼續添加圖像的新實例,您可以跟蹤狀態內每次點擊的歷史記錄,如下所示:
import React, { Component } from "react";
import mySVG from "./activeTab.svg";
export default class Coordinates extends Component {
constructor(props) {
super(props);
this.state = { x: 0, y: 0, history: [] };
}
_onMouseMove(e) {
e.persist();
const latest = { x: e.nativeEvent.layerX, y: e.nativeEvent.layerY };
this.setState({
...latest,
history: [...this.state.history, latest]
});
}
render() {
const { x, y, history } = this.state;
return (
<>
<h1>
Mouse coordinates: {x} {y}
</h1>
<div
style={{ height: 400, background: "peachpuff", position: "relative" }}
onClick={this._onMouseMove.bind(this)}
>
{history.map((item) => {
return (
<img
style={{
position: "absolute",
top: item.y,
left: item.x,
width: 60,
height: 60
}}
src={mySVG}
alt=""
/>
);
})}
</div>
</>
);
}
}
注意:上述內容可能會在某個時候遇到性能問題。 如果您打算繪制這些圖像的許多實例,您可能需要考慮查看canvas 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.