Canvas searchlight effect, canvas searchlight
The clip () method in the canvas is used to cut any shape and size from the original canvas. Once an area is cut, all subsequent drawings are restricted to the area to be cut (other areas on the canvas cannot be accessed)
You can also save the current canvas area by using the save () method before using the clip () method, and restore it through the restore () method at any time in the future.
Next, use the clip () method to achieve a searchlight effect.
<Button id = "btn"> transform </button> <button id = "con"> pause </button> <canvas id = "canvas" width = "400" height = & quot; 290 & quot; style = & quot; border: 1px solid black "> the current browser does not support canvas. Please change the browser and try again </canvas> <script> btn. onclick = function () {history. go ();} con. onclick = function () {if (this. innerHTML = 'paused ') {this. innerHTML = 'restore'; clearInterval (oTimer);} else {this. innerHTML = 'paused '; oTimer = setInterval (fnInterval, 50);} var canvas = document. getElementById ('canvas '); // storage canvas width and height var H = 290, W = 400; // storage searchlight var ball ={}; // storage photo var IMG; // store the photo URL var URL =' http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/chunfen.jpg '; Function initial () {if (canvas. getContext) {var cxt = canvas. getContext ('2d '); var tempR = Math. floor (Math. random () * 30 + 20); var tempX = Math. floor (Math. random () * (W-tempR) + tempR); var tempY = Math. floor (Math. random () * (H-tempR) + tempR) ball = {x: tempX, y: tempY, r: tempR, stepX: Math. floor (Math. random () * 21-10), stepY: Math. floor (Math. random () * 21-10)}; IMG = document. createElement ('img '); img. src = URL; IMG. onload = function () {cxt. drawImage (IMG, 0, 0) ;}} function update () {ball. x + = ball. stepX; ball. y + = ball. stepY; bumpTest (ball);} function bumpTest (ele) {// left-side if (ele. x <= ele. r) {ele. x = ele. r; ele. stepX =-ele. stepX;} // if (ele. x> = W-ele. r) {ele. x = W-ele. r; ele. stepX =-ele. stepX;} // if (ele. y <= ele. r) {ele. y = ele. r; ele. stepY =-ele. stepY;} // lower side if (ele. y> = H-ele. r) {ele. y = H-ele. r; ele. stepY =-ele. stepY ;}} function render () {// reset the canvas height to clear the canvas. height = H; if (canvas. getContext) {var cxt = canvas. getContext ('2d '); cxt. save (); // black the canvas background cxt. beginPath (); cxt. fillStyle = '# 000'; cxt. fillRect (0, 0, W, H); // render searchlight cxt. beginPath (); cxt. arc (ball. x, ball. y, ball. r, 0, 2 * Math. PI); cxt. fillStyle = '# 000'; cxt. fill (); cxt. clip (); // because clip () is used, the canvas background image appears in the cxt () area. drawImage (IMG, 0, 0); cxt. restore () ;}} initial (); clearInterval (oTimer); function fnInterval () {// update motion state update (); // render ();} var oTimer = setInterval (fnInterval, 50); </script>