javascript - 将 Javascript 重构为类对象的问题
问题描述
我尝试将我的 Javascript 代码重构为类对象 javascript 代码,但我遇到了一些问题。
我正在运行的旧代码是这样开始的:
document.addEventListener("DOMContentLoaded", function(event) {
// Variables :
var color = "#000000";
var sign = false;
var begin_sign = false;
var width_line = 5;
var canvas = document.getElementById('canvas');
var cursorX, cursorY;
var context = canvas.getContext('2d');
context.lineJoin = 'round';
context.lineCap = 'round';
document.addEventListener("mousedown", function(e) {
sign = true; // Coordonnées de la souris :
cursorX = (e.pageX - this.offsetLeft);
cursorY = (e.pageY - this.offsetTop);
});
我的新代码是这样开始的:
"use strict";
class Signature {
constructor() {
this.color = "#000000";
this.sign = false;
this.begin_sign = false;
this.width_line = 5;
this.canvas = document.getElementById('canvas');
this.cursorX, this.cursorY;
this.context = canvas.getContext('2d');
this.context.lineJoin = 'round';
this.context.lineCap = 'round';
}
init() {
document.addEventListener("DOMContentLoaded", event => {
this.whenMouseDown();
this.whenMouseUp();
this.whenMouseMove();
this.createSignature();
this.clearCanvas();
this.resetCanvas();
})
}
whenMouseDown() {
document.addEventListener("mousedown", function({
pageX,
pageY
}) {
this.sign = true;
this.cursorX = (pageX - this.offsetLeft);
this.cursorY = (pageY - this.offsetTop);
})
}
但似乎不正确。如何更正我的代码?
解决方案
请注意,注释代码是针对您代码中未实现的功能的。
如果您正在寻找传统方法,这是实现目标的方法。
已init()
移至构造函数,并且事件处理程序采用了一种非常干净的方法。
鉴于您的方法(以及其他答案的方法),每次单击鼠标时,document
您都会创建一个新的事件处理程序,每次单击鼠标等都会调用该事件处理程序。
在构造函数中设置事件处理程序可以防止这种情况。
"use strict";
class Signature {
constructor() {
this.color = "#000000";
this.sign = false;
this.begin_sign = false;
this.width_line = 5;
this.canvas = document.getElementById('canvas');
this.cursorX, this.cursorY;
this.context = canvas.getContext('2d');
this.context.lineJoin = 'round';
this.context.lineCap = 'round';
// this.createSignature();
// this.clearCanvas();
// this.resetCanvas();
this.whenMouseDown = this.whenMouseDown.bind(this);
//this.whenMouseUp = this.whenMouseUp.bind(this);
//this.whenMouseMove = this.whenMouseMove.bind(this);
document.addEventListener("mousedown", this.whenMouseDown);
// this.document.addEventListener("mousedown", this.whenMouseUp);
// this.document.addEventListener("mousedown", this.whenMouseMove);
}
whenMouseDown(e) {
this.sign = true;
this.cursorX = (e.pageX - this.offsetLeft);
this.cursorY = (e.pageY - this.offsetTop);
}
}
<canvas id="canvas"></canvas>
推荐阅读
- python - Python、Pandas 和 NLTK 类型错误“int”对象在调用系列时不可调用
- r - 是否有一个 R 函数可以将这些数据从长变宽?
- python - 4个嵌套循环的时间复杂度是多少,每个嵌套循环都取决于父循环
- oracle - 如何使用 informatica power center 调用物化视图?
- python - 迭代熊猫数据框并应用条件
- javascript - 将已经四舍五入的浮点数字符串化,然后将其转换回数字会产生进一步的精度错误吗?
- directx-9 - 为什么不推荐使用 d3d 效果框架?
- powershell - 在 PowerShell 中修改对象结果
- python - 尝试制作加密代码但出现许多错误
- wordpress - WooCommerce - WooSquare Plus 插件 - 加上产品变体必须是一个数组