同步画板演示

同时打开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. linux 高可用----keepalived+lvs

    什么是高可用? HA(high availability)即高可用性:就是在高可用集群中发生单点故障时,能够自动转移资源并切换服务,以保证服务一直在线的机制. LVS LVS:(linux virtu ...

  2. 【STM32】PWM波中的时间问题

    我们使用的TIM3定时器是挂载在APB1总线上的,APB1总线的时钟频率为72MHz. APB1总线的时钟频率通过PSC寄存器预分频,得到的频率为(72/(71+1))=1MHz. 定时器的自动重装载 ...

  3. Jenkins(2)docker容器中安装python3

    前言 使用docker安装jenkins环境,jenkins构建的workspace目录默认是在容器里面构建的,如果我们想执行python3的代码,需进容器内部安装python3的环境. 进jenki ...

  4. codeforces251A. Points on Line

    Little Petya likes points a lot. Recently his mom has presented him n points lying on the line OX. N ...

  5. linux搭建网站

    CentOS 1.安装 yum -y install nginx *或者安装指定版本,版本网址:http://nginx.org/packages/centos/7/x86_64/RPMS/ rpm ...

  6. 通过js正则表达式实例学习正则表达式基本语法

    正则表达式又叫规则表达式,一般用来检查字符串中是否有与规则相匹配的子串,达到可以对匹配的子串进行提取.删除.替换等操作的目的.先了解有哪些方法可以使用正则对字符串来实现这些操作: RegExpObje ...

  7. Redis的主从架构+哨兵模式

    Redis主从架构 redis主从架构搭建,配置从节点步骤: 1.复制一份redis.conf文件的目录 cd /usr/local/java cp -a redis redis_6380 2.将相关 ...

  8. Redis 事务 & 消息队列

    Redis 消息队列介绍 什么是消息队列 消息队列(Message Queue)是一种应用间的通信方式,消息发送后可以立即返回,有消息系统来确保信息的可靠传递,消息生产者只管把消息发布到消息队列中而不 ...

  9. LEETCODE - 【1271】十六进制魔术数字

    class Solution { public: string toHexspeak(string num) { stringstream ss; long long inter; //转16进制 s ...

  10. SOHO 程序员

    SOHO 程序员:从事程序开发.维护的家居办公人员. 一.自由程序员 SOHO程序员代表一种自由.弹性而新型的工作方式.SOHO,代表一种新经济.新概念. 是一些热爱软件开发的一族. SOHO程序员 ...