Home > Web Front-end > H5 Tutorial > body text

Canvas implements scratch-off

高洛峰
Release: 2016-10-12 09:52:30
Original
1657 people have browsed it

Canvas implements scratch-off

canvas实现刮刮乐主要是要注意两个地方:第一个是将绘制的图形设置成背景图片(用到toDataURL属性),这样在擦覆盖层的时候才不会丢失绘制的图案,

第二个是设置在绘制插图的时候,设置透明透明(用到globalCompositeOperation属性)

代码如下:

<script>
    var arr=[
        {name:"iphone7 磨砂黑",color:"rgba(255,255,0,1)"},
        {name:"iphone7 磨砂黑",color:"rgba(0,255,0,.9)"},
        {name:"iphone7 磨砂黑",color:"rgba(10,255,255,1)"},
        {name:"iphone7 磨砂黑",color:"rgba(10,255,100,1)"}
    ]
    var r=Math.random();
    var rIndex= Math.floor(r*arr.length);
    var rPrice=arr[rIndex];
    var cv=document.getElementsByTagName(&#39;canvas&#39;)[0];
    var isDown=false;
    cv.height=400;
    cv.width=600;
    var ctx=cv.getContext("2d");
    function toAngle(radian){
        return radian/Math.PI*180;
    }
    function toRadian(angle){
        return angle/180*Math.PI;
    }
    ctx.textAlign="center";
    ctx.textBaseline="middle";
    ctx.font="30px consolas";
    ctx.fillStyle=rPrice.color;
    ctx.fillText(rPrice.name,cv.width/2,cv.height/2);

    var dataURL=cv.toDataURL("image/jpg",1);
    cv.style.background="url("+dataURL+")";

    //覆盖层
    ctx.beginPath();
    ctx.fillStyle="#eee";
    ctx.fillRect(0,0,cv.width,cv.height);

    cv.addEventListener("mousedown",function(){
        isDown=true;
    })
    cv.addEventListener("mouseup",function(){
        isDown=false;
        ctx.globalCompositeOperation="source-out"
    })
    cv.addEventListener("mousemove",function(e){
        if (isDown){
            ctx.globalCompositeOperation="destination-out";
            ctx.beginPath();
            var posObj=cv.getBoundingClientRect();

            var left=posObj.left;
            var top=posObj.top;

            var x= e.clientX-left;
            var y= e.clientY-top;

            ctx.arc(x,y,50,0,Math.PI*2);
            ctx.fill();
        }
    })
</script>
Copy after login


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!