【问题标题】:clearRect function doesn't clear the canvasclearRect 函数不清除画布
【发布时间】:2012-11-06 07:43:19
【问题描述】:

我在bodyonmousemove函数上使用这个脚本:

function lineDraw() {
    // Get the context and the canvas:
    var canvas = document.getElementById("myCanvas");
    var context = canvas.getContext("2d");
    // Clear the last canvas
    context.clearRect(0, 0, canvas.width, canvas.height);
    // Draw the line:
    context.moveTo(0, 0);
    context.lineTo(event.clientX, event.clientY);
    context.stroke();
}

每次我移动鼠标时都应该清除画布并画一条新线,但它不能正常工作。 我试图在不使用 jQuery、鼠标侦听器或类似工具的情况下解决它。

这是一个演示:https://jsfiddle.net/0y4wf31k/

【问题讨论】:

    标签: javascript line draw onmousemove


    【解决方案1】:

    您应该使用“beginPath()”。就是这样。

    function lineDraw() {   
        var canvas=document.getElementById("myCanvas");
        var context=canvas.getContext("2d");
        context.clearRect(0, 0, context.width,context.height);
        context.beginPath();//ADD THIS LINE!<<<<<<<<<<<<<
        context.moveTo(0,0);
        context.lineTo(event.clientX,event.clientY);
        context.stroke();
    }
    

    【讨论】:

    • 想补充一点,这也适用于 rect 和 arc 等绘制方法。
    • 它很旧,但是...closePath 在这里是无用的和误导性的,它只是一个 lineTo(previousStartingPointOfThePath) 所以对于单行,它不会做任何事情,而且它根本不会说明你完成了你的路径声明。
    • 谢谢@kaiido,我编辑了这个问题。我认为编辑本着答案的精神。希望你不介意aviomaksim
    • 谢谢!太疯狂了,除非您执行beginPath,否则为什么清除失败?这没有任何意义。
    【解决方案2】:

    请注意,ctx.clearRect() 确实在 Google Chrome 上正常工作。我花了几个小时试图解决一个相关的问题,却发现在 Chrome 上,它不是用 rgba(0, 0, 0, 0) 填充矩形,而是 实际上 用 rgba(0 , 0, 0, 1) 代替!

    因此,为了用所需的透明黑色像素正确填充矩形,您需要在 Chrome 上改为这样做:

    ctx.fillStyle = "rgba(0, 0, 0, 0)";
    ctx.fillRect(left, top, width, height);
    

    当然,这应该适用于为 HTML5 Canvas 对象提供适当支持的所有浏览器。

    【讨论】:

      【解决方案3】:

      还有我们需要用到的beginPath()和stroke()。 此代码与 clearRect(...) 的工作方式相同

      ctx.beginPath();
      ctx.fillStyle = "rgba(0, 0, 0, 255)";
      ctx.fillRect(0, 0, canvas.width, canvas.height);    
      ctx.stroke();
      

      【讨论】:

        【解决方案4】:

        试试context.canvas.width = context.canvas.width:

        function lineDraw() {   
            var canvas=document.getElementById("myCanvas");
            var context=canvas.getContext("2d");
            //context.clearRect(0, 0, context.width,context.height);
            context.canvas.width = context.canvas.width;
            context.moveTo(0,0);
            context.lineTo(event.clientX,event.clientY);
            context.stroke();
        }
        

        演示HERE

        【讨论】:

        • 或者干脆myCanvas.width = myCanvas.width;
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-29
        • 1970-01-01
        • 2015-06-02
        • 2013-07-31
        • 2018-12-16
        相关资源
        最近更新 更多