【问题标题】:Adding a dot where a canvas is clicked在单击画布的位置添加一个点
【发布时间】: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;
};

【问题讨论】:

  • 视频似乎无法播放,您能否描述一下这个问题?
  • 抱歉,我将其设置为私有。现已公开
  • 您可以删除lineTomoveTo 命令并将其替换为this.ctx.arc(x, y, 1, 0, 2 * Math.PI)。您可以删除 lastX 和 lastY 变量
  • 这几乎可以工作。但点消失/不留在画布上。单击后它会出现一秒钟,然后消失。什么会导致它?我将添加我更新的代码

标签: javascript reactjs canvas html5-canvas


【解决方案1】:

您的绘图代码似乎试图绘制一条线而不是一个圆......

要画一个圆,看看这个例子。

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();

记录在案的https://developer.mozilla.org/kab/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes#Arcs

此外,您似乎试图附加一个侦听器而不是对侦听进行操作,您传递给 onClick 的函数将在每次点击时被调用,也不需要在其中附加一个点击侦听器。

【讨论】:

  • 这几乎可以工作。但点消失/不留在画布上。单击后它会出现一秒钟,然后消失。什么会导致它?我将添加我更新的代码
  • 供以后参考:点的消失是由 React 重新渲染图像引起的。请参阅stackoverflow.com/a/53744356/7055769 了解更多信息
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多