CanvasInput icon indicating copy to clipboard operation
CanvasInput copied to clipboard

correct usage of destroy

Open loudking opened this issue 8 years ago • 3 comments

Hi, I did following: 1. create a CanvasInput, 2. Destroy that CanvasInput object and clearRect whole canvas. After that wherever I click on the canvas there is error. Can you please help?

    var input = new CanvasInput({
        canvas: document.getElementById('myCanvas'),
        x: 40,
        y: 40
    });


function foo(input) {
  console.log("foo input x = " + input.x() + " y = " + input.y()
              + " width = " + input.width()
              + " height = " + input.height());
  input.destroy();
  
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext("2d");
  context.clearRect(0, 0, canvas.width, canvas.height);
}

setTimeout(foo, 1000, input);

Error:

"error"
"TypeError: Cannot set property 'font' of null
    at window.CanvasInput._textWidth (xeletudahe.js:10:14120)
    at window.CanvasInput._clipText (xeletudahe.js:10:13961)
    at window.CanvasInput._clickPos (xeletudahe.js:10:15620)
    at window.CanvasInput.mouseup (xeletudahe.js:10:10394)
    at HTMLCanvasElement.<anonymous> (xeletudahe.js:10:2431)"

loudking avatar Sep 04 '17 09:09 loudking

For some reason the destroy() event is being called every time when you click on the canvas, after destroying it for the first time, for a quick fix in the destroy event I've changed from: document.body.removeChild(self._hiddenInput); to if (self._hiddenInput.parentNode == document.body) document.body.removeChild(self._hiddenInput); and in the _textWidth:

_textWidth: function(text) {
  var self = this,
  ctx = self._renderCtx;

  if (ctx) {
      
      ctx.font = self._fontStyle + ' ' + self._fontWeight + ' ' + self._fontSize + 'px ' + self._fontFamily;
      ctx.textAlign = 'left';

      return ctx.measureText(text).width;
  }
}

huberemanuel avatar Mar 12 '18 16:03 huberemanuel

The issue persists and is pretty problematic

g--o avatar Aug 06 '19 17:08 g--o

For some reason the destroy() event is being called every time when you click on the canvas, after destroying it for the first time, for a quick fix in the destroy event I've changed from: document.body.removeChild(self._hiddenInput); to if (self._hiddenInput.parentNode == document.body) document.body.removeChild(self._hiddenInput); and in the _textWidth:

_textWidth: function(text) {
  var self = this,
  ctx = self._renderCtx;

  if (ctx) {
      
      ctx.font = self._fontStyle + ' ' + self._fontWeight + ' ' + self._fontSize + 'px ' + self._fontFamily;
      ctx.textAlign = 'left';

      return ctx.measureText(text).width;
  }
}

Looks like this issue has been dead for a while. The problem still exists, but the above solution from @huberemanuel solved it for me!

raimund89 avatar May 28 '20 10:05 raimund89