體驗效果:https://hovertree.com/html5/32.htm(請使用支援 HTML5 的瀏覽器,按住鼠標拖曳)
專案裡遇到一個類似刮刮卡的需求:在行動裝置上把上層圖片刮開,露出下面的內容。聽起來簡單,實作過程卻踩了不少坑,本文把整個思路與優化過程記錄下來。

擦除直覺上就是「清除像素」,Canvas 對應的 API 是 clearRect()。但 clearRect 清的是矩形,而多數人習慣的橡皮擦是圓形,於是引入剪輯區域 clip():
ctx.save();
ctx.beginPath();
ctx.arc(x2, y2, a, 0, 2 * Math.PI);
ctx.clip();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
先畫出圓形路徑並設為剪輯區域,再清除像素,圓形擦除就完成了。注意務必先 save()、擦完 restore(),否則後續所有繪圖都會被限制在這個剪輯區域裡。
最直白的做法是每次 mousemove 都在當前座標擦一個圓。慢速拖曳沒問題,但速度一快,圓與圓之間就出現空隙:

解法是把相鄰兩點連起來。畫線可以用 lineTo,但剪輯區域要求閉合路徑,單純連兩點無法圍出區域。於是改為計算兩圓之間的矩形四個端點:

var asin = a * Math.sin(Math.atan((y2 - y1) / (x2 - x1)));
var acos = a * Math.cos(Math.atan((y2 - y1) / (x2 - x1)));
var x3 = x1 + asin; var y3 = y1 - acos;
var x4 = x1 - asin; var y4 = y1 + acos;
var x5 = x2 + asin; var y5 = y2 - acos;
var x6 = x2 - asin; var y6 = y2 + acos;
已知兩端點座標與線寬,用三角函數就能推出矩形四個角。剪輯區域於是變成「圓 + 矩形」的組合:
var hastouch = "ontouchstart" in window ? true : false; // 是否為行動裝置
var tapstart = hastouch ? "touchstart" : "mousedown";
var tapmove = hastouch ? "touchmove" : "mousemove";
var tapend = hastouch ? "touchend" : "mouseup";
canvas.addEventListener(tapstart, function (e) {
e.preventDefault();
x1 = hastouch ? e.targetTouches[0].pageX : e.clientX - canvas.offsetLeft;
y1 = hastouch ? e.targetTouches[0].pageY : e.clientY - canvas.offsetTop;
// 第一次按下先擦一個圓,並記錄起始座標
ctx.save();
ctx.beginPath();
ctx.arc(x1, y1, a, 0, 2 * Math.PI);
ctx.clip();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
canvas.addEventListener(tapmove, tapmoveHandler);
canvas.addEventListener(tapend, function () {
canvas.removeEventListener(tapmove, tapmoveHandler);
});
});
function tapmoveHandler(e) {
e.preventDefault();
x2 = hastouch ? e.targetTouches[0].pageX : e.clientX - canvas.offsetLeft;
y2 = hastouch ? e.targetTouches[0].pageY : e.clientY - canvas.offsetTop;
var asin = a * Math.sin(Math.atan((y2 - y1) / (x2 - x1)));
var acos = a * Math.cos(Math.atan((y2 - y1) / (x2 - x1)));
var x3 = x1 + asin, y3 = y1 - acos;
var x4 = x1 - asin, y4 = y1 + acos;
var x5 = x2 + asin, y5 = y2 - acos;
var x6 = x2 - asin, y6 = y2 + acos;
// 在終點補一個圓,確保轉向處也連貫
ctx.save();
ctx.beginPath();
ctx.arc(x2, y2, a, 0, 2 * Math.PI);
ctx.clip();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
// 清除矩形區域
ctx.save();
ctx.beginPath();
ctx.moveTo(x3, y3);
ctx.lineTo(x5, y5);
ctx.lineTo(x6, y6);
ctx.lineTo(x4, y4);
ctx.closePath();
ctx.clip();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.restore();
x1 = x2;
y1 = y2;
}
刮刮卡的關鍵回饋是「擦到一定比例就自動揭曉」。做法是用 getImageData 取出像素,統計 alpha 不為 0 的數量:
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var dd = 0;
for (var x = 0; x < imgData.width; x += 1) {
for (var y = 0; y < imgData.height; y += 1) {
var i = (y * imgData.width + x) * 4;
if (imgData.data[i + 3] > 0) { dd++; }
}
}
// 剩餘不透明像素低於 40%,代表已擦開六成以上
if (dd / (imgData.width * imgData.height) < 0.4) {
canvas.className = "noOp";
}
這段程式碼放在 mouseup 裡,但兩個問題隨之而來:計算量不小,使用者狂點會瘋狂觸發迴圈導致卡頓。兩個優化手段:
① 加 timeout 去抖——每次點擊先清掉計時器,只有停下來才真正計算。
② 抽樣檢查——不必逐像素掃,每隔 30 個像素取一次樣即可:
timeout = setTimeout(function () {
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var dd = 0;
for (var x = 0; x < imgData.width; x += 30) {
for (var y = 0; y < imgData.height; y += 30) {
var i = (y * imgData.width + x) * 4;
if (imgData.data[i + 3] > 0) { dd++; }
}
}
if (dd / (imgData.width * imgData.height / 900) < 0.4) {
canvas.className = "noOp";
}
}, 100);
改完之後在 Android 真機測試,還是卡。真正的轉機是發現繪圖環境的 globalCompositeOperation 屬性。預設值 source-over 是「疊加繪製」,而 destination-out 的行為是:在既有像素上繪圖時,被畫到的區域會變成透明。

