同步画板演示

同时打开2个tab,分别在画布上写下任意内容,观察演示结果,同时可设置画笔颜色及线条宽度。演示地址

初始化画布

 <canvas id="drawBoard" width="700" height="400"></canvas>
   this.canvas = document.getElementById("drawBoard");
this.ctx = this.canvas.getContext("2d");
this.stage_info = this.canvas.getBoundingClientRect(); //初始化舞台信息
this.path = { //初始化路径
beginX: 0,
beginY: 0,
endX: 0,
endY: 0,
};
this.ctx.lineWidth = this.size;//初始化线条宽度

加载irealtime.js

irealtime.js 是一个第三方websocket实时消息推送服务jssdk,可用于快速搭建安全可靠高并发的web实时通讯体系,同时支持多语言开发且兼容绝大多数主流浏览器, 了解更多

  1. 引入irealtime.js
npm i irealtime --save
  1. 初始化irealtime
import IRealTime from "irealtime";

this.irealtime = new IRealTime({
host: "hk.irealtime.cn",
appkey: "your appkey", //如何获取appkey: https://irealtime.cn/docs/get_account_and_appkey.html
onConnected: function () {
console.log("连接成功...");
},
onDisconnected: function () {
console.log("连接断开...");
},
onConnectFailed: function (error) {
console.log("连接失败...", error);
},
});
  1. 订阅消息
  this.irealtime.subscribe({
channels: ["mychannel"],
onMessage: (data) => {
this.syncPath(data.message); //通过irealtime将绘画内容同步到其他客户端
},
onSuccess: function () {},
onFailed: function () {},
});
  1. 发布消息
    publish(msg) {
this.irealtime.publish({
channel: "mychannel",
message: msg,
onSuccess: function (data) {
console.log("success:", data);
},
onFailed: function (error) {
console.log("failed:", error);
},
});
},

开始绘画

  1. 绑定鼠标事件
  draw() {
let that = this;
this.canvas.onmousedown = (e) => {
that.ctx.beginPath();
that.path.beginX = e.pageX - that.stage_info.left;
that.path.beginY = e.pageY - that.stage_info.top;
that.ctx.moveTo(that.path.beginX, that.path.beginY);
that.isDraw = true;//isDraw 是否开始绘画
this.publish( //发送mousedown消息给其他客户端
JSON.stringify({
type: "mousedown",
path: this.path,
})
);
};
this.canvas.onmousemove = (e) => {
if (that.isDraw) {
that.drawing(e); //按下并移动鼠标开始绘画
}
};
this.canvas.onmouseup = () => {
that.isDraw = false;
this.publish( //发送stop消息给其他客户端
JSON.stringify({
type: "stop",
path: this.path,
})
);
};
},
  1. 绘画动作
    drawing(e) {
this.path.endX = e.pageX - this.stage_info.left;
this.path.endY = e.pageY - this.stage_info.top;
this.ctx.lineTo(this.path.endX, this.path.endY);
this.ctx.stroke();
let data = {
type: "draw",
size: this.size,
current: this.current,
path: this.path,
};
this.publish(JSON.stringify(data));//将当前绘画路径、线条宽度、当前颜色等信息发送给其他客户端
},
  1. 同步绘画信息

通过不同类型的消息,判断客户端需要做的操作

  syncPath(data) {
const { type, size, current, path } = JSON.parse(data);
if (type === "changeColor") { //改变颜色
this.current = current;
this.ctx.strokeStyle = this.palette[this.current];
return;
}
if (type === "changeSize") { //改变线条宽度
this.size = size;
this.ctx.lineWidth = this.size;
return;
} if (type == "clear") { //清空画布
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
return;
}
if (this.path.beginX != path.beginX) { //防止重复
if (type === "mousedown") {
this.ctx.beginPath(); this.ctx.moveTo(path.beginX, path.beginY);
this.isDraw = 1;
} else if (type === "draw" && this.isDraw === 1) {
this.ctx.lineTo(path.endX, path.endY);
this.ctx.stroke();
}
}
if (type === "stop") {//停止绘画
this.isDraw = 0;
}
},

查看源码

总结

本文通过使用irealtime.js的两个简单api(subscribe|publish)便实现了基于websocket的消息发布及订阅,开发者无需过多关注websocket服务端操作,可直接使用irealtime api开发基于websocket的应用,如需了解更多内容,请直接访问https://irealtime.cn/

