假设我有以下代码。HTML canvas聚光灯效果
// Find out window height and width
wwidth = $(window).width();
wheight = $(window).height();
// Place Canvas over current Window
$("body").append($("<canvas id='test' style='position:absolute; top:0; left:0;'></canvas>"));
var context = document.getElementById("test").getContext("2d");
context.canvas.width = wwidth;
context.canvas.height = wheight;
// Paint the canvas black.
context.fillStyle = '#000';
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
// On Mousemove, create "Flashlight" around the mouse, to see through the canvas
$(window).mousemove(function(event){
x = event.pageX;
y = event.pageY;
radius = 50;
context = document.getElementById("test").getContext("2d");
// Paint the canvas black. Instead it will draw it white?!
//context.fillStyle = '#000';
//context.clearRect(0, 0, context.canvas.width, context.canvas.height);
//context.fillRect(0, 0, context.canvas.width, context.canvas.height);
context.beginPath();
radialGradient = context.createRadialGradient(x, y, 1, x, y, radius);
radialGradient.addColorStop(0, 'rgba(255,255,255,1)');
radialGradient.addColorStop(1, 'rgba(0,0,0,0)');
context.globalCompositeOperation = "destination-out";
context.fillStyle = radialGradient;
context.arc(x, y, radius, 0, Math.PI*2, false);
context.fill();
context.closePath();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Test</div>
生成鼠标移动上产生以下影响:
如何补充聚光灯前用黑色画布绘制?我已经尝试了注释代码块中的内容,但它将所有内容都绘制成白色。
编辑:我不想在图像上产生这种效果。相反,我想将Canvas放置在整个网页上。此外,我希望Canvas始终为黑色,并且鼠标在其位置上生成Spotlight,以查看Canvas下面的内容,就像您可以在图片中看到的一样,或者在Snippet中将div放在空白的html页面中“测试”中。
你看过http://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing?这里 –
几个问题。我们无法重现你的例子,例如'giveCanvasContext'不是天真的功能。注意用黑色填充画布,你不需要'beginPath'或'endPath'。 –
@ CI_是的,我做到了,但它似乎像画布将绘制白色,而不是与黑色再次填补了.. – TeaTime