【问题标题】:Drawing on canvas with React setState使用 React setState 在画布上绘图
【发布时间】:2017-06-17 09:11:09
【问题描述】:

我的问题,我正在尝试使用从链接派生的 React setState 在画布上绘制图像数组。在对画布进行一些操作后,我重新渲染了所有内容,它可以工作,但我遇到了轻微的不一致。我需要在画布上“玩” 10 分钟才能让这个错误发生。

应该是:

偶尔会发生的情况:

我已经尽我所能,我确定我只画了一次。我尝试从 setState 回调、从 setTimeout 到 setState 回调、从 setTimeout 等分别调用它,但始终存在错误。我知道 setState 的异步性质,但这应该可以正常工作。我很难理解这与canvas api或react api有关。如果您需要更多信息,请告诉我!相关代码:

export let mapImage=curry((
    ctx:CanvasRenderingContext2D,
    link:string,
    width:number,
    location:Vertex
)=>{
    let img=new Image();
    let place=location; 
    img.src=link;    
    img.onload=()=>{ 
        ctx.save(); 
        ctx.beginPath();
        ctx.arc(
            place.x+width/2,
            place.y+width/2,
            width/2,
            0,
            Math.PI*2,true
        );  
        ctx.closePath();
        ctx.clip();
        ctx.drawImage( 
            img,  
            place.x,
            place.y,
            width,   
            width  
        );         
        ctx.restore();   
    };  
});       

On event:
       this.setState({down_delay:0, 
                      mouse_down:false},()=>{this.drawCard()}); 

In drawCard:
       this.context.clearRect(0,0,this.props.width,this.props.height);
       map(mapImage,this.props.vertices) 

...rest of the code 

谢谢!

【问题讨论】:

    标签: javascript html reactjs typescript canvas


    【解决方案1】:

    根据所提供的信息,不可能给出完美的答案。这就是我发现人们最常说的:

       this.setState({down_delay:0, 
                      mouse_down:false},()=>{this.drawCard()}); 
       moreCodeWithoutRealizingItWillRunBeforeDrawCard();
    

    建议探索

    您可以通过使用@action 装饰器和mobx 来避免这些问题。 I stopped using setState ?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 2019-08-14
      • 1970-01-01
      相关资源
      最近更新 更多