canvas制作签名版

直接复制粘贴

代码如下

<!DOCTYPE html>
<html>
<head>
	<title>Signature Pad</title>
	<style>
		canvas {
			border: 1px solid #ccc;
		}
	</style>
</head>
<body>
	<canvas id="signature-pad" width="400" height="200"></canvas>
	<br>
	<button id="*****-button">Clear</button>

	<script>
		// 获取canvas元素
		var canvas = document.getElementById('signature-pad');
		// 获取2D绘图上下文
		var ctx = canvas.getContext('2d');
		// 定义变量记录鼠标是否按下
		var isMouseDown = false;
		// 定义变量记录鼠标位置
		var lastX, lastY;

		// 绑定鼠标按下事件
		canvas.addEventListener('mousedown', function(e) {
			isMouseDown = true;
			// 记录鼠标位置
			lastX = e.clientX - canvas.offsetLeft;
			lastY = e.clientY - canvas.offsetTop;
		});

		// 绑定鼠标移动事件
		canvas.addEventListener('mousemove', function(e) {
			if (isMouseDown) {
				// 计算鼠标移动距离
				var currentX = e.clientX - canvas.offsetLeft;
				var currentY = e.clientY - canvas.offsetTop;
				// 绘制线条
				ctx.beginPath();
				ctx.moveTo(lastX, lastY);
				ctx.lineTo(currentX, currentY);
				ctx.stroke();
                
				// 更新鼠标位置
				lastX = currentX;
				lastY = currentY;
			}
		});

		// 绑定鼠标松开事件
		canvas.addEventListener('mouseup', function(e) {
			isMouseDown = false;
		});

		// 绑定清空按钮点击事件
		var Button = document.getElementById('*****-button');
		Button.addEventListener('click', function() {
			// 清空画布
			ctx.clearRect(0, 0, canvas.width, canvas.height);
		});
	</script>
</body>
</html>

你可能感兴趣的:(javascript,javascript,前端,html)