用canvas+mouseArea實現的刮刮卡效果。canvas
表層是一層色彩,用手指劃開,可看到下面的文字
Lisence: MIT, 請保留本文檔說明
Author: surfsky.cnblogs.com 2015-02spa
【先看效果】.net
【下載】rest
http://download.csdn.net/detail/surfsky/8445011code
【核心代碼】blog
1 Canvas { 2 id: canvas 3 anchors.fill: parent 4 5 // 6 property bool isFirstPaint : true; 7 property point lastPt; 8 9 // 10 onPaint: { 11 var ctx = getContext('2d'); 12 if (isFirstPaint){ 13 // 首次繪製刮刮層圖案 14 ctx.fillStyle = root.maskColor; 15 ctx.fillRect(0, 0, width, height); 16 isFirstPaint = false; 17 } 18 else{ 19 // 去除鼠標位置的圖案 20 clearRound(ctx, lastPt, 20); 21 lastPt = Qt.point(area.mouseX, area.mouseY); 22 } 23 } 24 25 // 清除圓形區域 26 function clearRound(ctx, p, r) 27 { 28 ctx.save(); 29 ctx.globalCompositeOperation = 'destination-out'; 30 ctx.beginPath(); 31 ctx.arc(p.x, p.y, r, 0, 2*Math.PI, false); 32 ctx.fill(); 33 ctx.restore(); 34 } 35 36 // 記錄下最後的鼠標點,並請求canvas重繪 37 MouseArea { 38 id: area 39 anchors.fill: parent 40 onPressed: {canvas.lastPt = Qt.point(mouseX, mouseY);} 41 onPositionChanged: {canvas.requestPaint();} 42 } 43 }