HTML5的 canvas完成刮刮卡功能

12 篇文章 0 订阅
8 篇文章 0 订阅
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<style>
.ggk {
    width: 200px;
    height: 100px;
    border: 1px solid #000;
    margin: 0 auto;
    color: red;
    position: relative;

}

.ggk span {
    position: absolute;
    width: 100%;
    height: 100%;
    text-align: center;
    line-height: 100px;
    font-size: 50px;
    user-select: none;
}

canvas {
    position: absolute;
    left: 0;
    top: 0;
}

</style>
<div class="ggk">
    <span></span>
    <canvas id="canvas">
        你的浏览器版本太低, 请升级浏览器.最好使用Chrome, IE太垃圾了
    </canvas>
</div>

<script>
var canvas = document.querySelector("#canvas");
draw();

function draw(){
    if (!canvas.getContext) return;
    canvas.width = 200;
    canvas.height = 100;
    var ctx = canvas.getContext("2d");
    productResult();
    drawCover(ctx);
    scratch(ctx);
}

function scratch(ctx){
    /*绘制线段来实现*/
    canvas.onmousedown = function (e){
        var downX = e.offsetX;
        var downY = e.offsetY;
        ctx.beginPath();
        ctx.globalCompositeOperation = "destination-out";
        ctx.lineWidth = 10;
        ctx.lineCap = "round";
        ctx.moveTo(downX, downY);
        canvas.onmousemove = function (e){
            var x = e.offsetX;
            var y = e.offsetY;
            ctx.lineTo(x, y);
            ctx.stroke();
        }
    }
    /*在路径中绘制圆弧来实现*/
    /*canvas.onmousedown = function (e){
        canvas.onmousemove = function (e){
            var x = e.offsetX;
            var y = e.offsetY;
            ctx.beginPath();
            ctx.arc(x, y, 8, 0, Math.PI * 2);
            ctx.globalCompositeOperation = "destination-out";
            ctx.fill();
            ctx.closePath();
        }
    }*/
    canvas.onmouseup = function (){
        canvas.onmousemove = null;
    }
}

/*生成中奖信息*/
function productResult(){
    var span = document.querySelector(".ggk span");
    var arr = ["100元", "200元", "300元", "400元", "谢谢", "谢谢", "谢谢", "谢谢"];
    var text = arr[randomInt(0, arr.length - 1)];
    span.innerHTML = text;
}

/*绘制覆盖层*/
function drawCover(ctx){
    ctx.save();
    ctx.fillStyle = "rgb(100,100,100)";
    ctx.fillRect(0, 0, 200, 100);
    ctx.restore();
}

/**
 作者:李振超      2018年05月10 09:22:37
 返回随机的 [from, to] 之间的整数(包括from,也包括to)
 */
function randomInt(from, to){
    return parseInt(Math.random() * (to - from + 1) + from);
}

</script>
</body>
</html>

  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值