效果展示
单点效果
多点效果
常规绘制效果和二阶贝塞尔曲线路径绘制效果:
下图中上面的曲线为二阶贝塞尔绘制效果,下面的为普通绘制。明显可见贝塞尔曲线路径的绘制更加平滑且锯齿较少:
创建画布
创建画布并设置事件处理器
<canvas
ref="board"
style="background-color: #2b2d42"
width="1000"
height="1000"
@touchstart="handleStart"
@touchmove="handleMove"
@touchend="handleEnd"
/>
获取画布并初始化画笔信息
onMounted(() => {
initPointer();
});
const board = ref();
const cxt = ref();
const lineWidth = 4;
const initPointer = () => {
cxt.value = board.value.getContext('2d');
window.MeApi?.mainWindowLoaded();
cxt.value.strokeStyle = 'red';
cxt.value.fillStyle = 'red';
cxt.value.lineWidth = lineWidth;
};
触摸事件处理
基础知识
Touch.identifier
唯一地识别和触摸平面接触的点的值。
这个值在这根手指(或触摸笔等)所引发的所有事件中保持一致,直到它离开触摸平面。
TouchEvent.changedTouches
该属性返回一个TouchList
:
-
对于
touchstart
事件,这个TouchList
对象列出在此次事件中新增加的触点。 -
对于
touchmove
事件,列出和上一次事件相比较,发生了变化的触点。 -
对于 touchend 事件,
changedTouches
是已经从触摸面的离开的触点的集合(也就是说,手指已经离开了屏幕/触摸面)。
拷贝触摸点
浏览器会复用触摸点,通过拷贝只记录差异点和唯一标识符替换引用整个对象的方式进行优化:
type Point = {
identifier: number,//触摸点什么标识
//触摸点坐标
x: number,
y: number
};
const copyTouch = (touch: Touch) => {
return {
identifier: touch.identifier,
x: touch.pageX,
y: touch.pageY
};
};
查找触摸点
通过遍历 activityTouches
数组来寻找与给定标记相匹配的触摸点,返回该触摸点在数组中的下标。
const activityTouchIndexById = (idToFind: number) => {
for (let i = 0; i < activityTouches.length; i++) {
const id = activityTouches[i].identifier;
if (id === idToFind) {
return i;
}
}
return -1;
};
跟踪所有触摸点以实现多点触控
//跟踪当前存在的所有触摸点
const activityTouches: Point[] = [];
新增触摸事件
当屏幕上出现新的触摸点touchstart
事件被触发,handleStart
函数被触发。此时,要收集记录触摸点并在触摸点处画圆:
const handleStart = (evt: TouchEvent) => {
//获取所有新增的点
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
//收集触摸点
activityTouches.push(copyTouch(touches[i]));
//画圆
cxt.value.beginPath();
drawCircle(touches[i].clientX, touches[i].clientY)
}
};
触摸移动时
当 touchmove
事件被触发时,从而将调用handleMove()
函数,此时按照路径绘制线:
const handleMove = (evt: TouchEvent) => {
evt.preventDefault();
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
const indexById = activityTouchIndexById(touches[i].identifier);
if (indexById >= 0) {
cxt.value.beginPath();
cxt.value.moveTo(activityTouches[indexById].x, activityTouches[indexById].y);
cxt.value.lineTo(touches[i].clientX, touches[i].pageY);
cxt.value.stroke();
//更新缓存信息
activityTouches.splice(indexById, 1, copyTouch(touches[i]));
}
}
};
首先遍历所有发生移动的触摸点。通过读取每个触摸点的 Touch.identifier
属性,从缓存中读取每个触摸点在变化前的起点。这样取得每个触摸点之前位置的坐标,进而进行绘制。
触摸结束处理
通过调用 handleEnd()
函数来处理触摸结束事件:
const handleEnd = (evt: TouchEvent) => {
evt.preventDefault();
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
const indexById = activityTouchIndexById(touches[i].identifier);
if (indexById >= 0) {
cxt.value.beginPath();
cxt.value.moveTo(activityTouches[indexById].x, activityTouches[indexById].y);
cxt.value.lineTo(touches[i].clientX, touches[i].clientY);
drawCircle(touches[i].clientX, touches[i].clientY)
//移除缓存
activityTouches.splice(indexById, 1);
}
}
};
类似handleMove
,首先遍历所有事件,并读取缓存。在事件触发点画个圆,然后将对应的触摸对象从缓存中移除。
贝塞尔曲线
上述虽然实现了基础的涂鸦功能,但是曲线不够平滑且锯齿较为严重。因此需要借助贝塞尔曲线实现更加平滑的曲线。Canvas提供了quadraticCurveTo 实现二次贝塞尔曲线路径的绘制:
//存储所有的绘制点和起止点
type BasselPoints = {
beginPoint: Point,
points: Point[]
}
//支持多点触控,根据Touch的identifier标识不同触点
const pointsMap: Map<number, BasselPoints> = new Map();
//存储每个触点的绘制点
const pushPoint = (p: Point) => {
//分别处理新增和后续加入
if (!pointsMap.has(p.identifier)) {
//第一次加入的点作为默认的起始点
pointsMap.set(p.identifier, { beginPoint: p, points: [p] });
} else {
pointsMap.get(p.identifier)?.points.push(p);
}
};
//用于手指抬起时清除当前事件
const clearPoint = (identifier: number) => {
pointsMap.delete(identifier);
};
当触摸屏幕时,handleStart
事件被触发,此时要向pushPoint
增加新的点。
const point = copyTouch(touches[index]);
pushPoint(point);
当手指在屏幕上滑动时,继续向pushPoint
增加新的点。当当前触点有三个绘制点时。开始进行绘制,以倒数第二个点为控制点,并根据最后两个点计算出结束点。然后以pushPoint
中的beginPoint
进行二阶贝塞尔曲线进行绘制。最后,更新起始点。
const drawBessel = (next: Point) => {
//添加绘制点
pushPoint(next);
const target = pointsMap.get(next.identifier)!!;
if (target.points?.length > 3) {
//计算各个点位
const lastTwoPoints = target.points.slice(-2);
const controlPoint = lastTwoPoints[0];
const endPoint = {
identifier: next.identifier,
x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
};
cxt.value.beginPath();
cxt.value.moveTo(target.beginPoint.x, target.beginPoint.y);
//进行贝塞尔曲线绘制
cxt.value.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
cxt.value.stroke();
cxt.value.closePath();
//更新起始点
target.beginPoint = endPoint;
}
};
当手指离开屏幕时,需要删除pointsMap
下对应的触摸点
const clearPoint = (identifier: number) => {
pointsMap.delete(identifier);
};
其他
移动端和PC端所对应的时间不同。详情可见鼠标事件和触摸事件文档。
移动端的触摸点信息被封装在Touch中,通过Touch.clientX
和Touch.clientX
读取当前坐标
移动端的触摸点信息被封装在MouseEvent中
亦可以使用三阶贝塞尔路径去绘制:
const bessel3 = (next: Point) => {
pushPoint(next);
const points = pointsMap.get(next.identifier)?.points ?? [];
// 绘制手势路径
cxt.value.beginPath();
cxt.value.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length - 2; i++) {
const p1 = points[i];
const p2 = points[i + 1];
const p3 = points[i + 2];
// 计算三次贝塞尔曲线的控制点
const cp1x = p1.x + (p2.x - p1.x) / 3;
const cp1y = p1.y + (p2.y - p1.y) / 3;
const cp2x = p2.x - (p3.x - p1.x) / 3;
const cp2y = p2.y - (p3.y - p1.y) / 3;
cxt.value.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, p2.x, p2.y);
}
cxt.value.stroke();
}
完整代码
<template>
<div>
<canvas
ref="board"
width="1200"
height="1000"
style="background-color: #2b2d42"
@touchstart="handleStart"
@touchmove="handleMove"
@touchend="handleEnd"
/>
<div class="control-setting">
<div class="div" @click="useBassel = !useBassel">
<text>{{ useBassel ? "" : "不"}}使用贝塞尔</text>
</div>
<div class="div" @click="clearCanvas">
<text>清空</text>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
const board = ref();
const cxt = ref();
const lineWidth = 4;
const useBassel = ref(true);
onMounted(() => {
cxt.value = board.value.getContext('2d');
retina();
initPointer();
});
const retina = () => {
const canvas = board.value;
let width = canvas.width, height = canvas.height;
if (window.devicePixelRatio) {
canvas.style.width = width + "px";
canvas.style.height = height + "px";
canvas.height = height * window.devicePixelRatio;
canvas.width = width * window.devicePixelRatio;
cxt.value.scale(window.devicePixelRatio, window.devicePixelRatio);
}
};
const initPointer = () => {
cxt.value.strokeStyle = 'red';
cxt.value.fillStyle = 'red';
cxt.value.lineWidth = lineWidth;
};
type Point = {
identifier: number,
x: number,
y: number
};
type BasselPoints = {
beginPoint: Point,
points: Point[]
}
const pointsMap: Map<number, BasselPoints> = new Map();
const activityTouches: Point[] = [];
const copyTouch = (touch: Touch) => {
return {
identifier: touch.identifier,
x: touch.pageX,
y: touch.pageY
};
};
const pushPoint = (p: Point) => {
if (!pointsMap.has(p.identifier)) {
pointsMap.set(p.identifier, { beginPoint: p, points: [p] });
} else {
pointsMap.get(p.identifier)?.points.push(p);
}
};
const clearPoint = (identifier: number) => {
pointsMap.delete(identifier);
};
const activityTouchIndexById = (idToFind: number) => {
for (let i = 0; i < activityTouches.length; i++) {
const id = activityTouches[i].identifier;
if (id === idToFind) {
return i;
}
}
return -1;
};
const handleStart = (evt: TouchEvent) => {
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
switchStart(touches, i);
}
};
const switchStart = (touches: TouchList, index: number) => {
if (useBassel.value) {
const point = copyTouch(touches[index]);
pushPoint(point);
} else {
const point = copyTouch(touches[index]);
activityTouches.push(point);
cxt.value.beginPath();
drawCircle(touches[index].clientX, touches[index].clientY);
}
};
const handleMove = (evt: TouchEvent) => {
evt.preventDefault();
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
switchMove(touches, i);
}
};
const switchMove = (touches: TouchList, index: number) => {
if (useBassel.value) {
drawBessel(copyTouch(touches[index]));
} else {
const indexById = activityTouchIndexById(touches[index].identifier);
if (indexById >= 0) {
cxt.value.beginPath();
cxt.value.moveTo(activityTouches[indexById].x, activityTouches[indexById].y);
cxt.value.lineTo(touches[index].clientX, touches[index].pageY);
cxt.value.stroke();
activityTouches.splice(indexById, 1, copyTouch(touches[index]));
}
}
};
const handleEnd = (evt: TouchEvent) => {
evt.preventDefault();
const touches = evt.changedTouches;
for (let i = 0; i < touches.length; i++) {
switchEnd(touches, i);
}
};
const switchEnd = (touches: TouchList, index: number) => {
if (useBassel.value) {
clearPoint(touches[index].identifier);
} else {
const indexById = activityTouchIndexById(touches[index].identifier);
if (indexById >= 0) {
cxt.value.beginPath();
cxt.value.moveTo(activityTouches[indexById].x, activityTouches[indexById].y);
cxt.value.lineTo(touches[index].clientX, touches[index].clientY);
drawCircle(touches[index].clientX, touches[index].clientY);
activityTouches.splice(indexById, 1);
}
}
};
const drawBessel = (next: Point) => {
pushPoint(next);
const target = pointsMap.get(next.identifier)!!;
if (target.points?.length > 3) {
const lastTwoPoints = target.points.slice(-2);
const controlPoint = lastTwoPoints[0];
const endPoint = {
identifier: next.identifier,
x: (lastTwoPoints[0].x + lastTwoPoints[1].x) / 2,
y: (lastTwoPoints[0].y + lastTwoPoints[1].y) / 2,
};
cxt.value.beginPath();
cxt.value.moveTo(target.beginPoint.x, target.beginPoint.y);
cxt.value.quadraticCurveTo(controlPoint.x, controlPoint.y, endPoint.x, endPoint.y);
cxt.value.stroke();
cxt.value.closePath();
target.beginPoint = endPoint;
}
};
const drawCircle = (x: number, y: number) => {
cxt.value.arc(x, y, lineWidth / 2, 0, 2 * Math.PI, false);
cxt.value.fill();
};
const clearCanvas = () => {
cxt.value.clearRect(0, 0, 1200, 1000);
}
</script>
<style lang="less">
.control-setting {
position: absolute;
bottom: 10px;
left: 10px;
right: 10px;
color: white;
display: flex;
justify-content: center;
gap: 10px;
.div {
padding: 5px 8px;
border: 1px solid white;
}
}
</style>