FocalPointPicker 是一个 WordPress 组件,用于创建 UI 以识别图像的关键视觉焦点,解决大背景图像在不同视口下裁剪不当的问题。它返回一个 0 到 1 之间的坐标值,可轻松转换为 CSS background-position 属性,确保焦点始终可见。
import { useState } from 'react';
import { FocalPointPicker } from '@wordpress/components';
const Example = () => {
const [ focalPoint, setFocalPoint ] = useState( {
x: 0.5,
y: 0.5,
} );
const url = '/path/to/image';
const style = {
backgroundImage: `url(${ url })`,
backgroundPosition: `${ focalPoint.x * 100 }% ${ focalPoint.y * 100 }%`,
};
return (
<>
<FocalPointPicker
url={ url }
value={ focalPoint }
onDragStart={ setFocalPoint }
onDrag={ setFocalPoint }
onChange={ setFocalPoint }
/>
<div style={ style } />
</>
);
};Focal Point Picker is a component which creates a UI for identifying the most important visual point of an image. This component addresses a specific problem: with large background images it is common to see undesirable crops, especially when viewing on smaller viewports such as mobile phones. This component allows the selection of the point with the most important visual information and returns it as a pair of numbers between 0 and 1. This value can be easily converted into the CSS background-position attribute, and will ensure that the focal point is never cropped out, regardless of viewport.
{ x: 0.5, y: 0.1 }background-position: 50% 10%;import { useState } from 'react';
import { FocalPointPicker } from '@wordpress/components';
const Example = () => {
const [ focalPoint, setFocalPoint ] = useState( {
x: 0.5,
y: 0.5,
} );
const url = '/path/to/image';
/* Example function to render the CSS styles based on Focal Point Picker value */
const style = {
backgroundImage: `url(${ url })`,
backgroundPosition: `${ focalPoint.x * 100 }% ${ focalPoint.y * 100 }%`,
};
return (
<>
<FocalPointPicker
url={ url }
value={ focalPoint }
onDragStart={ setFocalPoint }
onDrag={ setFocalPoint }
onChange={ setFocalPoint }
/>
<div style={ style } />
</>
);
};
urlTextURL of the image or video to be displayed
autoPlayBooleantrueAutoplays HTML5 video. This only applies to video sources (url).
valueObjectThe focal point. Should be an object containing x and y params.
onChangeFunctionCallback which is called when the focal point changes.
onDragFunctionCallback which is called repetitively during drag operations.
onDragEndFunctionCallback which is called at the end of drag operations.
onDragStartFunctionCallback which is called at the start of drag operations.
resolvePointFunctionFunction which is called before internal updates to the value state. It receives the upcoming value and may return a modified one.