Home Web Front-end JS Tutorial Javascript canvas implements scratch card lottery effect_javascript skills

Javascript canvas implements scratch card lottery effect_javascript skills

May 16, 2016 pm 03:48 PM
canvas javascript

Using canvas to create a simple scratch card effect, you can retest it every time you refresh it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<style type="text/css">
 *{ margin:0; padding:0;} 
 
.cjbox{ margin:100px; height:80px; width:200px; background:#FFF; position:relative;}
#canvas{position:absolute; left:0px; top:0px;z-index:99;}
.sjmes{ position:absolute; left:0px; top:0px; height:80px; width:200px; text-align:center; font-size:40px; line-height:80px; z-index:9;}
</style>
<title>demo1</title>
</head>
<body> 
 
<div style="position:relative; margin:20px 100px; background:#0CF; height:400px; width:500px; margin:0 auto;">
  <div>刮刮卡简单抽奖</div>
  <div class="cjbox">
    <div class="sjmes" id="sjmes"></div>
    <canvas width=200 height=80 id="canvas"></canvas> 
  </div>
</div> 
 
</body>
<script type="text/javascript">
//init 
var cjcon=["一等奖","二等奖","三等奖","谢谢参与"];//奖项设置
var cjper=[3,10,20,100];//奖项率,次数
/*
 * sjmes
 * @Author 透笔度(1530341234@qq.com)          
 * @param {cjcon}   所有奖项   
 */
var percjcon=[];
for(var i=0;i<cjper.length;i++){
  peic(cjper[i],i);
};
function peic(len,ind){
  for(var i=0;i<len;i++){
    percjcon.push(cjcon[ind]);
  }; 
};
var sjmes = document.getElementById("sjmes");
var numrandom=Math.floor(Math.random()*percjcon.length);
sjmes.innerHTML=percjcon[numrandom];
 
var opacityb=0.5;//透明百分比,参考值,什么程度出现提示
var backcolorb="#ffaaaa";
var numl=200*80;//总像素个数
var nump;//出现backcolorb的个数
var opacitya;//透明百分比实际值
 
var canvas = document.getElementById("canvas"); //获取canvas  
var context = canvas.getContext('2d'); //canvas追加2d画图
var flag = 0; //标志,判断是按下后移动还是未按下移动 重要
var penwidth=20; //画笔宽度
context.fillStyle="#faa"; //填充的颜色
context.fillRect(0,0,200,80); //填充颜色 x y坐标 宽 高
 
canvas.addEventListener('mousemove', onMouseMove, false); //鼠标移动事件 
canvas.addEventListener('mousedown', onMouseDown, false); //鼠标按下事件 
canvas.addEventListener('mouseup', onMouseUp, false); //鼠标抬起事件 
var movex=-1;
var movey=-1;
var imgData;//imagedada容器
var rgbabox=[];//存放读取后的rgba数据;
function onMouseMove(evt) {
  if (flag == 1) { 
    movex=evt.layerX;
    movey=evt.layerY;    
    context.fillStyle="#FF0000";
    context.beginPath();
    context.globalCompositeOperation="destination-out";
    context.arc(movex,movey,penwidth,0,Math.PI*2,true); //Math.PI*2是JS计算方法,是圆    
    context.closePath();
    context.fill();
  } 
} 
function onMouseDown(evt) { 
 flag = 1; //标志按下
} 
function onMouseUp(evt) { 
  flag = 0;
  //读取像素数据
  imgData=context.getImageData(0,0,200,80);//获取当前画布数据
  //imgData.data.length 获取图片数据总长度,没4个为一组存放rgba
  for(var i=0; i<imgData.data.length;i+=4){
    var rval=imgData.data[i];
    var gval=imgData.data[i+1];
    var bval=imgData.data[i+2];
    var aval=imgData.data[i+3];
    var rgbaval=rval+"-"+gval+"-"+bval+"-"+aval;
    rgbabox.push(rgbaval);
  }
  //end
  for(var j=0;j<rgbabox.length;j++){
    //alert(rgbabox[j].split("-")[0])
    rgbabox[j]='#'+rgbToHex(rgbabox[j].split("-")[0],rgbabox[j].split("-")[1],rgbabox[j].split("-")[2]);    
  }
  nump=countSubstr(rgbabox.join(","),backcolorb,true);
  opacitya=(numl-nump)/numl;
  if(opacitya>opacityb){
    alert("恭喜你获得"+percjcon[numrandom])
  }else{}
 
} 
function rgbToHex(r, g, b) { return ((r << 16) | (g << 8) | b).toString(16); }//rgb转为16进制 #xxx形式
function countSubstr(str,substr,isIgnore){//计算字符串出现子字符串的个数
  var count;
  var reg="";
  if(isIgnore==true){
  reg="/"+substr+"/gi"; 
  }else{
  reg="/"+substr+"/g";
  }
  reg=eval(reg);
  if(str.match(reg)==null){
  count=0;
  }else{
  count=str.match(reg).length;
  }
  return count;
}
//end
</script>
</html>
Copy after login

The above is the entire content of this article, I hope you all like it.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Learn the canvas framework and explain the commonly used canvas framework in detail Learn the canvas framework and explain the commonly used canvas framework in detail Jan 17, 2024 am 11:03 AM

Explore the Canvas framework: To understand what are the commonly used Canvas frameworks, specific code examples are required. Introduction: Canvas is a drawing API provided in HTML5, through which we can achieve rich graphics and animation effects. In order to improve the efficiency and convenience of drawing, many developers have developed different Canvas frameworks. This article will introduce some commonly used Canvas frameworks and provide specific code examples to help readers gain a deeper understanding of how to use these frameworks. 1. EaselJS framework Ea

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

Explore the powerful role and application of canvas in game development Explore the powerful role and application of canvas in game development Jan 17, 2024 am 11:00 AM

Understand the power and application of canvas in game development Overview: With the rapid development of Internet technology, web games are becoming more and more popular among players. As an important part of web game development, canvas technology has gradually emerged in game development, showing its powerful power and application. This article will introduce the potential of canvas in game development and demonstrate its application through specific code examples. 1. Introduction to canvas technology Canvas is a new element in HTML5, which allows us to use

Where to write canvas code Where to write canvas code Dec 20, 2023 pm 03:17 PM

Canvas code can be written inside the <body> tag of an HTML file, usually as part of the HTML document. The core of the Canvas code is to obtain and operate the context of the Canvas element. The reference to the Canvas element is obtained through document.getElementById('myCanvas') , and then use getContext('2d') to get the 2D drawing context.

See all articles