我在嘗試在畫布中創建自定義游標/十字準線時遇到問題。我遇到的問題是為形成游標的四個矩形指定的長度、寬度和間隙會為中心間隙產生不正確的像素數量。
Live CodeSandbox:https ://codesandbox.io/s/nifty-resonance-bcl0m
代碼:
import "./styles.css";
import { Stage, Layer, Rect } from "react-konva";
export default function App() {
const length = 15;
const width = 4;
const gap = 3;
const x = 400 / 2;
const y = 400 / 2;
return (
<div className="App">
<Stage width={400} height={400}>
<Layer>
{/* Horizontal Rectangles */}
<Rect
x={x (width / 2 gap)}
y={y - width / 2}
width={length}
height={width}
fill="green"
/>
<Rect
x={x - (length width / 2 gap)}
y={y - width / 2}
width={length}
height={width}
fill="green"
/>
{/* Vertical Rectangles */}
<Rect
x={x - width / 2}
y={y - (length width / 2 gap)}
width={width}
height={length}
fill="blue"
/>
<Rect
x={x - width / 2}
y={y (width / 2 gap)}
width={width}
height={length}
fill="blue"
/>
</Layer>
</Stage>
</div>
);
}
在上面的示例中,測量游標的長度和寬度是正確的量,但是,中心間隙給出 10 像素而不是 6 像素(間隙 * 2)。我知道這個問題一定是由于我如何計算每個矩形的 X/Y 位置,但我似乎無法找到正確的公式來避免游標的整體外觀。
uj5u.com熱心網友回復:
它的發生是因為您計算了兩次差距:
你的代碼:
const length = 6;
const width = 4;
const gap = 3;
const x = 400 / 2;
const y = 400 / 2;
return (
<div className="App">
<Stage width={400} height={400}>
<Layer>
{/* Horizontal Rectangles */}
<Rect
x={x (width / 2 gap)}
y={y - width / 2}
width={length}
height={width}
fill="green"
/>
</layer>
</div>
在計算您正在執行的水平長度時:(width / 2) gap == (4/2) 3 = 5.您可以從計算中洗掉寬度以獲得 6 的間隙
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/397925.html
標籤:javascript 反应 帆布
