使用Canvas动画来制作一个滑动遮罩效果

话不多说,先上源码
代码之后是分析
js

var speed = 0.5
    var img1 = {
        w: 150,
        h: 30,
        x: 0,
        y: 0
    }

    function fun() {
        console.log(1) //检测是否运行动画
        var ctx = document.getElementById("cav").getContext("2d"); //获取到画笔
        var img = new Image() //新建作为底片的图片
        img.src = "20190513135530.png" //可以传参
        ctx.clearRect
        ctx.save()
        img.onload = function() {
            ctx.drawImage(img, 50, 50) //三个值都传参  ,XY坐标
            ctx.globalCompositeOperation = "destination-in"
            ctx.fillStyle = "red"
            ctx.fillRect(img1.x += 1 * speed, img1.y, img1.w -= 1 * speed, img1.h) //遮罩位置,速度,可以传参
            ctx.fill()
            ctx.stroke();
            ctx.restore()
        }
        if (img1.w == 0) {

        } else {
            requestAnimationFrame(fun)

        }
    }

    requestAnimationFrame(fun)

html

<body>
    <canvas id="cav" width="500" height="500">
       请换一个浏览器
   </canvas>
    <img src="20190513135530.png" alt="">
</body>

首先!!!
使用画笔工具的一项属性 globalCompositeOperation
用来进行设置两张图像重叠的样式,具体效果请戳
转载自 https://www.cnblogs.com/hzj680539/p/5068487.html
这里我们使用destination-in属性进行绘制

首先!

我们使用一张图片当做底片,请自行设置

img.src = "20190513135530.png"

在img.onolad中进行接下来的操作

img1中放着的是我们后画上去的矩形,通过 globalCompositeOperation=“destination-in”
的效果来进行, 原图只显示与后画上去的矩形重叠的部分

没了
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值