我已经在这里创建了一个关于我在这里创建的画布的问题,但在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效果......
修改
我刚刚意识到,当初始半径大于悬停半径时,鼠标悬停/输出有效。很奇怪......
答案 0 :(得分: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()。这使得画布子系统知道每次调用该函数时它都是一条新路径。否则新路径将与旧路径结合。
编辑:鼠标移动时具有简单的动画效果:http://jsfiddle.net/CvuyN/2/