diff --git a/service.js b/service.js index 19564ec..32ad3ad 100644 --- a/service.js +++ b/service.js @@ -333,13 +333,11 @@ class BesService { const canvasPanelRect = this.canvasPanel.getBoundingClientRect() const highlights = [] this.canvasPanel.classList.add('bes-canvas') - const ctx = this.canvasPanel.getContext('2d') - ctx.lineWidth = 1 - ctx.strokeStyle = ruleId.startsWith('MORFOLOGIK_RULE') + this.ctx.lineWidth = 1 + this.ctx.strokeStyle = ruleId.startsWith('MORFOLOGIK_RULE') ? '#e91313' : '#269b26' - this.setCanvasDpr() for (let rect of range.getClientRects()) { const x = rect.left - canvasPanelRect.left const y = rect.top - canvasPanelRect.top + rect.height @@ -350,10 +348,10 @@ class BesService { const globalY = rect.top + window.scrollY // Draw the underline - ctx.beginPath() - ctx.moveTo(x, y) - ctx.lineTo(x + width, y) - ctx.stroke() + this.ctx.beginPath() + this.ctx.moveTo(x, y) + this.ctx.lineTo(x + width, y) + this.ctx.stroke() const rectCoords = { x, y, width, height, globalX, globalY } highlights.push(rectCoords) } @@ -454,6 +452,7 @@ class BesService { this.scrollPanel.style.height = `${this.hostElement.scrollHeight}px` this.canvasPanel.style.width = `${this.hostElement.scrollWidth}px` this.canvasPanel.style.height = `${this.hostElement.scrollHeight}px` + this.ctx = this.canvasPanel.getContext('2d') this.setCanvasDpr() if (this.isHostElementInline()) { const totalWidth = @@ -474,12 +473,15 @@ class BesService { * Sets canvas panel device pixel ratio. */ setCanvasDpr() { - const ctx = this.canvasPanel.getContext('2d') const dpr = window.devicePixelRatio || 1 const canvasPanelRect = this.canvasPanel.getBoundingClientRect() this.canvasPanel.width = canvasPanelRect.width * dpr this.canvasPanel.height = canvasPanelRect.height * dpr - ctx.scale(dpr, dpr) + this.ctx.scale(dpr, dpr) + if (!this.ctx) { + this.ctx = this.canvasPanel.getContext('2d') + } + this.ctx.scale(dpr, dpr) } /** @@ -529,13 +531,11 @@ class BesService { * Updates all grammar mistake markup positions. */ repositionAllMarkup() { - const ctx = this.canvasPanel.getContext('2d') - this.results.forEach(result => { result.matches.forEach(match => { if (match.highlights) { match.highlights.forEach(h => { - ctx.clearRect(h.x - 2, h.y - 2, h.width + 4, h.height) + this.ctx.clearRect(h.x - 2, h.y - 2, h.width + 4, h.height) }) delete match.highlights @@ -799,8 +799,6 @@ class BesTreeService extends BesService { * @param {Element} el DOM element we want to clean markup for */ clearMarkup(el) { - const ctx = this.canvasPanel.getContext('2d') - this.results .filter(result => BesTreeService.isSameParagraph(result.element, el)) .forEach(result => @@ -811,7 +809,7 @@ class BesTreeService extends BesService { match.highlights.forEach(h => { console.log(h) // Figure out why i need to add 2px to width - ctx.clearRect(h.x - 2, h.y - 2, h.width + 4, h.height) + this.ctx.clearRect(h.x - 2, h.y - 2, h.width + 4, h.height) }) delete match.highlights }