2013-12-16 308 views
2

重绘的画布,我已经开了一个问题,关于这个画布上我创建这里,但与一个不同的问题:Make rectangle overlay image with canvas鼠标悬停

我想知道是否有可能进行动画鼠标悬停拱半径? 这里就是我:jsfiddle

// Options 
var maxImageWidth = 250, 
    maxImageHeight = 196, 
    radius = 50; 

var canvas = $('#ddayCanvas'), 
    canvasWidth = canvas.width(), 
    canvasHeight = canvas.height(), 
    sectorColor = $('.product-box').css('background-color'), 
    context = canvas[0].getContext('2d'), 
    imageSrc = canvas.data('image'); 


function drawDday (option) { 

    context.clearRect(0, 0, canvasWidth, canvasHeight);   

    if (typeof option != 'undefined'){ 
     radius = option; 
    }  

    var imageObj = new Image(); 
    imageObj.onload = function() { 

     var imageWidth = imageObj.width, 
      imageHeight = imageObj.height; 

     if (imageWidth > maxImageWidth){ 
      imageHeight = imageHeight - (imageWidth - maxImageWidth); 
      imageWidth = maxImageWidth; 
     } 

     if (imageHeight > maxImageHeight) { 
      imageWidth = imageWidth - (imageHeight - maxImageHeight); 
      imageHeight = maxImageHeight; 
     } 

     context.drawImage(imageObj, Math.ceil((canvasWidth - imageWidth)/2), Math.ceil((canvasHeight - imageHeight)/2), imageWidth, imageHeight); 

     // Why does this rectangle not overlay the previous image? 
     context.fillStyle = sectorColor; 
     context.rect(0, 0, canvasWidth, canvasHeight); 
     context.arc(canvasWidth/2, canvasHeight/2, radius, 0, Math.PI*2, true); 
     context.fill(); 
    }; 


    imageObj.src = imageSrc; 

} 

drawDday(); 

canvas.hover(function(){ 
    drawDday(90); 
}, function(){ 
    drawDday(20); 
}); 

我试着打电话与悬停半径参数的功能,和“覆盖”与clearRect画布。但不幸的是它只是给了我一个Flickr的效果......

编辑

我只是意识到鼠标悬停/输出工作时的初始半径更大然后悬停半径。非常奇怪...

回答

3

您正在重新加载每个drawDday调用的图像。这会导致闪烁效应。尝试加载一次图像并重新使用imageObj引用来绘制到画布。

imageObj被加载一次并在每个drawDday调用中重用。请参阅:http://jsfiddle.net/Vr5k9/4/

function drawDday (radius) { 
    context.clearRect(0, 0, canvasWidth, canvasHeight); 
    context.drawImage(imageObj, Math.ceil((canvasWidth - imageWidth)/2), Math.ceil((canvasHeight - imageHeight)/2), imageWidth, imageHeight); 
    context.fillStyle = sectorColor; 
    context.beginPath(); 
    context.rect(0, 0, canvasWidth, canvasHeight); 
    context.arc(canvasWidth/2, canvasHeight/2, radius, 0, Math.PI*2, true); 
    context.closePath(); 
    context.fill(); 
} 

编辑:请注意context.beginPath()和context.closePath()。这让canvas子系统知道每次函数被调用时它都是一个新的路径。否则,新的路径将与旧的路径结合在一起。

编辑:随着移动鼠标简单的动画效果:http://jsfiddle.net/CvuyN/2/

+0

这是伟大的感谢,但也有一个方法,使动画(可能与jQuery的动画'()')这个悬停效果? – enyce12

+0

这很酷,但我不需要永久性的用户交互,就需要鼠标悬停的效果。 – enyce12

+0

您的意思是这个动画应该只发生在最初的鼠标悬停事件上,然后不会再发生? – Synthetx