The clip () method in canvas is used to cut arbitrary shapes and sizes from the original canvas. Once an area is clipped, all subsequent drawings are restricted to the area being clipped (no access to other areas on the canvas)
You can also save the current canvas area by using the Save () method before using the clip () method, and restore it at any later time through the Restore () method
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= "290" style= "border:1px solid black" > current browser does not support canvas, please replace the browser and try </canvas><script>btn.onclick = function () {history.go ();} Con.onclick = function () {if (this.innerhtml = = ' Pause ') {this.innerhtml = ' recover '; Clearinterval (Otimer); }else{this.innerhtml = ' pause '; Otimer = SetInterval (fninterval,50); }}var canvas = document.getElementById (' canvas ');//Storage canvas height var h=290,w=400;//storage searchlight var ball = {};//storage photo var img;// Store photo address var URL = ' http://www.php.cn/'; 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 if (ele.x <= ele.r) {ele.x = ELE.R; ELE.STEPX =-ele.stepx; }//Right if (ele.x >= w-ele.r) {ele.x = W-ELE.R; ELE.STEPX =-ele.stepx; }//Upper side 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 () {//Resets the canvas height to the effect of emptying the canvas canvas.height = H; if (canvas.getcontext) {var cxt = Canvas.getcontext (' 2d '); Cxt.save (); Paint the canvas background black 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 clip () area cxt.drawimage (img,0,0); Cxt.restore (); }}initial (); clearinterval (otimer); function Fninterval () {//Update Motion State Update (); Renders render (); }var Otimer = setinterval (fninterval,50);</script>