canvas实现画布拖拽效果 适配Uniapp和Vue (开箱即用)
<template>
<view class="container">
<canvas
canvas-id="canvas"
class="canvas"
@touchmove="touchMove"
@touchend="touchEnd"
></canvas>
</view>
</template>
<script>
export default {
data() {
return {
ctx: null,
isDrawing: false,
lastX: 0,
lastY:
};
},
onReady() {
this.ctx = uni.createCanvasContext('canvas', this);
this.ctx.setLineCap('round');
this.ctx.setLineWidth(5);
this.ctx.setStrokeStyle('#000');
},
methods: {
touchMove(e) {
if (e.touches.length === 1) {
const x = e.touches[0].x;
const y = e.touches[0].y;
this.draw(x, y);
}
},
touchEnd() {
this.isDrawing = false;
},
draw(x, y) {
this.isDrawing = true;
this.ctx.beginPath();
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(x, y);
this.ctx.stroke();
this.ctx.closePath();
this.lastX = x;
this.lastY = y;
}
}
};
</script>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.canvas {
width: 80%;
height: 80%;
}
</style>
这段代码提供了一个简单的画布拖拽绘制的例子,适用于UniApp和Vue框架。在用户触摸移动时,记录下当前位置并绘制线条,当用户抬起手指时结束绘制过程。这个例子展示了如何在UniApp中使用Canvas API进行绘图,并且提供了基本的拖拽绘制功能。
评论已关闭