js使用canvas实现在线绘制图片地图-支持放大缩小及拖动,并且点击图片的实际位置横纵坐标

<body>
<canvas id=”canvas” width=”1024″ height=”768″></canvas>
</body>
<script>
var canvas,context;
var img,//图片对象
imgIsLoaded,//图片是否加载完成;
imgX=0,
imgY=0,
imgScale=1;

var image_widht=0;
var image_height=0;
(function int(){
canvas=document.getElementById(‘canvas’);
context=canvas.getContext(‘2d’);
loadImg();
})();

function loadImg(){
img=new Image();
img.src=”map.jpg”;
img.onload=function(){
imgIsLoaded=true;
drawImage();
image_width = img.width;
image_height= img.height;
}

}

function drawImage(){
context.clearRect(0,0,canvas.width,canvas.height);
context.drawImage(img,0,0,img.width,img.height,imgX,imgY,img.width*imgScale,img.height*imgScale);
}
//监听canvas拖动事件
canvas.onmousedown=function(event){
var pos=windowToCanvas(canvas,event.clientX,event.clientY);
canvas.onmousemove=function(event){
canvas.style.cursor=”move”;
var pos1=windowToCanvas(canvas,event.clientX,event.clientY);
var x=pos1.x-pos.x;
var y=pos1.y-pos.y;
pos=pos1;
imgX+=x;
imgY+=y;
drawImage();
}

canvas.onmouseup=function(){
canvas.onmousemove=null;
canvas.onmouseup=null;
canvas.style.cursor=”default”;
}
//->console.log(“canvas开始坐标 x=”+imgX +” & y=”+imgY);
}
//监听canvas放大缩小事件
canvas.onmousewheel=canvas.onwheel=function(event){
var pos=windowToCanvas(canvas,event.clientX,event.clientY);
event.wheelDelta=event.wheelDelta?event.wheelDelta:(event.deltaY*(-40));
if(event.wheelDelta>0){
imgScale*=2;
imgX=imgX*2-pos.x;
imgY=imgY*2-pos.y;
}else{
imgScale/=2;
imgX=imgX*0.5+pos.x*0.5;
imgY=imgY*0.5+pos.y*0.5;
}
drawImage();
//->console.log(“canvas开始坐标 x=”+imgX +” & y=”+imgY);
}

canvas.onclick=function(event){
var pos = windowToCanvas(canvas,event.clientX,event.clientY);
//实际点的坐标
var isX = 0;
var isY = 0;
//实际选中坐标 肯定 = 点击的坐标 + canvas的坐标(必须为-数)
var temp_canvas_x = imgX-imgX*2;
var temp_canvas_y = imgY-imgY*2;

if(imgScale == 1){ //原始尺寸
isX = (pos.x+temp_canvas_x);
isY = (pos.y+temp_canvas_y);
} else {
if(imgScale>1){ //被放大了,实际坐标需要/
isX = (pos.x+temp_canvas_x)/imgScale;
isY = (pos.y+temp_canvas_y)/imgScale;
} else { //被缩小了,坐标点放大
isX = (pos.x+temp_canvas_x)*(1/imgScale);
isY = (pos.y+temp_canvas_y)*(1/imgScale);
}
}

//处理左上的是否超出图片范围
if(isX<0 || isY<0){
console.log(“请选择图片区域”);
//return;
}
//处理右下区域,主要处理图片是否超出
if(isX>image_width || isY > image_height){
console.log(“超出图片尺度”);
}
console.log(“点击的坐标点: x=”+isX +” & y=”+isY);
console.log(“图片完整的宽度=”+image_width+”&高度=”+image_height);
console.log(“缩放级别:”+imgScale);
}

//获取窗口中canvas的区域
function windowToCanvas(canvas,x,y){
var bbox = canvas.getBoundingClientRect();
return {
x:x – bbox.left – (bbox.width – canvas.width) / 2,
y:y – bbox.top – (bbox.height – canvas.height) / 2
};
}
</script>

发表评论