拖动矩形可移动位置,拖动右下角正方形可改变矩形大小,效果如下:

完整的代码:
点击查看
我们以uniapp为例,uniapp可以导出小程序
<template>
<view>
<canvas canvas-id="myCanvas" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" style="width: 100%; height: 300px;"></canvas>
</view>
</template>
<script>
export default {
data() {
return {
ctx: null,
rect: {
x: 50,
y: 50,
width: 100,
height: 80
},
isDragging: false,
isResizing: false,
lastX: 0,
lastY: 0,
resizeHandleSize: 20, // 增大调整大小的触控范围
}
},
onReady() {
this.ctx = uni.createCanvasContext('myCanvas')
this.drawRect()
},
methods: {
drawRect() {
this.ctx.clearRect(0, 0, 300, 150)
// 绘制主矩形
this.ctx.beginPath()
this.ctx.rect(this.rect.x, this.rect.y, this.rect.width, this.rect.height)
this.ctx.stroke()
// 绘制右下角的调整大小标识
this.drawResizeHandle()
this.ctx.draw()
},
drawResizeHandle() {
const x = this.rect.x + this.rect.width
const y = this.rect.y + this.rect.height
// 绘制一个小正方形作为调整大小的标识
this.ctx.fillStyle = 'blue'
this.ctx.fillRect(x - 10, y - 10, 10, 10)
// 绘制两条线来增强视觉效果
this.ctx.beginPath()
this.ctx.moveTo(x - 15, y)
this.ctx.lineTo(x, y)
this.ctx.moveTo(x, y - 15)
this.ctx.lineTo(x, y)
this.ctx.strokeStyle = 'blue'
this.ctx.stroke()
},
touchStart(e) {
const touch = e.touches[0]
this.lastX = touch.x
this.lastY = touch.y
// 检查是否在右下角的调整大小区域
if (this.isInResizeHandle(touch.x, touch.y)) {
this.isResizing = true
}
// 检查是否在矩形内部
else if (this.isInRect(touch.x, touch.y)) {
this.isDragging = true
}
},
touchMove(e) {
const touch = e.touches[0]
const dx = touch.x - this.lastX
const dy = touch.y - this.lastY
if (this.isDragging) {
this.rect.x += dx
this.rect.y += dy
} else if (this.isResizing) {
this.rect.width += dx
this.rect.height += dy
// 确保矩形不会变得太小
if (this.rect.width < 20) this.rect.width = 20
if (this.rect.height < 20) this.rect.height = 20
}
this.lastX = touch.x
this.lastY = touch.y
this.drawRect()
},
touchEnd() {
this.isDragging = false
this.isResizing = false
},
isInResizeHandle(x, y) {
const handleX = this.rect.x + this.rect.width
const handleY = this.rect.y + this.rect.height
return (x >= handleX - this.resizeHandleSize && x <= handleX &&
y >= handleY - this.resizeHandleSize && y <= handleY)
},
isInRect(x, y) {
return (x >= this.rect.x && x <= this.rect.x + this.rect.width &&
y >= this.rect.y && y <= this.rect.y + this.rect.height)
}
}
}
</script> 网友回复
python能写一个检测nginx rewrite高危漏洞的工具代码?
css如何给video视频进行mask遮罩?
windows如何同时允许两个用户远程桌面连接同一个电脑?
nginx升级到1.30.1导致无法启动 [emerg] SSL_CTX_new() failed怎么办?
什么是ASLR(地址随机化)?
有没有不依赖embedding向量的RAG技术?
有没有支持实时打断语音通话并后台帮你执行任何的ai模型?
开源ai大模型文件格式GGUF、MLX、Safetensors、 ONNX 有什么区别?
出海挣钱支付收款PayPal、Wise 、PingPong、Stripe如何选择?
如何实现类似google的图片隐形水印添加和识别技术?


