correct usage of destroy
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)"
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;
}
}
The issue persists and is pretty problematic
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);toif (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!