style,
lineWidth 等,然后会将这个状态压入一个堆栈。
restore 用来恢复上一次 save 的状态,从堆栈里弹出最顶层的状态。
context.save();
context.beginPath();
context.arc(centerPoint.x, centerPoint.y, originalRadius, 0, Math.PI * 2, false);
context.clip();
......
context.restore();计算放大镜区域
通过中心点、被放大区域的宽高以及放大倍数,获得区域的左上角坐标以及区域的宽高。
scaleGlassRectangle = {
x: centerPoint.x - originalRectangle.width * scale / 2,
y: centerPoint.y - originalRectangle.height * scale / 2,
width: originalRectangle.width * scale,
height: originalRectangle.height * scale
}绘制图片
在这里我们使用
context.drawImage(img,sx,sy,swidth,sheight,x,y,width,height); 方法,将 canvas 自身作为一副图片,然后取被放大区域的图像,将其绘制到放大镜区域里。
context.drawImage(canvas,
originalRectangle.x, originalRectangle.y,
originalRectangle.width, originalRectangle.height,
scaleGlassRectangle.x, scaleGlassRectangle.y,
scaleGlassRectangle.width, scaleGlassRectangle.height
);绘制放大边缘
createRadialGradient 用来绘制渐变图像
context.beginPath();
var gradient = context.createRadialGradient(
centerPoint.x, centerPoint.y, originalRadius - 5,
centerPoint.x, centerPoint.y, originalRadius);
gradient.addColorStop(0, 'rgba(0,0,0,0.2)');
gradient.addColorStop(0.80, 'silver');
gradient.addColorStop(0.90, 'silver');
gradient.addColorStop(1.0, 'rgba(150,150,150,0.9)');context.strokeStyle = gradient;
context.lineWidth = 5;
context.arc(centerPoint.x, centerPoint.y, originalRadius, 0, Math.PI * 2, false);
context.stroke();
添加鼠标事件
为 canvas 添加鼠标移动事件
canvas.onmousemove = function (e) {
......
}转换坐标
鼠标事件获得坐标一般为屏幕的或者 window 的坐标,我们需要将其装换为 canvas 的坐标。
getBoundingClientRect 用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置。
function windowToCanvas(x, y) {
var bbox = canvas.getBoundingClientRect();
return {x: x - bbox.left, y: y - bbox.top}
}









