


This article mainly introduces the implementation method and implementation code of Scratch Lottery on the mobile terminal. Has very good reference value. Let’s take a look at it with the editor
Programmers have a habit of thinking, that is, when they see something that moves (something with a bit of technology, forget about cats or dogs), they always have to think about it first. , how is this thing controlled by code? For example, elevators, neon lights on the roadside, remote controls, children's toys, etc. have all been "obscene" by programmers.
Sometimes I feel that programmers can see the world more clearly.......
I believe everyone has played scratch games, let’s introduce one A mobile way to implement scratch-off games! Use canvas
1. Use HTML 5 canvas globalCompositeOperation attribute to implement scratch-off
Ideas:
(1) First, you need to position a box to determine where you want to place the scratch-off area.
(2) There is a box in the positioning box for the content, which is where the prizes are placed.
(3) Cover the upper box with a canvas
(4) When the hand touches and moves, part of the canvas can be erased to reveal the prize area
(5) When enough (3/4) has been erased, you can choose to make the canvas disappear automatically and slowly fade out (this effect is optional)
Mainly the fourth step, How to erase?
GlobalCompositeOperation is selected here, which is the synthesis operation in Canvas. Simply put, Composite (combination) is the combined display effect between the graphics you draw later and the graphics you draw first in drawing. For example, in Chinese painting, you first draw a stroke of red, then a stroke of green, and they intersect. The part is a mixed color, and in oil painting, the green will cover the red of the intersecting part. The processing in program drawing is Composite, the corresponding function in Canvas API It is globalCompositeOperation.
There is a property value in globalCompositeOperation that is "destination-out", which means it will be transparent when the paintings overlap. Just when we use it here, we can doodle on the canvas. The overlapping areas will become transparent and reveal what is under the canvas, which is the effect we want.html code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" /> <title></title> <link rel="stylesheet" type="text/css" href="css/guaguale.css" rel="external nofollow" /> </head> <body> <!-- 大的背景盒子--> <p id="main"> <!-- 定位的盒子--> <p class="canvasBox"> <!-- 放内容的盒子--> <span id="prize"> 恭喜发财,红包拿来 </span> <!-- 蒙版画布--> <canvas id="canvas"></canvas> </p> </p> </body> <script type="text/javascript"> var canvas = document.getElementById("canvas"); var ctx = canvas.getContext('2d'); /* 画布偏移量,下面用到的时候再介绍*/ var arr = getOffset(canvas); var oLeft = arr[0]; var oTop = arr[1]; /* 初始化画布*/ ctx.beginPath(); ctx.fillStyle = '#ccc'; ctx.fillRect(0,0,canvas.width,canvas.height); ctx.closePath(); /* 增加触摸监听*/ document.addEventListener("touchstart",function(){ /* 初始化画笔*/ ctx.beginPath(); /* 画笔粗细*/ ctx.lineWidth = 30; /* 设置组合效果*/ ctx.globalCompositeOperation = 'destination-out'; /* 移动画笔原点*/ ctx.moveTo(event.touches[0].pageX-oLeft,event.touches[0].pageY-oTop); },false) document.addEventListener("touchmove",function(){ /* 根据手指移动画线,使之变透明*/ ctx.lineTo(event.touches[0].pageX-oLeft,event.touches[0].pageY-oTop); /* 填充*/ ctx.stroke(); }) /* 之所以会用到下面的那个函数getOffset(obj) * 是因为event.touches[0].pageX、pageY获取的是相对于可视窗口的距离 * 而lineTo画笔的定位是根据画布位置定位的 * 所以就要先获取到画布(canvas)相对于可视窗口的距离,然后计算得出触摸点相对于画布的距离 * */ /* 获取该元素到可视窗口的距离*/ function getOffset(obj){ var valLeft = 0,valTop = 0; function get(obj){ valLeft += obj.offsetLeft; valTop += obj.offsetTop; /* 不到最外层就一直调用,直到offsetParent为body*/ if (obj.offsetParent.tagName!='BODY') { get(obj.offsetParent); } return [valLeft,valTop]; } return get(obj); } </script> </html>
css code is as follows:
*{ margin: 0; padding: 0; } #main{ width: 100%; padding: 20px 0; background-color: red; } .canvasBox{ width: 78%; height: 160px; border-radius: 10px; background-color: #FFF; margin-left: 11%; line-height: 160px; text-align: center; position: relative; } #canvas{ width: 96%; height: 96%; position: absolute; left: 2%; top: 2%; background-color: transparent; }The fifth step is to use canvas pixels Get (note here, pixel-level operations must be opened in a server environment) getImageData(int x, int y, int width, int height): This method gets the (x, y) point on the canvas Starting with the data of the picture area whose width is width and height is height, this method returns a Canv
asPixelArray object, which has attributes such as width, height, and data. The data attribute is an array, and every 4 elements of the array correspond to one pixel.
(You can also do this to reverse the image and change the rgba value)The object returned by getImageData(int x, int y, int width, int height), data What is stored inside is the pixel information
js code:
document.addEventListener("touchend",function(){ /* 获取imageData对象*/ var imageDate = ctx.getImageData(0,0,canvas.width,canvas.height); /* */ var allPX = imageDate.width * imageDate.height; var iNum = 0;//记录刮开的像素点个数 for(var i=0;i<allPX;i++){ if(imageDate.data[i*4+3] == 0){ iNum++; } } if(iNum >= allPX*3/4){ // disappear里面写了缓慢清除的css3动画效果 canvas.setAttribute('class','disappear'); } },false)
" .disappear " css style, css3 disappearance animation
.disappear{ -webkit-animation: disa 2s 1; animation: disa 2s 1; -webkit-animation-fill-mode: forwards; -moz-animation-fill-mode: forwards; -o-animation-fill-mode: forwards; animation-fill-mode: forwards; } @keyframes disa{ 0%{opacity:1;} 100%{opacity: 0;} }
The above is the detailed content of Detailed explanation of the way to implement scratch-off games on the mobile terminal using js+HTML5. For more information, please follow other related articles on the PHP Chinese website!

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1
Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools
