当我在画布中输入文本时,我正试图使闪烁的光标向前移动。光标确实向前移动,但由于某种原因,旧光标仍然在前一个位置闪烁。
import React, {Component} from 'react';
import './CanvasTextEditor.scss';
class CanvasTextEditor extends Component {
constructor(props) {
super(props);
this.state = {
cursorPos: [40.5, 5.5],
cursorSize: [1, 18],
cursorColour: '#000000',
cursorBlinkSpeed: 1,
backgroundColour: '#FFFFFF',
font: 'Arial',
fontSize: 30,
fontColour: '#000000',
text: ''
};
this.cursorBlink = this.cursorBlink.bind(this);
}
componentDidMount() {
this.c = document.getElementsByClassName('canvasTextEditor')[0];
this.ctx = this.c.getContext('2d');
this.ctx.font = this.state.fontSize + 'px ' + this.state.font;
clearInterval(this.cursorBlinkFunc);
this.cursorBlinkFunc = setInterval(this.cursorBlink, this.state.cursorBlinkSpeed * 1000);
this.c.onkeydown = e => {
console.log(e.key);
clearInterval(this.cursorBlinkFunc);
this.cursorBlinkFunc = setInterval(this.cursorBlink, this.state.cursorBlinkSpeed * 1000);
switch (e.key) {
case 'Enter':
break;
default:
this.setState({cursorPos: [this.state.cursorPos[0] + this.state.fontSize, this.state.cursorPos[1]]});
console.log(this.state.cursorPos);
}
this.setState({text: this.state.text + e.key});
this.drawText();
};
}
cursorBlink() {
const x = this.state.cursorPos[0];
const y = this.state.cursorPos[1];
console.log('cursorBlink:', x, y);
this.drawCursor(x, y);
setTimeout(() => {
this.eraseCursor(x, y);
}, this.state.cursorBlinkSpeed / 2 * 1000);
}
drawCursor(x, y) {
this.ctx.moveTo(x, y);
this.ctx.lineTo(x, y + this.state.cursorSize[1]);
this.ctx.lineWidth = this.state.cursorSize[0];
this.ctx.strokeStyle = this.state.cursorColour;
this.ctx.stroke();
}
eraseCursor(x, y) {
this.ctx.lineTo(x, y + this.state.cursorSize[1]);
this.ctx.strokeStyle = this.state.backgroundColour;
this.ctx.stroke();
}
drawText() {
this.ctx.clearRect(0, 0, this.c.width, this.c.height);
this.ctx.fillText(this.state.text, 20, this.state.fontSize);
}
render() {
return (
<div>
<canvas className="canvasTextEditor" width="800" height="600" tabIndex="1"/>
</div>
);
}
}
export default CanvasTextEditor;
定位和其他一些东西还不正确,但我想首先解决重复光标的问题。每次按下一个键时,一个新光标会从前一个光标向前出现一点,而前一个光标在那里闪烁,几乎就像它嘲弄我一样。这很古怪!
答案 0 :(得分:0)
看起来我只是忘了这样做.ctx.beginPath()
糟糕