基于JS实现含图片URI的SVG边角拖拽变形(适配Scratch扩展)
纯JS+SVG实现拖拽边角变形图片(适配Scratch扩展)
以下是完全不依赖Node.js、Three.js等第三方工具的解决方案,用原生SVG和JavaScript实现拖拽边角变形图片的效果:
实现代码
SVG结构(可直接嵌入Scratch扩展)
<svg id="imageWarpSVG" width="400" height="400" viewBox="0 0 400 400"> <!-- 定义图片填充图案 --> <defs> <pattern id="imagePattern" patternUnits="userSpaceOnUse" width="400" height="400"> <image href="你的图片URI" width="400" height="400" /> </pattern> </defs> <!-- 可变形的多边形,填充目标图片 --> <polygon id="warpShape" points="50,50 350,50 350,350 50,350" fill="url(#imagePattern)" stroke="#000" stroke-width="2" /> <!-- 四个拖拽控制点 --> <circle class="dragHandle" cx="50" cy="50" r="8" fill="#ff0000" /> <circle class="dragHandle" cx="350" cy="50" r="8" fill="#ff0000" /> <circle class="dragHandle" cx="350" cy="350" r="8" fill="#ff0000" /> <circle class="dragHandle" cx="50" cy="350" r="8" fill="#ff0000" /> </svg>
JavaScript逻辑
const svg = document.getElementById('imageWarpSVG'); const warpShape = document.getElementById('warpShape'); const dragHandles = document.querySelectorAll('.dragHandle'); let activeHandle = null; // 绑定拖拽激活事件 dragHandles.forEach((handle, index) => { handle.addEventListener('mousedown', (e) => { activeHandle = { element: handle, index }; e.stopPropagation(); }); }); // 绑定拖拽移动事件 window.addEventListener('mousemove', (e) => { if (!activeHandle) return; // 转换鼠标坐标为SVG内部坐标 const point = svg.createSVGPoint(); point.x = e.clientX; point.y = e.clientY; const svgPoint = point.matrixTransform(svg.getScreenCTM().inverse()); // 更新当前拖拽点位置 activeHandle.element.setAttribute('cx', svgPoint.x); activeHandle.element.setAttribute('cy', svgPoint.y); // 更新多边形顶点,同步变形效果 const points = Array.from(dragHandles).map(handle => `${handle.getAttribute('cx')},${handle.getAttribute('cy')}`); warpShape.setAttribute('points', points.join(' ')); e.stopPropagation(); }); // 绑定拖拽结束事件 window.addEventListener('mouseup', () => { activeHandle = null; });
关键说明
- 核心原理:将目标图片转为SVG填充图案,用可编辑顶点的多边形承载该图案,拖拽四个红色控制点即可改变多边形形状,图片会同步变形。
- 适配Scratch:完全原生实现,无第三方依赖,可直接嵌入Scratch扩展的HTML模块中。
- 自定义调整:替换
<image>标签的href为你的图片URI(支持base64或在线地址);修改SVG的width、height、viewBox适配Scratch舞台尺寸。 - 触摸支持:若需要适配平板等触摸设备,可添加
touchstart、touchmove、touchend事件监听,逻辑与鼠标事件一致。
内容的提问来源于stack exchange,提问作者ObviousAlexC.
相关产品推荐
相关产品推荐

