话不多说,先上源码
代码之后是分析
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”
的效果来进行, 原图只显示与后画上去的矩形重叠的部分
没了