gpt4 book ai didi

javascript - 鼠标悬停时重绘 Canvas

转载 作者:行者123 更新时间:2023-11-27 22:28:37 26 4
gpt4 key购买 nike

我已经提出了一个关于我在这里创建的 Canvas 的问题,但有一个不同的问题: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“覆盖” Canvas 。但不幸的是,它只给我一个 flickr 效果......

编辑

我刚刚意识到,当初始半径大于悬停半径时,鼠标悬停/移出有效。很奇怪...

最佳答案

每次 drawDday 调用都会重新加载图像。这将导致闪烁效果。尝试加载一次图像并重新使用 imageObj 引用来绘制到 Canvas 。

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/

关于javascript - 鼠标悬停时重绘 Canvas ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20613907/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com