canvas 刮刮乐效果

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>audio</title>
    <style type="text/css">
        canvas {
            /* canvas 默认宽高 300*150 
        css设置的宽高,只能设置canvas对象在页面显示的大小。
        并不能增加画布内部的像素数
    */
            margin: 0 auto;
            position: absolute;
            left: 0;
            top: 0;
        }

        div {
            width: 500px;
            height: 500px;
            background: url("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1566357763988&di=bcf0827252aa1c8bab453020de5ec75b&imgtype=0&src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0128475543010c0000019ae92b7605.jpg%401280w_1l_2o_100sh.jpg") no-repeat;
            background-size: 100% 100%;
            position: relative;
        }

        div p {
            font-size: 50px;
            line-height: 500px;
            text-align: center;
            width: 100%;
        }
    </style>

</head>

<body>
    <!-- 在标签上添加canvas像素值 -->
    <div>
        <p>一等奖</p>
        <canvas id="canvasId" width="500" height="500">您的浏览器不支持canvas!</canvas>
    </div>
    <script type="text/javascript">
        var cv = document.getElementById("canvasId"),
            p = document.getElementsByTagName("p")[0],
            ct = cv.getContext("2d");

        p.innerText = "一等奖";

        //绘制背景色
        ct.fillStyle = "#aaa";
        ct.fillRect(0, 0, 500, 500);
        //设置绘制状态
        ct.lineCap = "round";   //设置线条两端为圆弧
        ct.lineWidth = 60;  //画笔宽度
        /*设置新绘制清除新绘制内容和原内容的重叠区域*/
        ct.globalCompositeOperation = "destination-out";

        //绘制曲线
        var flag = false,
            lx, ly;

        cv.onmousedown = function (e) {
            flag = true;
            lx = e.offsetX;
            ly = e.offsetY;
        }
        cv.onmousemove = function (e) {
            if (flag) {
                ct.beginPath();
                ct.moveTo(lx, ly);
                ct.lineTo(e.offsetX, e.offsetY);
                ct.stroke();
                ct.closePath();
                //更新坐标
                lx = e.offsetX;
                ly = e.offsetY;
            }
        }

        cv.onmouseup = function (e) {
            flag = false;
        }
    </script>

</html>
发布了121 篇原创文章 · 获赞 151 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/feifanzhuli/article/details/99933522