同步画板演示

同时打开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. Golang内建库学习笔记(2)-web服务器相关

    package main import ( "net/http" "fmt" "strings" "log" ) fun ...

  2. 封装各种生成唯一性ID算法的工具类

    /** * Copyright (c) 2005-2012 springside.org.cn * * Licensed under the Apache License, Version 2.0 ( ...

  3. 【noi 2.6_9271】奶牛散步(DP)

    这题与前面的"踩方格"重复了,而且是大坑题!题目漏写了取模12345的条件! 详细解析请见我之前的博文--http://www.cnblogs.com/konjak/p/59368 ...

  4. Codeforces Global Round 9 B. Neighbor Grid (构造,贪心)

    题意:给一个\(n\)X\(m\)的矩阵,矩阵中某个数字\(k\)表示其四周恰好有\(k\)个不为0的数字,你可以使任意位置上的数字变大,如果操作后满足条件,输出新矩阵,否则输出NO. 题解:贪心,既 ...

  5. Python 读Excel数据

    一.读取Excel数据的步骤及方式: 1.打开Excel文件 data = xlrd.open_workbook(r'D:\Interface_test\test_data\测试用例.xlsx') 2 ...

  6. Vue3.0新特性

    Vue3.0新特性 Vue3.0的设计目标可以概括为体积更小.速度更快.加强TypeScript支持.加强API设计一致性.提高自身可维护性.开放更多底层功能. 描述 从Vue2到Vue3在一些比较重 ...

  7. 【.NET 与树莓派】让喇叭播放音乐

    如果你和老周一样,小时候特别喜欢搞破坏(什么电器都敢拆),那下面这样小喇叭你一定见过. 这种喇叭其实以前很多录音机都用,包括上小学时买来做英语听力的便携录音机.嗯,就是放录音带的那种,录音带也叫磁带或 ...

  8. MHA 高可用介绍

    目录 MHA 介绍 MHA 简介(Master High Availability) MHA 工作原理(转载) MHA 架构 MHA 工具 Manager 节点 Node 节点 MHA 优点 MHA ...

  9. 接口测试框架Requests

    目录 Requests Requests安装 Requests常见接口请求方法构造 请求目标构造 header构造 cookie 构造请求体 Get Query请求 Form请求参数 JSON请求体构 ...

  10. 字节笔试题 leetcode 69. x 的平方根

    更多精彩文章请关注公众号:TanLiuYi00 题目 解题思路 题目要求非负整数 x 的平方根,相当于求函数 y = √x 中 y 的值. 函数 y = √x  图像如下: 从上图中,可以看出函数是单 ...