社区文档构建进行中,欢迎编辑。社区答疑群(非官方):717421103,点点小课堂(腾讯会议):5696651544

全站通知:

Widget:SignBoard.js

来自WIKI实验室WIKI_BWIKI_哔哩哔哩
跳到导航 跳到搜索

<script> class SignBoard { cv = document.createElement("canvas") ctx = this.cv.getContext("2d") timer = null timeout = 1000 isSigned = false path = [] events = {}

constructor() { this.cv.width = 600 this.cv.height = 200 this.ctx.lineWidth = 3 this.ctx.strokeStyle = "#88ffff" let p1 let touchClient let mousemove = e => { let p2 = [e.offsetX, e.offsetY] this.draw(p1, p2) p1 = p2 } let mouseup = e => { this.timer = setTimeout(e => { this.stop() }, this.timeout) $(document) .off("mousemove", mousemove) .off("mouseup", mouseup) } let touchmove = e => { e.preventDefault() let p2 = [e.changedTouches[0].clientX - touchClient[0], e.changedTouches[0].clientY - touchClient[1]] this.draw(p1, p2) p1 = p2 } let touchend = e => { this.timer = setTimeout(e => { this.stop() }, this.timeout) $(document) .off("touchmove", touchmove) .off("touchcancel", touchend) .off("touchend", touchend) }

if (navigator.maxTouchPoints > 0) { $(this.cv).on("touchstart", e => { if (this.isSigned) { return } touchClient = [this.cv.offsetLeft, this.cv.offsetTop] p1 = [e.changedTouches[0].clientX - touchClient[0], e.changedTouches[0].clientY - touchClient[1]] if (this.timer) { clearTimeout(this.timer) } $(document) .on("touchmove", touchmove) .on("touchcancel", touchend) .on("touchend", touchend) }) } else { $(this.cv).on("mousedown", e => { if (this.isSigned) { return } p1 = [e.offsetX, e.offsetY] if (this.timer) { clearTimeout(this.timer) }

$(document) .on("mousemove", mousemove) .on("mouseup", mouseup) }) } }

appendTo($dom) { $dom.append(this.cv) }

draw([x1, y1], [x2, y2]) { this.path.push([[x1, y1], [x2, y2]]) let ratio = this.cv.width / this.cv.clientWidth this.ctx.lineWidth = 3 * ratio this.ctx.beginPath() this.ctx.moveTo(x1 * ratio, y1 * ratio) this.ctx.lineTo(x2 * ratio, y2 * ratio) this.ctx.stroke() }

stop() { this.isSigned = true try { this.events.stop.forEach(e => { try { e(this) } catch (e) { } }) } catch (e) { } }

on(eventName, func) { if (!this.events[eventName]) { this.events[eventName] = [] } this.events[eventName].push(func) } } </script>