/***************绘制图像,放大缩小实例******************/
varcanvas=document.getElementById('canvasOne');varctx=canvas.getContext('2d');//加载图片
varscale= 0.1;//缩放比例
varimg= newImage();
img.οnlοad= function() {
reShow();
}
img.src= '../images/1.jpg';//根据缩放比例,显示图片
functionreShow() {varcWidth=canvas.width;varcHeight=canvas.height;variWidth=img.width;variHeight=img.height;varwidth=iWidth*scale;varheight=iHeight*scale;//居中显示
varleft=(cWidth-width)/ 2;vartop=(cHeight-height)/ 2;//清空画布极限值 --失败
//var maxWidth = iWidth > width ? iWidth : width;
//var maxHeight = iHeight > height ? iHeight : height;
//var minLeft = left < 0 ? left : 0;
//var minTop = top < 0 ? top : 0;
//ctx.clearRect(0,0,cWidth,cHeight);
//清除画布方式2 --失败
//var number = 1 / scale;
//var cWidth = canvas.width * number;
//var cHeight = canvas.height * number;
//ctx.clearRect(-cWidth, -cHeight, cWidth * 2, cHeight * 2);
//清除画布3
ctx.clearRect(-spanLeft,-spanTop, canvas.width, canvas.height);
ctx.drawImage(img, left, top, width, height);
}//滚轮时间
addMouseWheel(canvas,function(e) {vartemp=e.delta> 0 ? 0.1:-0.1;
scale+=temp;//缩放极限判断
scale=scale< 0.1 ? 0.1: scale;
scale=scale> 1 ? 1: scale;
reShow();
});//鼠标移动事件
//1.有一个鼠标移动,重绘图片的bug
varoldX=oldY= 0;varisMove= false;varspanLeft=spanTop= 0;
canvas.οnmοusedοwn= function(e) {
oldX=e.clientX;
oldY=e.clientY;
isMove= true;
}
canvas.οnmοusemοve= function(e) {if(isMove) {varcurrentX=e.clientX;varcurrentY=e.clientY;//计算移动的距离
varspanX=currentX-oldX;varspanY=currentY-oldY;
spanLeft+=spanX;
spanTop+=spanY;
ctx.translate(spanX, spanY);
reShow();//记录当前结果
oldX=currentX;
oldY=currentY;
}
}
canvas.οnmοuseup= function(e) {
oldX=oldY= 0;
isMove= false;
}
canvas.οnmοuseleave= function(e) {
oldX=oldY= 0;
isMove= false;
}