@jianghh/canvas-graffiti
Version:
canvas涂鸦库,支持手写、笔写、鼠标,选中元素,并且移动、删除等功能。集成撤销重做操作。
81 lines (80 loc) • 3.08 kB
JavaScript
import { GraffitiEle as W } from "../element/index.js";
import { roundToNDecimalPlaces as l } from "../utils/index.js";
let d = !1;
const m = {
pointerdown({ offsetX: i, offsetY: h, pointerType: n, pressure: o }) {
this.points.push({ x: l(i), y: l(h), pressure: l(o) }), n === "pen" && o !== 0 ? (this.ctx.lineWidth = this.lineWidth * 0.5, d = !0) : (this.ctx.lineWidth = this.lineWidth * 0.8, d = !1), this.ctx.moveTo(this.beginPoint.x, this.beginPoint.y);
},
pointermove({ offsetX: i, offsetY: h, pressure: n }) {
const o = l(n);
if (d ? this.points.push({ x: l(i), y: l(h), pressure: o }) : this.points.push({ x: l(i), y: l(h) }), this.points.length < 3)
return;
const t = this.points.slice(-2), a = t[0], c = {
x: (t[0].x + t[1].x) / 2,
y: (t[0].y + t[1].y) / 2
};
if (d) {
const f = E(o) + 0.5;
this.ctx.lineWidth = this.lineWidth * f;
} else {
let f = Math.sqrt(Math.pow(i - t[0].x, 2) + Math.pow(h - t[0].y, 2));
const y = p(f) + 0.8;
this.ctx.lineWidth = this.lineWidth * y;
}
this.ctx.beginPath(), this.ctx.moveTo(this.beginPoint.x, this.beginPoint.y), this.ctx.quadraticCurveTo(a.x, a.y, c.x, c.y), this.ctx.stroke(), this.beginPoint = c;
},
pointerup() {
this.ctx.lineWidth = this.lineWidth, e = 0, s = 0.2;
let i = this.width, h = this.height, n = 0, o = 0;
this.points.forEach((t) => {
t.x < i && (i = t.x), t.x > n && (n = t.x), t.y < h && (h = t.y), t.y > o && (o = t.y);
}), this.graffitiEleList.push(
new W({
tool: "Pen",
left: i,
top: h,
right: n,
bottom: o,
points: this.points,
shadowColor: this.shadowColor,
lineWidth: this.lineWidth,
shadowBlur: this.shadowBlur,
strokeStyle: this.strokeStyle,
fillStyle: this.fillStyle
})
);
},
drawEle(i) {
let h = [], n = i[0];
i.forEach((o) => {
if (h.push(o), h.length < 3)
return;
const t = h.slice(-2), a = t[0], c = {
x: (t[0].x + t[1].x) / 2,
y: (t[0].y + t[1].y) / 2
};
if (o.pressure && o.pressure > 0) {
const f = E(o.pressure) + 0.5;
this.ctx.lineWidth = this.lineWidth * f;
} else {
let f = Math.sqrt(Math.pow(o.x - t[0].x, 2) + Math.pow(o.y - t[0].y, 2));
const y = p(f) + 0.8;
this.ctx.lineWidth = this.lineWidth * y;
}
this.ctx.beginPath(), this.ctx.moveTo(n.x, n.y), this.ctx.quadraticCurveTo(a.x, a.y, c.x, c.y), this.ctx.stroke(), n = c;
}), e = 0, s = 0.2, h = [];
}
};
let e = 0;
const r = 2, u = 8, P = 40;
function p(i) {
return i >= u * 2 ? (e <= -12 + r ? e = -12 : e -= r, e / P) : i >= u ? (e <= 0 ? e < -r ? e += r : e = 0 : e > r ? e -= r : e = 0, e / P) : (e < u - r ? e += r : e = u, e / P);
}
let s = 0.2, g = 0;
const x = 0.05, T = 0.35;
function E(i) {
return i >= 0.5 ? (s >= 0.5 ? s = 0.5 : s += x, s) : i >= 0.15 ? (i > g ? s <= T ? s += x : s = T : s >= 0.2 ? s -= x : s = 0.15, s) : (s <= x ? s = 0 : s -= x, s);
}
export {
m as Pen
};