如何使用irealtime.js实现一个基于websocket的同步画板的更多相关文章

  1. JS实现一个基于对象的链表

    JS实现一个基于对象的链表 /*JS实现一个基于对象的链表*/ function Node(element){ this.element = element;//节点存储的元素 this.next = ...

  2. 推荐一个 基于 WebSocket 和 Redis 的 即时通信 开源项目

    项目地址 : https://github.com/2881099/im 大家可以和 SignalR 比较看看 ,  如何  ?        ^^  ^^  ^^ 这是一个 网友 写的 , 他还写了 ...

  3. Ext JS学习第十六天 事件机制event(一) DotNet进阶系列(持续更新) 第一节:.Net版基于WebSocket的聊天室样例 第十五节:深入理解async和await的作用及各种适用场景和用法 第十五节:深入理解async和await的作用及各种适用场景和用法 前端自动化准备和详细配置(NVM、NPM/CNPM、NodeJs、NRM、WebPack、Gulp/Grunt、G

    code&monkey   Ext JS学习第十六天 事件机制event(一) 此文用来记录学习笔记: 休息了好几天,从今天开始继续保持更新,鞭策自己学习 今天我们来说一说什么是事件,对于事件 ...

  4. 高效简易开发基于websocket 的通讯应用

    websocket的主要是为了解决在web上应用长连接进行灵活的通讯应用而产生,但websocket本身只是一个基础协议,对于消息上还不算灵活,毕竟websocket只提供文本和二进制流这种基础数据格 ...

  5. 基于WebSocket和SpringBoot的群聊天室

    引入 普通请求-响应方式:例如Servlet中HttpServletRequest和HttpServletResponse相互配合先接受请求.解析数据,再发出响应,处理完成后连接便断开了,没有数据的实 ...

  6. 使用JMeter测试基于WebSocket协议的服务

    使用JMeter测试基于WebSocket协议的服务 :first-child{margin-top:0!important}img.plugin{box-shadow:0 1px 3px rgba( ...

  7. 基于websocket实现的一个简单的聊天室

    本文是基于websocket写的一个简单的聊天室的例子,可以实现简单的群聊和私聊.是基于websocket的注解方式编写的.(有一个小的缺陷,如果用户名是中文,会乱码,不知如何处理,如有人知道,请告知 ...

  8. RSuite 一个基于 React.js 的 Web 组件库

    RSuite http://rsuite.github.io RSuite 是一个基于 React.js 开发的 Web 组件库,参考 Bootstrap 设计,提供其中常用组件,支持响应式布局. 我 ...

  9. 基于docker+reveal.js搭建一个属于自己的在线ppt网站

    前言 最近热衷于Docker,由于这段时间使用Docker来折腾自己的服务器,越来越感觉这是一种及其被应该推广的技术,因此想在公司内部也做一次技术分享.当然,如果只是做的PPT,我就不写这文章了.既然 ...

随机推荐

  1. K8s 二、(1、kubeadm部署Kubernetes集群)

    准备工作 满足安装 Docker 项目所需的要求,比如 64 位的 Linux 操作系统.3.10 及以上的内核版本: x86 或者 ARM 架构均可: 机器之间网络互通,这是将来容器之间网络互通的前 ...

  2. linux 一分钟搭建zookeeper linux 单机版(亲测可用)

    wget https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-3.4.14/zookeeper-3.4.14.tar.gzt ...

  3. [USACO12FEB]Symmetry

    传送门: https://www.luogu.com.cn/problem/P3046 https://ac.nowcoder.com/acm/contest/6306/G 题意 给定n个不同的点,求 ...

  4. AtCoder Beginner Contest 164

    比赛链接:https://atcoder.jp/contests/abc164 A - Sheep and Wolves #include <bits/stdc++.h> using na ...

  5. 【noi 2.6_9268】酒鬼(DP)

    题意:有N瓶酒,不能连续喝>=3瓶的酒,问能喝的最大的酒量. 解法:同前一题相似,可以f[i][j]表示前i瓶中连续喝了j瓶的最大酒量.1.f[i][0]=f[i-1][3] ; 2.i=1或2 ...

  6. SPOJ 227 Ordering the Soldiers

    As you are probably well aware, in Byteland it is always the military officer's main worry to order ...

  7. Codeforces Round #670 (Div. 2) C. Link Cut Centroids (dfs,树)

    C. Link Cut Centroids Fishing Prince loves trees, and he especially loves trees with only one centro ...

  8. HDU 3416 Marriage Match IV (最短路径&&最大流)

    /*题意: 有 n 个城市,知道了起点和终点,有 m 条有向边,问从起点到终点的最短路一共有多少条.这是一个有向图,建边的时候要注意!!解题思路:这题的关键就是找到哪些边可以构成最短路,其实之前做最短 ...

  9. 动态主席树【带修改】&& 例题 Dynamic Rankings ZOJ - 2112

    参考链接:https://blog.csdn.net/WilliamSun0122/article/details/77885781 一.动态主席树介绍 动态主席树与静态主席树的不同在于:静态主席树不 ...

  10. C#之字符编码

    在 Windows Vista 及之后的版本中,每个Unicode字符都使用UTF-16编码,UTF的全称是 Unicode Transformation Format(Unicode 转换格式).U ...