HTML5 Canvas实现放大镜效果示例

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


canvas.onmousedown = function (e) {
var point = windowToCanvas(e.clientX, e.clientY);
var x1, x2, y1, y2, dis;

x1 = point.x;
y1 = point.y;
x2 = centerPoint.x;
y2 = centerPoint.y;
dis = Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2);
if (dis < Math.pow(originalRadius, 2)) {
lastPoint.x = point.x;
lastPoint.y = point.y;
moveGlass = true;
}
}

canvas.onmousemove = function (e) {
if (moveGlass) {
var xDis, yDis;
var point = windowToCanvas(e.clientX, e.clientY);
xDis = point.x - lastPoint.x;
yDis = point.y - lastPoint.y;
centerPoint.x += xDis;
centerPoint.y += yDis;
lastPoint.x = point.x;
lastPoint.y = point.y;
draw();
}
}

canvas.onmouseup = function (e) {
moveGlass = false;
}

鼠标双击

当移动到对应的线段上时,鼠标双击可以选择该线段,将该线段的颜色变为红色。


canvas.ondblclick = function (e) {
var xStart, xEnd, yStart, yEnd;
var clickPoint = {};
clickPoint.x = scaleGlassRectangle.x + scaleGlassRectangle.width / 2;
clickPoint.y = scaleGlassRectangle.y + scaleGlassRectangle.height / 2;
var index = -1;

for (var i = 0; i < scaleGlassLines.length; i++) {
var scaleLine = scaleGlassLines[i];

xStart = scaleGlassRectangle.x + scaleLine.xStart - 3;
xEnd = scaleGlassRectangle.x + scaleLine.xStart + 3;
yStart = scaleGlassRectangle.y + scaleLine.yStart;
yEnd = scaleGlassRectangle.y + scaleLine.yEnd;

if (clickPoint.x > xStart && clickPoint.x < xEnd && clickPoint.y < yStart && clickPoint.y > yEnd) {
scaleLine.color = "#f00";
index = scaleLine.index;
break;
}
}

for (var i = 0; i < chartLines.length; i++) {
var line = chartLines[i];
if (line.index == index) {
line.color = "#f00";
} else {
line.color = "#888";
}
}

draw();
}

键盘事件

因为线段离得比较近,所以使用鼠标移动很难精确的选中线段,这里使用键盘的

w
,
a
,
s
,
d
来进行精确移动


document.onkeyup = function (e) {
if (e.key == 'w') {
centerPoint.y = intAdd(centerPoint.y, -0.2);
}
if (e.key == 'a') {
centerPoint.x = intAdd(centerPoint.x, -0.2);
}
if (e.key == 's') {
centerPoint.y = intAdd(centerPoint.y, 0.2);
}
if (e.key == 'd') {
centerPoint.x = intAdd(centerPoint.x, 0.2);
}
draw();
}

** 参考资料 **
HTML5-MagnifyingGlass

到此这篇关于HTML5 Canvas实现放大镜效果示例的文章就介绍到这了,更多相关HTML5 Canvas放大镜内容请搜索软件开发网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持软件开发网!