5

前端Js结合canvas实现刮刮乐效果

 1 year ago
source link: https://www.fly63.com/article/detial/12209
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

刮刮乐效果的实现思路如下:

  • 先在视图上画真正要显示的图像
  • 在第一步绘制的图像上面再绘制一个一样大小的纯灰色图像,彻底盖住第一步中绘制的图像
  • 随着手指在灰色图像上的滑动不断的修改灰色图像的内容。

本文实例为大家分享了JavaScript canvas实现刮刮乐效果的具体代码,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

Js实现原理

在网页上实现刮刮乐效果,其实很多人都知道原理非常简单,用一个 canvas 盖在结果内容上层,然后给 canvas 绑定 ontouchmove 事件,触发后使用 context.clearRect(x, y, width, height);清除 canvas 上的点击位置中 x, y 位置的一个对应矩形即可实现刮刮乐效果。

html代码:

<div class="ggk">
<span id="span">200元</span>
<canvas id="canvas"></canvas>
</div>

css代码:

.ggk {
width: 200px;
height: 100px;
border: 1px solid #000;
margin: 20px auto;
color: red;
position: relative;
}
.ggk span {
position: absolute;
width: 100%;
height: 100%;
text-align: center;
font-size: 50px;
line-height: 100px;
}
#canvas {
position: absolute;
left: 0;
top: 0;
}

js代码:

var canvas = document.getElementById("canvas");
init();
function init(){
canvas.width = 200;
canvas.height = 100;
var ctx = canvas.getContext("2d");
ctx.save();
ctx.fillStyle = 'rgb(100,100,100)';
ctx.fillRect(0, 0, 200, 100);
draw(ctx);
pro();
}
function pro() {//随机内容
var span = document.getElementById("span");
var arr = ["100元", '谢谢惠顾', '200元', '谢谢惠顾', '谢谢惠顾', '谢谢惠顾', '500万', '谢谢惠顾'];
var num = Math.floor(Math.random() * (arr.length - 1));
var text = arr[num];
span.innerHTML = text;
}
function draw(ctx) {
canvas.onmousedown = function(e) {// 移动事件
var downX = e.offsetX;
var downY = e.offsetY;
ctx.beginPath();
ctx.lineWidth = 10;
ctx.moveTo(downX, downY);
canvas.onmousemove = function(e) {
var x = e.offsetX;
var y = e.offsetY;
ctx.clearRect(x, y, 20, 20);
ctx.stroke();
}
}
canvas.onmouseup = function() {//鼠标弹起事件
canvas.onmousemove = null
}
}

其中用到canvas的一些api如下:

  • save(); 保存当前环境的状态。
  • beginPath(); 开始一条路径,或重置当前的路径
  • fillStyle='rgb(100,100,100)'; 用来填充颜色,或者提供渐变
  • fillRect(0, 0, 200, 100); 方法绘制"已填充"的矩形。默认的填充颜色
  • moveTo(downX, downY); 把路径移动到画布中的指定点,不创建线条
  • clearRect(x, y, 20, 20); 在给定的矩形内清除指定的像素。

链接: https://www.fly63.com/article/detial/12209


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK