Home >Web Front-end >H5 Tutorial >h5canvas implements scratch effect code
There are two main things to pay attention to when implementing scratch-off on canvas: The first is to set the drawn graphics as background images (using the toDataURL attribute), so that the drawn patterns will not be lost when the overlay is wiped,
The second is to set the transparency when drawing illustrations (using the globalCompositeOperation attribute)
The code is as follows:
<script> var arr=[ {name:"iphone7 磨砂黑",color:"rgba(255,255,0,1)"}, {name:"iphone7 磨砂黑",color:"rgba(0,255,0,.9)"}, {name:"iphone7 磨砂黑",color:"rgba(10,255,255,1)"}, {name:"iphone7 磨砂黑",color:"rgba(10,255,100,1)"} ] var r=Math.random(); var rIndex= Math.floor(r*arr.length); var rPrice=arr[rIndex]; var cv=document.getElementsByTagName('canvas')[0]; var isDown=false; cv.height=400; cv.width=600; var ctx=cv.getContext("2d"); function toAngle(radian){ return radian/Math.PI*180; } function toRadian(angle){ return angle/180*Math.PI; } ctx.textAlign="center"; ctx.textBaseline="middle"; ctx.font="30px consolas"; ctx.fillStyle=rPrice.color; ctx.fillText(rPrice.name,cv.width/2,cv.height/2); var dataURL=cv.toDataURL("image/jpg",1); cv.style.background="url("+dataURL+")"; //覆盖层 ctx.beginPath(); ctx.fillStyle="#eee"; ctx.fillRect(0,0,cv.width,cv.height); cv.addEventListener("mousedown",function(){ isDown=true; }) cv.addEventListener("mouseup",function(){ isDown=false; ctx.globalCompositeOperation="source-out" }) cv.addEventListener("mousemove",function(e){ if (isDown){ ctx.globalCompositeOperation="destination-out"; ctx.beginPath(); var posObj=cv.getBoundingClientRect(); var left=posObj.left; var top=posObj.top; var x= e.clientX-left; var y= e.clientY-top; ctx.arc(x,y,50,0,Math.PI*2); ctx.fill(); } }) </script>
【 Related recommendations】
1. Special recommendation:"php Programmer Toolbox" V0.1 version download
2. Free h5 online video tutorial
3. php.cn original html5 video tutorial
The above is the detailed content of h5canvas implements scratch effect code. For more information, please follow other related articles on the PHP Chinese website!