[转载]刮刮奖效果的简单实现 – ms_config – 博客园.
无意中看到个刮刮奖的效果,觉得很有意思.就想自己也做一个,怎样用html5及JavaScript实现呢,回忆以前
做报表的时候,用过html5 canvas元素.心里就有思路了.
惯例先用关键字在网上搜索了下,发现一些例子,已经做得很不错了,完全可以拿来主义.嘿…
自己简单改了下,就发布在runjs上去了.
源码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>eraser effect</title> </head> <body> <div id="canvas"></div> </body> </html>
js
(function() { // Creates a new canvas element and appends it as a child // to the parent element, and returns the reference to // the newly created canvas elemen function createCanvas(parent, width, height) { var canvas = {}; canvas.node = document.createElement('canvas'); canvas.context = canvas.node.getContext('2d'); canvas.node.width = width || 100; canvas.node.height = height || 100; parent.appendChild(canvas.node); return canvas; } function init(container, width, height, fillColor) { var canvas = createCanvas(container, width, height); var ctx = canvas.context; // define a custom fillCircle method ctx.fillCircle = function(x, y, radius, fillColor) { this.fillStyle = fillColor; this.beginPath(); this.moveTo(x, y); this.arc(x, y, radius, 0, Math.PI * 2, false); this.fill(); }; ctx.clearTo = function(fillColor) { ctx.fillStyle = fillColor; ctx.fillRect(0, 0, width, height); }; ctx.clearTo(fillColor || "#ddd"); // bind mouse events canvas.node.onmousemove = function(e) { if (!canvas.isDrawing) { return; } var x = e.pageX - this.offsetLeft; var y = e.pageY - this.offsetTop; var radius = 10; // or whatever var fillColor = '#ff0000'; ctx.globalCompositeOperation = 'destination-out'; ctx.fillCircle(x, y, radius, fillColor); }; canvas.node.onmousedown = function(e) { canvas.isDrawing = true; }; canvas.node.onmouseup = function(e) { canvas.isDrawing = false; }; } var container = document.getElementById('canvas'); init(container, 531, 438, '#ddd'); })(); #canvas { background:url(http://www.topscratchcards.com/images/games/888ladies/scratchcard-winning-ticket.jpg); width: 531px; height: 438px; }