<canvas :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" canvas-id="imgGird" id="imgGird"></canvas>
// 初始化宽高
const canvasWidth = ref(400)
const canvasHeight = ref(600)
// 画点
function drawDot(ctx, x, y) {
ctx.beginPath();
ctx.arc(x, y, 10, 0, 2 * Math.PI); //x,y,直径
ctx.fillStyle = '#2a71b9'; //颜色
ctx.fill();
}
// 画图画线
function drawGrid(path, width, height, positionArr) {
const ctx = uni.createCanvasContext('imgGird', this);
ctx.drawImage(path, 0, 0, width, height);
// 设置网格线颜色和宽度
ctx.setStrokeStyle('rgba(63,127,192,0.5)');
ctx.setLineWidth(1);
// 绘制水平网格线
for (let i = 0; i <= height; i += 20) {
ctx.moveTo(0, i);
ctx.lineTo(width, i);
}
// 绘制垂直网格线
for (let i = 0; i <= width; i += 20) {
ctx.moveTo(i, 0);
ctx.lineTo(i, height);
}
// 执行绘制
ctx.stroke();
// 根据坐标画圆点
positionArr.forEach(item => {
drawDot(ctx, item.x, item.y)
})
// 将canvas转换为图片
ctx.draw(true, () => {
uni.canvasToTempFilePath({
canvasId: 'imgGird',
success: (res) => {
console.log(res.tempFilePath);
// 可以将生成的临时文件路径进行保存或者其他操作
},
fail: (err) => {
console.error(err);
}
});
});
}
// 上传图片
const updateImg = (ev) => {
chooseAvatarUrl.value = ''
console.log('裁切完成', ev)
let positionArr = [
{
x: 50,
y: 60
},
{
x: 80,
y: 90
},
{
x: 110,
y: 120
},
{
x: 160,
y: 250
},
{
x: 400,
y: 590
},
{
x: 300,
y: 220
}
]
uni.getImageInfo({
src: ev.path,
success: function (image) {
console.log('图片信息', image, image.path)
canvasWidth.value = image.width
canvasHeight.value = image.height
drawGrid(ev.path, image.width, image.height, positionArr)
}
});
}