canvas make a scratch card

Finishing ideas:

1. Select a background image, prizes content on pictures

2. prize drawing color text area covered by the district

3. eliminate color drawing area, making it visible text background image.

code show as below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>scratch_card</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <Meta name = "description" content = "scratch effect to achieve a" />
    <meta name="keywords" content="canvas, js, dom, 动效" />
    <meta name="author" content="丰林, jayfeng",[email protected] />
    <meta name="copyright" content="www.fenglin.com" />
    <meta name="robots" content="all" />
    <style>
        .img{
            margin:0 auto;
            width:640px;
            position:relative;
        }
        #canvas{
            position:absolute;
            left:66px;
            top:360px;
        }
    </style>
</head>
<body>
    <div class="img">
        <img src="timg.jpg" />
        <canvas width="510" height="248" id="canvas"></canvas>
    </div>

    <script>
        var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        ctx.fillStyle = "#000";
        ctx.fillRect(0,0,510,248);
        // add mouse down
        canvas.onmousedown = function(){
            // get the mouse position
            canvas.onmousemove = function(ev){
                //oEvent.clientX is the distance the mouse to the left border of the visible area
                // offsetLeft: get in the left distance themselves left outside the borders of the border and offsetParent
                var bx = ev.clientX - canvas.offsetLeft - canvas.parentNode.offsetLeft;
                var by = ev.clientY - canvas.offsetTop - canvas.parentNode.offsetTop;
                // keep the target in the source image does not overlap. Other portions have become transparent.
                ctx.globalCompositeOperation = "destination-out";
                // Circle
                ctx.beginPath ();
                ctx.arc(bx,by,20,0,2*Math.PI,false);
                ctx.fillStyle = "#fff";
                ctx.fill();
                ctx.closePath();
            }
        }
        canvas.onmouseup = function(){
            canvas.onmousemove = null;
        }
    </script>
</body>
</html>

Guess you like

Origin www.cnblogs.com/jayfeng/p/12103775.html