版本:2.30.2
canvas缩放后再次绘图偏移,手画的地方和画布出现的线条位置不一样
//设置画布信息
getCanvasInfo() {
const query = wx.createSelectorQuery().in(this)
query.select('#canvas').fields({node: true,size: true,rect: true})
.exec((res) => {const ele = res[0]
canvasEle = ele
// 配置项
const option = {
ele: canvasEle, // canvas元素
drawCallBack: this.draw, // 必须:用户自定义绘图方法
scale: 1, // 当前缩放倍数
scaleStep: 0.1, // 缩放步长(按钮)
touchScaleStep: 0.005, // 缩放步长(手势)
maxScale: 2, // 缩放最大倍数(缩放比率倍数)
minScale: 0.5, // 缩放最小倍数(缩放比率倍数)
translate: {
x: 0,
y: 0
}, // 默认画布偏移
isThrottleDraw: true, // 是否开启节流绘图(建议开启,否则安卓调用频繁导致卡顿)
throttleInterval: 20, // 节流绘图间隔,单位ms
pixelRatio: wx.getSystemInfoSync().pixelRatio, // 像素比(高像素比可以解决高清屏幕模糊问题)
}
canvasDraw = new CanvasDraw(option) // 创建CanvasDraw实例后就可以使用实例的所有方法了
})
},
//以下代码写在另一个js文件里,import过来的
//初始化画布
this.init = () => {
const optionCopy = JSON.parse(JSON.stringify(option))
this.scale = optionCopy.scale ?? 1 // 当前缩放倍数
this.scaleStep = optionCopy.scaleStep ?? 0.1 // 缩放步长(按钮)
this.touchScaleStep = optionCopy.touchScaleStep ?? 0.005 // 缩放步长(手势)
this.maxScale = optionCopy.maxScale ?? 2 // 缩放最大倍数(缩放比率倍数)
this.minScale = optionCopy.minScale ?? 0.5 // 缩放最小倍数(缩放比率倍数)
this.translate = optionCopy.translate ?? {
x: 0,
y: 0
} // 默认画布偏移
this.isThrottleDraw = optionCopy.isThrottleDraw ?? true // 是否开启节流绘图(建议开启,否则安卓调用频繁导致卡顿)
this.throttleInterval = optionCopy.throttleInterval ?? 20 // 节流绘图间隔,单位ms
this.pixelRatio = optionCopy.pixelRatio ?? 1 // 像素比(高像素比解决高清屏幕模糊问题)
startPoint = {
x: 0,
y: 0
} // 拖动开始坐标
startDistance = 0 // 拖动开始时距离(二指缩放)
curTranslate = JSON.parse(JSON.stringify(this.translate)) // 当前偏移
curScale = this.scale // 当前缩放
preScale = this.scale // 上次缩放
drawTimer = null // 绘图计时器,用于节流
fingers = 1 // 手指触摸个数
this.canvasNode.width = ele.width * this.pixelRatio
this.canvasNode.height = ele.height * this.pixelRatio
}
//缩放函数
this.zoomTo = (scale, zoomCenter0) => {
// console.log('缩放到:', scale, '缩放中心点:', zoomCenter0)
this.scale = scale
this.scale = this.scale > this.maxScale ? this.maxScale : this.scale
this.scale = this.scale < this.minScale ? this.minScale : this.scale
const zoomCenter = zoomCenter0 || this.zoomCenter
this.translate.x = zoomCenter.x - ((zoomCenter.x - this.translate.x) * this.scale) / preScale
this.translate.y = zoomCenter.y - ((zoomCenter.y - this.translate.y) * this.scale) / preScale
this.draw()
preScale = this.scale
curTranslate.x = this.translate.x
curTranslate.y = this.translate.y
}
/**
* 绘制线段
*/
this.drawLines = (opt) => {
this.ctx.beginPath()
this.ctx.strokeStyle = opt.strokeStyle
for (let i = 0; i < opt.points.length; i++) {
const p = opt.points[i]
if (i === 0) {
this.ctx.moveTo(p.x, p.y)
} else {
this.ctx.lineTo(p.x, p.y)
}
}
this.ctx.stroke()
}
<canvas type="2d" id="canvas" canvas-id="canvas" style="background-color: {{bgColor}};width: 400px;height: 380px;" bindtouchstart="touchstart" bindtouchmove="touchMove" bindtouchend="touchEnd" disable-scroll="{{touchType=='drag'?false:true}}"></canvas>