javascript - 在 Canvas 上分层矩形会导致不透明度增加

标签 javascript html css canvas opacity

我正在使用 jpeg 图像和我在图像上绘制的矩形对图像进行注释。然后我可以将图像传输到 Canvas ,并且使用 for 循环,我可以获取我在图像上绘制的矩形 div 的边界,以便在 Canvas 上重新绘制。

当我有多个矩形时会出现问题,因为每个后续矩形的不透明度都会降低,因为它们是分层的,因此:`

    function drawRectangleToCanvas(left, top, width, height, canvas, context, opacity) { 

    context.globalCompositeOperation='destination-over';
    context.strokeStyle = 'rgba(0,255,130,0.7)';
    context.fillStyle = 'rgba(0,0,255,'+opacity+')';
    context.rect(left, top, width, height);
    context.setLineDash([2,1]);
    context.lineWidth = 2;
    context.fill();
    context.stroke();

    }

根据我的理解,context.globalCompositeOperation='destination-over' 导致矩形像面包片一样放置在图像上。对于在 div 上绘制的每个矩形,不透明度重叠,导致不透明度增加一个因子,在本例中为 0.1。这是问题的样子:Canvas with layered rectangles and opacity problems.

我怎样才能添加所有的矩形而没有这个不透明度问题?我为我拥有的每个矩形调用此方法,所以我不知道我是否可以将所有矩形放在一个数组中或什么。解决此问题的任何建议都会有所帮助。

编辑:最暗的矩形是第一个绘制的,只是为了添加一些信息。

最佳答案

不完全确定您想要什么,但您可以在定义所有矩形之前省略对 strokefill 方法的调用。

    // Not much left to do in the function but just here to illustrate
    // that creating the rectangles should be put together
    function drawRectangleToCanvas(left, top, width, height, canvas, context){ 
        context.rect(left, top, width, height);
    }

    context.globalCompositeOperation='destination-over';
    context.strokeStyle = 'rgba(0,255,130,0.7)';
    context.fillStyle = 'rgba(0,0,255,'+opacity+')';
    context.setLineDash([2,1]);
    context.lineWidth = 2;
    context.beginPath();
    while(??? ){
        // loop and define all the rectangles 
        drawRectangleToCanvas(...  //
    }
    // once all the rectangles are defined 
    // call the fill and stroke to render them
    context.fill();
    context.stroke();

这将阻止他们复合 alpha 值

关于javascript - 在 Canvas 上分层矩形会导致不透明度增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34363838/

相关文章:

javascript - 在同一页面上运行 2 个 Emscripten 脚本

javascript - 如何使用 JQuery/CSS 在单击按钮时将 div 面板移动到所有其他 div 面板下方?

html - 如何在 float :left element to stop next element to move position if current element changes size? 之间设置一个固定间隙

css - 如何将 css 添加到 .scss 文件或主题中

javascript - Highcharts js : get errors if there is a big point in a 3d series chart

javascript - 如何使用 Javascript 将数据写入 JSON 文件

javascript - 在未定义上使用严格相等会引发错误吗?

javascript - 如何使用javascript读取html "<a>"标签中的所有href链接

html - Netbeans 中有关为我的 Web 应用程序设置元素默认值的提示弄乱了我所有的 HTML 文件

javascript - 带高度的媒体查询