Javascript 在单击画布的位置添加点
我正在尝试使图像在浏览器中可编辑。我找到了,我试图重新使用这段代码。这就是我的结局:Javascript 在单击画布的位置添加点,javascript,reactjs,canvas,html5-canvas,Javascript,Reactjs,Canvas,Html5 Canvas,我正在尝试使图像在浏览器中可编辑。我找到了,我试图重新使用这段代码。这就是我的结局: export default class CanvasComponent extends React.Component { constructor(props) { super(props); this.lastX = 0; this.lastY = 0; this.ctx = 0; } componentWillRec
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>
);
}
}
你的绘图代码似乎试图画一条线而不是一个圆 要画一个圆,请看这个例子 this.ctx.beginPath; this.ctx.strokeStyle='red'; this.ctx.lineWidth=5; //x,y是线,5是圆的半径,最后2个表示整圆。 this.ctx.arcx,y,5,0,2*Math.PI;
这个.ctx.stroke;视频似乎不可用,你能描述一下这个问题吗?对不起,我将其设置为私密。现在它是公共的。您可以删除lineTo和moveTo命令,并将其替换为this.ctx.arcx,y,1,0,2*Math.PI。您可以删除lastX和lastY变量。这几乎可以正常工作。但是圆点消失了/没有停留在画布上。单击后它会出现一秒钟,然后消失。是什么引起的?我将添加我的更新代码,这几乎有效。但是圆点消失了/没有停留在画布上。单击后它会出现一秒钟,然后消失。是什么引起的?我将添加我的更新代码以供将来参考:点的消失是由于重新渲染图像造成的。有关更多信息,请参阅
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;
};