2014-02-14 56 views
1

我正在查看this example油漆效果onmouseover(jQuery)

我想知道是否可以跟蹤鼠標光標,以便一旦將鼠標懸停在圖像的一部分上,它就會保持顏色?有點像您正在繪畫或着色。是否有一個我應該尋找的特定插件,或者我該如何實現?

+2

您可以修改我寫了幾年前做同樣的事情(HTTP代碼://www.catchmyfame。 COM/2011/06/28/A-jQuery的帆布刮開/)。只需使用一個灰度圖像和一個彩色圖像。 – j08691

+0

@ j08691謝謝。你能回答你的例子的源代碼,我會接受答案嗎? –

回答

3

這是jQuery的:

/* 
* jQuery + Canvas Scratch Off 
* @author [email protected] - http://www.catchmyfame.com 
* @version 1.0 
* @date June 28, 2011 
* @copyright (c) 2011 [email protected] (www.catchmyfame.com) 
* @license CC Attribution-NoDerivs 3.0 Unported - http://creativecommons.org/licenses/by-nc-sa/3.0/ 
*/ 
var topImage = new Image(); 
var bottomImage = new Image(); 
var coinImage = new Image(); 
bottomImage.src = "bottom-300.jpg"; 
coinImage.src = "circle.png"; 

function init() 
{ 
    var isMouseDown = false; 
    var canvasWidth = $('#canvas').width(); 
    var canvasHeight = $('#canvas').height(); 
    $('body').append('<canvas id="overlay" width="'+canvasWidth+'" height="'+canvasHeight+'" />'); // Create the coin overlay canvas 
    var overlayctx = $('canvas')[1].getContext('2d'); 
    overlayctx.drawImage(coinImage, 0,0); 


    function scratchOff(x, y) 
    { 
     mainctx.save(); 
     mainctx.beginPath(); 
     mainctx.arc(x,y,radius,0,Math.PI*2,false); // we don't fill or stroke the arc intentionally 
     mainctx.clip(); 
     mainctx.drawImage(bottomImage, 0, 0); 
     mainctx.restore(); 
    } 

    $('#overlay').mousedown(function(e){ 
      isMouseDown = true; 
      var relX = e.pageX - this.offsetLeft; 
      var relY = e.pageY - this.offsetTop; 
      scratchOff(relX, relY, true); 
    }); 
    $('#overlay').mousemove(function(e){ 
     var relX = e.pageX - this.offsetLeft; 
     var relY = e.pageY - this.offsetTop; 
     overlayctx.clearRect(0,0,canvasWidth,canvasHeight); 
     overlayctx.drawImage(coinImage, relX-radius, relY-radius); 
     if (isMouseDown) scratchOff(relX, relY, false); 
    }); 
    $('#overlay').mouseup(function(e){ 
     isMouseDown = false; 
    }); 

    var mainctx = $('canvas')[0].getContext('2d'); 
    var radius = 15; 
    topImage.onload = function(){ 
     mainctx.drawImage(topImage, 0, 0); 
    }; 
    topImage.src = "top-300.jpg"; 
} 

和HTML:

<canvas id="canvas" width="300" height="225"></canvas>