【发布时间】:2018-12-12 09:23:22
【问题描述】:
我正在尝试使图像在浏览器中可编辑。我找到了this,并尝试重新使用此代码以供我使用。这就是我最终得到的结果:
export default class CanvasComponent extends React.Component {
constructor(props) {
super(props);
this.lastX = 0;
this.lastY = 0;
this.ctx = 0;
}
componentWillReceiveProps(nextProps) {
this.ctx = document.getElementById('canvas').getContext('2d');
const img = new Image();
img.onload = () => {
this.ctx.drawImage(img, 0, 0, nextProps.width, nextProps.height);
};
img.src = URL.createObjectURL(nextProps.image)
}
handleClick = () => {
const canvas = document.getElementById('canvas');
canvas.addEventListener('click', (e) => {
this.Draw(e.pageX - canvas.offsetLeft, e.pageY - canvas.offsetTop);
})
};
Draw = (x, y) => {
console.log('drawing');
this.ctx.beginPath();
this.ctx.strokeStyle = 'red';
this.ctx.lineWidth = 5;
this.ctx.lineJoin = "round";
this.ctx.moveTo(this.lastX, this.lastY);
this.ctx.lineTo(x, y);
this.ctx.closePath();
this.ctx.stroke();
this.lastX = x;
this.lastY = y;
};
render() {
return (
<div>
<canvas onClick={this.handleClick} width={this.props.width} height={this.props.height} id={'canvas'}/>
</div>
);
}
}
我真的不知道画布(第一次使用它)所以我可能在做一些非常愚蠢的事情(请不要大喊大叫)。
现在的代码是这样的:https://youtu.be/4rvGigRvJ8E
我无法将其制作成 gif。对不起
我想要发生的事情: 当用户单击图像时,我希望出现一个点来代替单击。我怎样才能做到这一点?
新的Draw 方法
Draw = (x, y) => {
console.log('drawing');
this.ctx.beginPath();
this.ctx.strokeStyle = 'red';
this.ctx.lineWidth = 5;
// x, y are the cords, 5 is the radius of the circle and the last 2 things specify full circle.
this.ctx.arc(x, y, 5, 0, 2 * Math.PI);
this.ctx.stroke();
this.lastX = x;
this.lastY = y;
};
【问题讨论】:
-
视频似乎无法播放,您能否描述一下这个问题?
-
抱歉,我将其设置为私有。现已公开
-
您可以删除
lineTo和moveTo命令并将其替换为this.ctx.arc(x, y, 1, 0, 2 * Math.PI)。您可以删除 lastX 和 lastY 变量 -
这几乎可以工作。但点消失/不留在画布上。单击后它会出现一秒钟,然后消失。什么会导致它?我将添加我更新的代码
标签: javascript reactjs canvas html5-canvas