简体   繁体   English

画布:在整个画布上创建半透明覆盖,除了一个窗口

[英]Canvas: create semi-transparent overlay over entire canvas except one window

I have a rectangular canvas with an image painted on it.我有一个矩形画布,上面画有图像。 As the user moves the cursor over the canvas, I'd like to make the canvas semitransparent except for a small rectangle around the cursor, which I'd like to retain the underlying image content in full opacity.当用户将光标移到画布上时,除了光标周围的一个小矩形,我想让画布半透明,我希望将底层图像内容保留为完全不透明。

So my question in brief is how to "mute" the canvas except for a small rectangle.所以我的问题是如何“静音”画布,除了一个小矩形。

My first thought was to create a semitransparent overlay over the entire canvas, then just paint the rectangular region that should be full opacity again, but this makes the background disappear while I want to retain it at 0.2 opacity:我的第一个想法是在整个画布上创建一个半透明的叠加层,然后再绘制应该完全不透明的矩形区域,但这会使背景消失,而我想将其保留在 0.2 不透明度:

 var elem = document.querySelector('canvas'); var ctx = elem.getContext('2d'); elem.width = 400; elem.height = 300; ctx.fillStyle = '#ff0000'; ctx.fillRect(0, 0, elem.width, elem.height); elem.addEventListener('mousemove', function(e) { ctx.globalAlpha = 0.2; ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, elem.width, elem.height); var x = e.clientX; var y = e.clientY; var d = 30; ctx.fillStyle = '#ff0000'; ctx.fillRect(xd, yd, d*2, d*2); })
 <canvas/>

Does anyone know the most performant way to mute the background to 0.2 opacity while retaining the rectangle around the cursor at full opacity?有谁知道将背景静音到 0.2 不透明度同时将光标周围的矩形保留为完全不透明度的最有效方法吗? Any pointers would be super helpful!任何指针都会非常有帮助!

Here's the two canvas method:这是两个画布方法:

 var elemA = document.querySelector('#a'); var elemB = document.querySelector('#b'); var ctx = elemA.getContext('2d'); var bctx = elemB.getContext('2d'); elemA.width = elemB.width = 400; elemA.height = elemB.height = 300; ctx.fillStyle = '#ff0000'; ctx.fillRect(0, 0, elemA.width, elemA.height); elemB.addEventListener('mousemove', function(e) { bctx.clearRect(0, 0, elemB.width, elemB.height); var x = e.clientX; var y = e.clientY; var x0 = x-10; var x1 = x+10; var y0 = y-10; var y1 = y+10; // draw boxes; origin is top left bctx.globalAlpha = 0.8; bctx.fillStyle = '#ffffff'; bctx.fillRect(0, 0, elemA.width, y0); // top bctx.fillRect(0, y0, x0, elemB.height+20); // left bctx.fillRect(x0, y1, elemB.width+20, elemB.height); // bottom bctx.fillRect(x1, y0, elemA.width, y1-y0); // right })
 * { margin: 0; } #c { position: relative; } #a, #b { position: absolute; top: 0; right: 0; bottom: 0; left: 0; } #b { z-index: 1; opacity: 0.5; }
 <div id='c'> <canvas id='a'></canvas> <canvas id='b'></canvas> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM