javascript - Canvas clearRect 仅在循环中第一次工作,发生了什么?

标签 javascript jquery canvas

这不是完整的代码,其他部分只是大括号和一些函数。 它是循环中要做的事情的主要部分。我想要获得具有边框半径(如 Angular )的矩形,以便通过它们查看 Canvas 下的内容。但我只是第一次得到clearRect。或者它们可能只是没有显示,因为循环在我需要的时候都可以工作。

 function draw() {
            $document = $(document);
            canvas.width = $document.width();
            canvas.height = $document.height();

            ctx.fillStyle = "rgba(0,0,0, 0.6)";
            ctx.fillRect(0, 0, canvas.width, canvas.height);

            var $layer = $('#hint-layer'),
                $arrows = $('.arrows', $layer);

            $arrows.empty();

            $(options.selector).each(function() {
                var $this = $(this);
                roundedRect(ctx,
                    $this.offset().left -5,
                    $this.offset().top -5,
                    $this.outerWidth() + 10,
                    $this.outerHeight() + 10
                    ,10);

                ctx.clip();
                ctx.clearRect(
                    $this.offset().left -5,
                    $this.offset().top -5,
                    $this.outerWidth() + 10,
                    $this.outerHeight() + 10
                );
    }

    function roundedRect(ctx,x,y,width,height,radius){
          ctx.beginPath();
          ctx.moveTo(x,y+radius);
          ctx.lineTo(x,y+height-radius);
          ctx.quadraticCurveTo(x,y+height,x+radius,y+height);
          ctx.lineTo(x+width-radius,y+height);
          ctx.quadraticCurveTo(x+width,y+height,x+width,y+height-radius);
          ctx.lineTo(x+width,y+radius);
          ctx.quadraticCurveTo(x+width,y,x+width-radius,y);
          ctx.lineTo(x+radius,y);
          ctx.quadraticCurveTo(x,y,x,y+radius);
          ctx.stroke();
}

最佳答案

您需要使用 ctx.save 和 ctx.restore 重置剪辑

$(options.selector).each(function() {
    var jQ =$(this);
    roundedRect(ctx,
        jQ .offset() .left - 5,
        jQ .offset() .top - 5,
        jQ .outerWidth() + 10,
        jQ .outerHeight() + 10
        ,10
    );
    ctx.save(); // save current unclipped state
    ctx.clip();
    ctx.clearRect(
        jQ .offset() .left - 5,
        jQ .offset() .top - 5,
        jQ .outerWidth() + 10,
        jQ .outerHeight() + 10
    );
    ctx.restore(); // remove the clip by restoring to unclipped state.
}

关于javascript - Canvas clearRect 仅在循环中第一次工作,发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40874624/

相关文章:

javascript - knockout 从输入到函数的发送值

javascript - MVC Webgrid,javascript 在排序和分页后停止工作

javascript - scrollLeft 在 Internet Explorer 中不起作用

javascript - 如何使用 MomentJS 正确检查日期是否相同或晚于今天?

javascript - 如何使用 jquery 将项目从一个列表移动到多个其他列表?

javascript - HTML5/JS大量隐藏 Canvas

ios - 使用 Retina 显示屏在 Canvas 上绘制图像

javascript - JavaScript 中拖放功能的问题

jquery - 用 jquery Accordion 跳跃

javascript - 绘制两个半圆,错误的填充点