drawCanvas.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. class DrawCanvas {
  2. constructor() {
  3. this._ctx = null
  4. this._canvas = null
  5. this._executionArr = []
  6. this._pathArr = []
  7. this._style = null
  8. }
  9. _init({ width, height, canvas, baseMapUrl = '' }) {
  10. if (!width || !height || !canvas) return
  11. const ctx = canvas.getContext('2d')
  12. const dpr = wx.getSystemInfoSync().pixelRatio
  13. canvas.width = width * dpr
  14. canvas.height = height * dpr
  15. ctx.scale(dpr, dpr)
  16. // 添加底图
  17. if (baseMapUrl) {
  18. const img = canvas.createImage()
  19. img.onload = () => {
  20. this._ctx.drawImage(img, 0, 0, width, height)
  21. this._ctx.globalCompositeOperation = "source-atop" //画笔重叠部分覆盖
  22. }
  23. img.src = baseMapUrl
  24. }
  25. this._canvas = canvas
  26. this._ctx = ctx
  27. this._executionArr = [] //每移动一笔的数据
  28. this._pathArr = [] //抬起落下为一笔
  29. }
  30. mouseStart() {
  31. this._executionArr = []
  32. }
  33. mouseMove({ x = 0, y = 0 }) {
  34. if (!this._style) return
  35. this._executionArr.push([x, y])
  36. this._ctx.fillStyle = this._style
  37. this._ctx.fillRect(x - 5, y - 5, 10, 10)
  38. console.log('画图并存储');
  39. }
  40. mouseEnd() {
  41. this._pathArr.push({
  42. fillStyle: this._style,
  43. path: this._executionArr
  44. })
  45. }
  46. mouseBack() {
  47. // 删除每个移动数据
  48. if (this._pathArr.length) {
  49. const item = this._pathArr.length <= 1 ? this._pathArr[0] : this._pathArr[this._pathArr.length - 1]
  50. for (let k = 0; k < item.path.length; k++) {
  51. const el = item.path[k];
  52. this._ctx.clearRect(el[0] - 5, el[1] - 5, 11, 11)
  53. }
  54. this._pathArr.pop()
  55. }
  56. }
  57. // 切换画笔
  58. changeBrush(url = '') {
  59. if (!url) return
  60. const img = this._canvas.createImage()
  61. img.onload = () => {
  62. this._style = this._ctx.createPattern(img, 'repeat')
  63. }
  64. img.src = url
  65. }
  66. // 清除画布
  67. destory() {
  68. this._ctx.clearRect(0, 0, this._ctx.canvas.width, this._ctx.canvas.height)
  69. this._pathArr = []
  70. this._executionArr = []
  71. this._style = null
  72. }
  73. // 保存
  74. save() {
  75. wx.canvasToTempFilePath({
  76. canvas: this._canvas,
  77. success(res) {
  78. console.log('保存', res.tempFilePath);
  79. }
  80. })
  81. }
  82. }
  83. export { DrawCanvas }