【发布时间】:2015-12-03 04:20:45
【问题描述】:
假设我有以下代码。
// 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>
对 mousemove 产生以下效果:
如何在聚光灯绘制之前用黑色填充画布?我已经尝试过注释掉的代码块中的内容,但它会将所有内容都涂成白色。
编辑:我不希望在图像上产生这种效果。相反,我想将画布放在整个网页上。我还希望画布始终为黑色,并且鼠标在其位置上生成一个聚光灯,以查看画布下方的内容,就像您在图片中看到的那样,或者在片段中放置了一个 div 的空 html 页面“测试”在里面。
【问题讨论】:
-
这里有几个问题。我们无法重现您的示例,例如
giveCanvasContext不是天真的函数。注意用你不需要beginPath或endPath的黑色填充画布。 -
@ci_ 是的,我做到了,但似乎画布将被绘制为白色而不是再次填充黑色..
标签: javascript html canvas