前期web浏览器上面canvas可以很支持vue页面,因为要用原生插件组件必须是nvue才能使用显示出来所以重构(真的巨坑),然后之前写的绘制功能canvas又不能生效了是因为nvue原生weex啥的原因导致直接方法无效我丢。
话不多说实现方式上效果:
思路:nvue + <web-view> + H5 Canvas
在 nvue 页面中放 <web-view src="/static/draw.html">
draw.html 用标准 HTML5 Canvas + JS 实现手指绘制
1️⃣ nvue 页面:pages/home/draw.nvue
<template>
<view class="page">
<web-view :src="webViewUrl" class="webview"></web-view>
</view>
</template>
<script>
export default {
data() {
return {
// H5 文件路径,放在 /static/draw.html
webViewUrl: '/static/draw.html'
}
}
}
</script>
<style scoped>
.page {
flex: 1;
}
.webview {
flex: 1;
}
</style>
2️⃣ H5 页面:static/draw.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>手指画笔</title>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
background: #111;
overflow: hidden;
}
#canvas {
display: block;
background: #fff;
touch-action: none; /* 防止滚动 */
}
#controls {
position: absolute;
top: 10px;
left: 10px;
z-index: 10;
}
button {
margin-right: 10px;
padding: 5px 10px;
}
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<div id="controls">
<button id="clearBtn">清空</button>
<button id="logBtn">打印坐标</button>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 全屏自适应
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
ctx.strokeStyle = '#000';
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
let drawing = false;
let lastX = 0;
let lastY = 0;
let points = []; // 存储轨迹坐标
canvas.addEventListener('touchstart', (e) => {
drawing = true;
const touch = e.touches[0];
lastX = touch.clientX;
lastY = touch.clientY;
points.push({x: lastX, y: lastY});
});
canvas.addEventListener('touchmove', (e) => {
if (!drawing) return;
const touch = e.touches[0];
const x = touch.clientX;
const y = touch.clientY;
ctx.beginPath();
ctx.moveTo(lastX, lastY);
ctx.lineTo(x, y);
ctx.stroke();
lastX = x;
lastY = y;
points.push({x, y});
});
canvas.addEventListener('touchend', () => {
drawing = false;
});
// 清空按钮
document.getElementById('clearBtn').addEventListener('click', () => {
ctx.clearRect(0, 0, canvas.width, canvas.height);
points = [];
});
// 打印轨迹坐标
document.getElementById('logBtn').addEventListener('click', () => {
console.log('轨迹坐标:', points);
alert('已打印到控制台');
});
</script>
</body>
</html>