先上个效果图
<meta charset="utf-8">
实现思路大概是:当用户按下鼠标,移动鼠标,直到放开鼠标,将鼠标指向的点的坐标储存在一个数组中。放下鼠标后就将这个数组发送至服务器,服务器将这个数据转发到其他连接到服务器上的页面,页面收到数组后,将这个数组在画布上绘制出来就行了
下面上html代码
<html>
<head>
<meta charset="utf-8">
<title>canvas画板</title>
</head>
<body>
<div style="width:600px;height:350px;">
<canvas style="background-color:#efefef;border:1px solid #ddd;" id="myCanvas"></canvas>
</div>
<div style="width:600px;text-align:center;margin-top:30px;">
<button onclick="clean();">清 空</button>
<button onclick="save();">生成图片</button>
</div>
<img id='img' alt='' />
<script type="text/javascript">
var canvas, board, img;
canvas = document.getElementById('myCanvas');
img = document.getElementById('img');
canvas.height = 350;
canvas.width = 600;
board = canvas.getContext('2d');
var mousePress = false;
var last = null;
var points = [];
function beginDraw() {
mousePress = true;
console.log("开始绘图");
points = [];
points.push(pos(event));
}
function drawing(event) {
event.preventDefault();
if (!mousePress) return;
var xy = pos(event);
points.push(xy);
if (last != null) {
board.beginPath();
board.moveTo(last.x, last.y);
board.lineTo(xy.x, xy.y);
console.log(xy.x, xy.y);
board.stroke();
}
last = xy;
}
function endDraw(event) {
console.log("结束绘图");
send(points);
mousePress = false;
event.preventDefault();
last = null;
}
function pos(event) {
var x, y;
if (isTouch(event)) {
x = event.touches[0].pageX;
y = event.touches[0].pageY;
} else {
x = event.offsetX + event.target.offsetLeft;
y = event.offsetY + event.target.offsetTop;
}
return { x: x, y: y };
}
function log(msg) {
var log = document.getElementById('log');
var val = log.value;
log.value = msg + 'n' + val;
}
function isTouch(event) {
var type = event.type;
if (type.indexOf('touch') >= 0) {
return true;
} else {
return false;
}
}
function save() {
var dataUrl = canvas.toDataURL();
img.src = dataUrl;
}
function clean() {
board.clearRect(0, 0, canvas.width, canvas.height);
}
board.lineWidth = 1;
board.strokeStyle = "#2AA6C0";
canvas.onmousedown = beginDraw;
canvas.onmousemove = drawing;
canvas.onmouseup = endDraw;
canvas.addEventListener('touchstart', beginDraw, false);
canvas.addEventListener('touchmove', drawing, false);
canvas.addEventListener('touchend', endDraw, false);
var websocket = null;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://127.0.0.1:27979/websocket/" + getQueryString("id"));
} else {
alert("您的浏览器不支持websocket");
}
websocket.onerror = function () {
setMessageInHtml("send error!");
}
websocket.onopen = function () {
setMessageInHtml("connection success!")
//send();
}
websocket.onmessage = function (event) {
console.log("接收", event.data);
points = JSON.parse(event.data);
last = null;
for (j = 0; j < points.length; j++) {
//console.log(points[j]);
if (last == null) {
last = points[j];
} else {
board.beginPath();
board.moveTo(last.x, last.y);
board.lineTo(points[j].x, points[j].y);
board.stroke();
last = points[j];
}
}
last = null;
}
websocket.onclose = function () {
setMessageInHtml("closed websocket!")
}
window.onbeforeunload = function () {
clos();
}
function setMessageInHtml(message) {
//document.getElementById('message').innerHTML += message;
}
function clos() {
websocket.close(3000, "强制关闭");
}
function send(msg) {
websocket.send(JSON.stringify(msg));
console.log("发送信息:{}", JSON.stringify(msg));
}
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
}
</script>
</body>
</html>
springboot的pom新增依赖
<!--web socket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!--web socket end-->
application类新增
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
websocket类
@ServerEndpoint("/websocket/{pageCode}")
@Component
public class WebSocket {
private static final String loggerName=WebSocket.class.getName();
private static final org.slf4j.Logger log= LoggerFactory.getLogger(WebSocket.class);
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
public static Map<String, List<Session>> electricSocketMap = new ConcurrentHashMap<String, List<Session>>();
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(@PathParam("pageCode") String pageCode, Session session) {
List<Session> sessions = electricSocketMap.get(pageCode);
log.info("{}页面连接成功",pageCode);
if(null==sessions){
List<Session> sessionList = new ArrayList<>();
sessionList.add(session);
electricSocketMap.put(pageCode,sessionList);
}else{
sessions.add(session);
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(@PathParam("pageCode") String pageCode,Session session) {
if (electricSocketMap.containsKey(pageCode)){
electricSocketMap.get(pageCode).remove(session);
}
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("websocket received message:" + message);
// JSONObject object = JSON.parseObject(message);
// System.out.println("x坐标" + object.get("x"));
// System.out.println("y坐标" + object.get("y"));
for (String s : electricSocketMap.keySet()) {
List<Session> sessions = electricSocketMap.get(s);
sessions.forEach(e -> {
try {
e.getBasicRemote().sendText(message);
} catch (IOException e1) {
e1.printStackTrace();
}
});
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");;
}
}
onMessage方法中直接将接收到的消息发送到所有页面