HTML5 Canvas实现放大镜效果示例

2020-04-25 07:24:31易采站长站整理

sgLine.xEnd = parseInt(gLine.xEnd * scale);
sgLine.yEnd = parseInt(gLine.yEnd * scale);
sgLine.color = line.color;
glassLineIndex++;
}
glassLineSize = glassLineIndex;
}

绘制放大镜中心点

绘制放大镜中心的瞄准器


function drawAnchor() {
context.beginPath();
context.lineWidth = 2;
context.fillStyle = "#fff";
context.strokeStyle = "#000";
context.arc(parseInt(centerPoint.x), parseInt(centerPoint.y), 10, 0, Math.PI * 2, false);

var radius = 15;
context.moveTo(parseInt(centerPoint.x - radius), parseInt(centerPoint.y));
context.lineTo(parseInt(centerPoint.x + radius), parseInt(centerPoint.y));
context.moveTo(parseInt(centerPoint.x), parseInt(centerPoint.y - radius));
context.lineTo(parseInt(centerPoint.x), parseInt(centerPoint.y + radius));
//context.fill();
context.stroke();
}

绘制放大镜


function drawMagnifyingGlass() {

calScaleLines();

context.save();
context.beginPath();
context.arc(centerPoint.x, centerPoint.y, originalRadius, 0, Math.PI * 2, false);
context.clip();

context.beginPath();
context.fillStyle = "#fff";
context.arc(centerPoint.x, centerPoint.y, originalRadius, 0, Math.PI * 2, false);
context.fill();

context.lineWidth = 4;
for (var i = 0; i < glassLineSize; i++) {
context.beginPath();
context.strokeStyle = scaleGlassLines[i].color;
context.moveTo(scaleGlassRectangle.x + scaleGlassLines[i].xStart, scaleGlassRectangle.y + scaleGlassLines[i].yStart);
context.lineTo(scaleGlassRectangle.x + scaleGlassLines[i].xEnd, scaleGlassRectangle.y + scaleGlassLines[i].yEnd);
context.stroke();
}
context.restore();

context.beginPath();
var gradient = context.createRadialGradient(
parseInt(centerPoint.x), parseInt(centerPoint.y), originalRadius - 5,
parseInt(centerPoint.x), parseInt(centerPoint.y), originalRadius);

gradient.addColorStop(0.50, 'silver');
gradient.addColorStop(0.90, 'silver');
gradient.addColorStop(1, 'black');
context.strokeStyle = gradient;
context.lineWidth = 5;
context.arc(parseInt(centerPoint.x), parseInt(centerPoint.y), originalRadius, 0, Math.PI * 2, false);
context.stroke();

drawAnchor();
}

添加事件

鼠标拖动

鼠标移动到放大镜上,然后按下鼠标左键,可以拖动放大镜,不按鼠标左键或者不在放大镜区域都不可以拖动放大镜。
为了实现上面的效果,我们要实现3种事件

mousedown
,
mousemove
, ‘mouseup’, 当鼠标按下时,检测是否在放大镜区域,如果在,设置放大镜可以移动。鼠标移动时更新放大镜中兴点的坐标。鼠标松开时,设置放大镜不可以被移动。