這意味著完全不需要 clip,也不需要 sin / cos 算矩形——只要畫一條粗線就夠了。計算量大幅下降,繪圖 API 呼叫次數也少了:
function tapClip() {
var hastouch = "ontouchstart" in window ? true : false,
tapstart = hastouch ? "touchstart" : "mousedown",
tapmove = hastouch ? "touchmove" : "mousemove",
tapend = hastouch ? "touchend" : "mouseup";
ctx.lineCap = "round"; // 線條兩端圓弧
ctx.lineJoin = "round"; // 轉折處圓弧
ctx.lineWidth = a * 2;
ctx.globalCompositeOperation = "destination-out"; // 關鍵
canvas.addEventListener(tapstart, function (e) {
clearTimeout(timeout);
e.preventDefault();
x1 = hastouch ? e.targetTouches[0].pageX : e.clientX - canvas.offsetLeft;
y1 = hastouch ? e.targetTouches[0].pageY : e.clientY - canvas.offsetTop;
ctx.save();
ctx.beginPath();
ctx.arc(x1, y1, 1, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
canvas.addEventListener(tapmove, tapmoveHandler);
canvas.addEventListener(tapend, function () {
canvas.removeEventListener(tapmove, tapmoveHandler);
timeout = setTimeout(function () {
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var dd = 0;
for (var x = 0; x < imgData.width; x += jiange) {
for (var y = 0; y < imgData.height; y += jiange) {
var i = (y * imgData.width + x) * 4;
if (imgData.data[i + 3] > 0) { dd++; }
}
}
if (dd / (imgData.width * imgData.height / (jiange * jiange)) < 0.4) {
canvas.className = "noOp";
}
}, tomatos);
});
function tapmoveHandler(e) {
clearTimeout(timeout);
e.preventDefault();
x2 = hastouch ? e.targetTouches[0].pageX : e.clientX - canvas.offsetLeft;
y2 = hastouch ? e.targetTouches[0].pageY : e.clientY - canvas.offsetTop;
ctx.save();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
ctx.restore();
x1 = x2;
y1 = y2;
}
});
}
擦除部分的程式碼短到幾乎等同一個普通的畫圖功能:設定好線條樣式,把 globalCompositeOperation 切成 destination-out,之後畫的一切就都變成擦除。改完在 Android 真機上實測,流暢度明顯提升,達到了「至少能玩」的要求。
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0;">
<title>HTML5橡皮擦</title>
<style type="text/css">
body { margin: 0; padding: 0; }
.box {
position: absolute;
left: 0; top: 0; bottom: 0; right: 0;
background: url("keleyi.jpg") no-repeat;
background-size: 100% 100%;
backface-visibility: hidden;
overflow: hidden;
}
#cas_keleyi_com {
width: 100%;
height: 100%;
opacity: 1;
-webkit-transition: opacity .5s;
-ms-transition: opacity .5s;
-moz-transition: opacity .5s;
}
/* 擦開後淡出,露出底圖 */
.noOp { opacity: 0 !important; }
</style>
</head>
<body>
<div class="box" id="bb">
<canvas id="cas_keleyi_com"></canvas>
</div>
<script type="text/javascript" charset="utf-8">
var canvas = document.getElementById("cas_ke" + "leyi_com"),
ctx = canvas.getContext("2d");
var x1, y1, a = 30, timeout, tomatos = 100, jiange = 30;
canvas.width = document.getElementById("bb").clientWidth;
canvas.height = document.getElementById("bb").clientHeight;
var img = new Image();
img.src = "hovertree.jpg";
img.onload = function () {
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
tapClip();
};
function tapClip() {
var hastouch = "ontouchstart" in window ? true : false,
tapstart = hastouch ? "touchstart" : "mousedown",
tapmove = hastouch ? "touchmove" : "mousemove",
tapend = hastouch ? "touchend" : "mouseup";
ctx.lineCap = "round";
ctx.lineJoin = "round";
ctx.lineWidth = a * 2;
ctx.globalCompositeOperation = "destination-out";
canvas.addEventListener(tapstart, function (e) {
clearTimeout(timeout);
e.preventDefault();
x1 = hastouch ? e.targetTouches[0].pageX : e.clientX - canvas.offsetLeft;
y1 = hastouch ? e.targetTouches[0].pageY : e.clientY - canvas.offsetTop;
ctx.save();
ctx.beginPath();
ctx.arc(x1, y1, 1, 0, 2 * Math.PI);
ctx.fill();
ctx.restore();
canvas.addEventListener(tapmove, tapmoveHandler);
canvas.addEventListener(tapend, function () {
canvas.removeEventListener(tapmove, tapmoveHandler);
timeout = setTimeout(function () {
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
var dd = 0;
for (var x = 0; x < imgData.width; x += jiange) {
for (var y = 0; y < imgData.height; y += jiange) {
var i = (y * imgData.width + x) * 4;
if (imgData.data[i + 3] > 0) { dd++; }
}
}
if (dd / (imgData.width * imgData.height / (jiange * jiange)) < 0.4) {
canvas.className = "noOp";
}
}, tomatos);
});
function tapmoveHandler(e) {
clearTimeout(timeout);
e.preventDefault();
x2 = hastouch ? e.targetTouches[0].pageX : e.clientX - canvas.offsetLeft;
y2 = hastouch ? e.targetTouches[0].pageY : e.clientY - canvas.offsetTop;
ctx.save();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
ctx.restore();
x1 = x2;
y1 = y2;
}
});
}
</script>
</body>
</html>
這次優化最大的收穫:遇到效能問題時,與其想方設法簡化既有算法,不如先確認自己是不是用錯了 API。針對性地選對 globalCompositeOperation,比任何微調都有效。