当青训营遇上码上掘金
如题,如何使用canvas的globalCompositeOperation
做一个刮刮卡形式的简陋且离谱的个人名片。首先我们来了解一下globalCompositeOperation
。
1. globalCompositeOperation
globalCompositeOperation
是绘制新形状时应用的合成操作的类型,其中 type 是用于标识要使用的合成或混合模式操作的字符串。
globalCompositeOperation = type
- type属性设定了在画新图形时采用的遮盖策略,其值是一个标识 12 种遮盖方式的字符串。
使用方法:
ctx.globalCompositeOperation = type;
12种遮盖方式不在此一一列举。
destination-out
要实现刮刮卡形式,我们需要的是destination-out
这种方式,当新图形绘制时,
现有内容保持在新图形不重叠的地方。也就是相当于新图形会“擦掉”旧图形的内容。
其次,我们再来回忆一下canvas的基本使用方法
第一步,创建一个canvas画布
<canvas id="c1" width="600" height="400"></canvas>
第二步,编写canvas的js
1. 找到画布
const c1 = document.getElementById("c1");
2. 获取画笔,上下文对象
const ctx = c1.getContext("2d");
3. 获取图片
var img = new Image();
img.src = "./img/image.png";
4. 编写方法
在加载时,使用 drawImage
方法将图片渲染到 canvas 里。
这里又要提到,drawImage
方法有三种形态。
-
drawImage(image, x, y)
其中 image 是 image 或者 canvas 对象,x 和 y 是其在目标 canvas 里的起始坐标。 -
缩放
drawImage(image, x, y, width, height)
这个方法多了 2 个参数:width 和 height,这两个参数用来控制当向 canvas 绘制时应该缩放的大小。 -
切片(裁剪)
drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
第一个参数和其它的是相同的,都是一个图像或者另一个 canvas 的引用。其它 8 个参数最好是参照右边的图解,前 4 个是定义图像源的切片位置和大小,后 4 个则是定义切片的目标显示位置和大小。
下面是我的代码:
img.onload = function () {
// drawImage的第二种
ctx.drawImage(img, 0, 0, 600, 400);
};
5. 一些关于鼠标操作的限制
当鼠标按下时才开始涂抹。
鼠标按下后,以鼠标坐标为圆心画圆,使用ctx.globalCompositeOperation = "destination-out";
来擦除
var isDraw = false;
c1.onmousedown = function () {
isDraw = true;
};
c1.onmouseup = function () {
isDraw = false;
};
c1.onmousemove = function (e) {
if (isDraw) {
var x = e.pageX;
var y = e.pageY;
ctx.globalCompositeOperation = "destination-out";
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fill();
}
};
6. 最后增加名片的趣味性(什么名片,明明只是刮刮卡)
在html中增加一个div,在js最后增加一个random,使其随机出现名片或再试一次。
<div id="ggk">不好意思,再试一次吧</div>
let random = Math.random();
if (random < 0.5) {
var ggkDiv = document.querySelector("#ggk");
ggkDiv.innerHTML = "恭喜您获得我简陋的名片一张!姓名:cen姜";
}