h5canvas实现刮刮乐效果代码


本文摘自PHP中文网,作者零下一度,侵删。

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

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

canvas实现刮刮乐0

代码如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

<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('canvas')[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>

【相关推荐】

1. 特别推荐:“php程序员工具箱”V0.1版本下载

2. 免费h5在线视频教程

3. php.cn原创html5视频教程

以上就是h5canvas实现刮刮乐效果代码的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

使用canvas轻松实现黑客帝国炫酷代码雨!!

如何使用html5 canvas绘制文字

h5 canvas实现粒子时钟的详细方法

h5 canvas api中drawimage(图像进行缩放或裁剪)的使用实例

横向不间断滚动效果代码

使用canvas设计出一个简易的画板

canvas贝塞尔公式推导与物体跟随复杂曲线轨迹运动

利用html5中的canvas绘制笑脸的代码

详细介绍7款炫酷的html5 canvas动画特效

canvas实现旋转风车的绘制

更多相关阅读请进入《canvas》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...