In mobile devices, almost all operations are related to touch, and based on this feature, some more special interaction methods have also emerged in mobile terminals in recent years. Using a finger to "scratch prizes" on the screen is a very typical example. It not only requires front-end designers to be familiar with the control methods of touch gestures, but also requires designers to master certain image processing skills. Next, we will learn about touch operations in HTML5 by making a simple scratch case.
1. The basics of touch interaction - the difference between Touch and Click
On mobile devices, the way people interact is no longer keyboards and mice, but fingers. Therefore, the interaction method of the corresponding mobile page will be different from that of the desktop.
On the desktop side, to create a click function for a submit button, you can use the following JavaScript code:
var submit = document.getElementById("submit"); submit.onclick = function(){ // function code };
The above code uses the onclick event to correspond to the mouse click behavior. However, when testing on mobile devices like the iPhone, we found that the onclick event has a delay of about half a second, because the iOS system needs to wait for a while to determine whether the user is clicking or dragging. To make the user's interaction on the mobile terminal smoother, the Touch event needs to be used, so that the page knows that the user's interaction is not a click, but a "touch". code show as below:
submit.addEventListener("touchstart", submitForm); function submitForm(){ // function code }
The above code uses the addEventListener method to register event listeners for the submit element, the listener event is touchstart, and the triggered function is submitForm(). That is to say, when the user touches the submit button on the mobile device, the touchstart event of the button is triggered and the submitForm function is executed.
When the touchstart event is triggered, an event object is also generated, which includes various information about the touch behavior. For example, we can use the following code to output the number of touch points:
function submitForm(event){ submit.innerHTML = "The number of touch points" + event.touches.length; }
We can also get the x and y position attributes of the touch point, whose attribute names are pageX and pageY respectively. The following code will output the x coordinate of the first touch point:
function submitForm(event){ submit.innerHTML = "X position of the first touch point" + event.touches[0].pageX; }
In addition to touchstart, touch-related events in HTML5 also include touchmove and touchend. The former is triggered continuously while the finger is dragging the page element, while the latter is triggered when the finger is removed from a page element.
In addition to touch events, gesture events, which are multi-finger operations, are also provided in iOS devices. It can be understood that when the user puts one finger on the button, touch is triggered at this time, and when the second finger is also placed on the button at this time, the gesture event is triggered. Gestures will be explained in detail in subsequent tutorials.
After understanding the basics of touch events, next, we will use the touch time to make a "scratch prize" effect.
2. HTML material preparation - prepare HTML code, necessary CSS styles and material files
First, we create a Canvas element in the page and put it into a div container
3. Use touch events to achieve scratch effect - write JavaScript code
We hope that the result of the scratch award will be covered by a color coating by default, and the user will not be able to see the result directly. Only after "scratching" the screen with a finger, can the bottom be seen by erasing the coating 's awards. This operation needs to be done in JavaScript, the code is as follows:
<script type="text/javascript"> var canvas=document.getElementById("mask"); var context=canvas.getContext("2d"); context.fillStyle="#D1D1D1"; //Set the fill color to light gray context.fillRect(0,0,240,65); //fill the color to cover the background image below </script>
The above code draws a light gray rectangle in the Canvas so that it covers the award image in the background below
Next, we need to make touch-based interactions so that when the user's finger moves across the coating, the light gray in the corresponding area is erased. Here, we can use a property called globalCompositeOperation in Canvas, by setting it to destination-out, so that when drawing again on the basis of the filled color, the drawn area becomes transparent, thereby revealing the underlying Picture of the award, the code is as follows:
context.globalCompositeOperation = 'destination-out';
Next, we create a touchmove event listener for the canvas. When the finger moves on the canvas, draw a corresponding circle at the touched position, which will subtract from the existing fill color, thereby wiping off the gray coating. code show as below:
canvas.addEventListener('touchmove', function(event) { //When the finger moves on the canvas event.preventDefault(); //First remove the default response behavior var touch = event.touches[0]; //Get the first point of touch context.beginPath(); //Start path drawing context.arc(touch.pageX-canvas.offsetLeft,touch.pageY-canvas.offsetTop,20,0,Math.PI*2); //Draw a circle at the touched place with a radius of 20 pixels context.closePath(); //End path drawing context.fillStyle="#BDC3C7"; //Set a drawing color at will context.fill(); //fill the color }); In the above code, it should be noted that the drawing coordinate value of the circle should be the coordinate value corresponding to the current touch position. However, the pageX and pageY properties of the touch point return the global coordinates for the entire page. We need to subtract the above property values from the x and y coordinates of the canvas itself to get the coordinates of the circle to be drawn in the canvas. Test the page, now we are able to "scratch" the prize with our finger on the screen. 4. Case Closing - Some Details to Consider It seems that the scratching effect is successfully completed like this. But imagine that in our actual development, users will basically jump to the next interface after scraping the prize to prompt the specific information of the prize, and how to judge whether the user has finished scraping the prize? If the user only touches it sporadically once or twice, it will not scratch off all the coating, nor will the full award information be seen. We make an assumption here that when 90% of the coated pixels are offset, that is, when 90% of the area is scratched off, the user has obtained the award-winning information relatively completely. At this time, it can be judged that the scratching award has been end. code show as below: canvas.addEventListener('touchmove', function(event) { // Previous code omitted var imgData = context.getImageData(0,0,240,65); //Get all pixels in the canvas var pixelsArr = imgData.data; //Get the byte data of the pixel var loop = pixelsArr.length; //Get the length of the data var transparent = 0; //Set a variable to record the number of pixels that have become transparent for (var i = 0; i < loop; i += 4) { //loop through each pixel var alpha = pixelsArr[i + 3]; //Get the transparency value of each pixel if (alpha < 10) { //When the transparency is less than 10, think it has been erased transparent++; //Add 1 to the transparent value } } var percentage = transparent / (loop / 4); //Calculate the proportion of transparent pixels in all pixels if(percentage>.9){ //When the ratio is greater than 90% document.getElementById("status").innerHTML = "Scratch end!"; //Display the word end of scratch } });
Now, refresh the page again, when we scratch the prize to a certain level, the words "Scratch Prize Ended" will be displayed below.
All code:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no,maximum-scale = 1.0"> <title>Touch实践</title> <style type="text/css"> #guajiang{ width:240px; height:65px; background:url(./guajiang.fw.png) no-repeat; background-size: auto 100%; } </style> </head> <body> <div id="guajiang"> <canvas width="240" height="65" id="mask"></canvas> </div> <script type="text/javascript"> var canvas=document.getElementById("mask"); var context=canvas.getContext("2d"); context.fillStyle="#D1D1D1"; //Set the fill color to light gray context.fillRect(0,0,240,65); //fill the color to cover the background image below context.globalCompositeOperation = 'destination-out';//The area passed through becomes transparent when drawn again canvas.addEventListener('touchmove', function(event) { //When the finger moves on the canvas // event.preventDefault(); //First remove the default response behavior var touch = event.touches[0]; //Get the first point of touch context.beginPath(); //Start path drawing context.arc(touch.pageX-canvas.offsetLeft,touch.pageY-canvas.offsetTop,10,0,Math.PI*2); //Draw a circle at the touched place with a radius of 20 pixels context.closePath(); //End path drawing context.fillStyle="#BDC3C7"; //Set a drawing color at will context.fill(); //fill the color var imgData = context.getImageData(0,0,240,65); //Get all pixels in the canvas var pixelsArr = imgData.data; //Get the byte data of the pixel var loop = pixelsArr.length; //Get the length of the data var transparent = 0; //Set a variable to record the number of pixels that have become transparent for (var i = 0; i < loop; i += 4) { //loop through each pixel var alpha = pixelsArr[i + 3]; //Get the transparency value of each pixel if (alpha < 10) { //When the transparency is less than 10, think it has been erased transparent++; //Add 1 to the transparent value } } var percentage = transparent / (loop / 4); //Calculate the proportion of transparent pixels in all pixels if(percentage>.3){ //When the ratio is greater than 90% alert("end") // document.getElementById("status").innerHTML = "Scratch end!"; //Display the word end of scratch } }); </script> </body> </html>
Expansion: H5 new attribute --- Compatible with IE9 at most! ! !
The <canvas> tag defines graphics, such as charts and other images.
The <canvas> tag is just a graphics container, and a script must be used to draw the graphics.
This HTML element is designed for client-side vector graphics. It has no behavior on its own, but exposes a drawing API to client-side JavaScript so that the script can draw whatever it wants to draw onto a canvas.
By default the <canvas> element has no border and no content
It is not capable of drawing itself. All drawing work must be done inside JavaScript