文档章节

js实现在图片上画矩形框

暗之幻影
 暗之幻影
发布于 2015/09/23 16:59
字数 1072
阅读 86
收藏 0
JS组件:

@author Darkness
@version 1.0
@date 2010-08-18

Function.prototype.bind = function(obj){
    var _method = this;
    return function(){
        _method.apply(obj, arguments);
    }
}

DrawRectangle = function(id, onMouseUp, className){
    this.IMG = document.getElementById(id);
    this.isDraw = false;
    this.isMouseUp = true;
    this.index = 0;
    this.currentDrawRectangle = null;
	this.className = className;
    
    this.RectangleDivs = [];
    
    this.debug = false;

    this._onMouseUp = onMouseUp;
    
    this.bindListener();
}

DrawRectangle.prototype = {
    bindListener: function(){
    
        this.IMG.onmousemove = this.dragSize.bind(this);
        this.IMG.onmouseup = this.onMouseUp.bind(this);
        this.IMG.onmouseout = this.onMouseOut.bind(this);
        this.IMG.onmouseover = this.onMouseOver.bind(this);
        this.IMG.onmousedown = this.drawLayer.bind(this);
        this.IMG.onmouseup = this.onMouseUp.bind(this);
    },
    drawLayer: function(){
        this.IMG.setCapture(true);
        this.isDraw = true;
        this.ismouseup = false;
        this.index++;
        
        var pos = this.getSourcePos();
		
		var x = event.offsetX; 
        var y = event.offsetY; 

        var top = y + pos.top - 2;
        var left = x + pos.left - 2;
       
        var d = document.createElement("div");
        document.body.appendChild(d);
        d.style.border = "1px solid #ff0000";
        d.style.width = 0;
        d.style.height = 0;
        d.style.overflow = "hidden";
        d.style.position = "absolute";
        d.style.left = left;
        d.style.top = top;
		if(this.className) {
			d.className = this.className;
		}
        d.id = "draw" + this.index;
        if (this.debug) {
            //d.innerHTML = "<div class='innerbg'>x:" + x + ",y:" + y + ". img_x:" + img_x + ",img_y:" + img_y + ".</div>";
        }
        
        this.currentDrawRectangle = d;
        
        this.RectangleDivs[this.index] = {
            left: left,
            top: top,
            el: d
        };
    },
    getSourcePos: function(){
        return this.getAbsolutePosition(this.IMG);
    },
    dragSize: function(){
        if (this.isDraw) {
            if (event.srcElement.tagName != "IMG") 
                return;
            
            var pos = this.getSourcePos();
            var img_x = pos.top; 
            var img_y = pos.left; 
            var x = event.offsetX;
            var y = event.offsetY;
            var drawW = (x + img_x) - this.RectangleDivs[this.index].left;
            var drawH = (y + img_y) - this.RectangleDivs[this.index].top;
            this.currentDrawRectangle.style.width = drawW > 0 ? drawW : -drawW;
            this.currentDrawRectangle.style.height = drawH > 0 ? drawH : -drawH;
            if (drawW < 0) {
                this.currentDrawRectangle.style.left = x + img_x;
            }
            if (drawH < 0) {
                this.currentDrawRectangle.style.top = y + img_y;
            }
            
            if (this.debug) {
                this.currentDrawRectangle.innerHTML = "<div class='innerbg'>x:" + x + ",y:" + y +
                ". img_x:" +
                img_x +
                ",img_y:" +
                img_y +
                ". drawW:" +
                drawW +
                ",drawH:" +
                drawH +
                ".  Dleft[i]:" +
                this.RectangleDivs[this.index].left +
                ",Dtop[i]:" +
               this.RectangleDivs[this.index].top +
                "src:" +
                event.srcElement.tagName +
                ".</div>";
            }
            
        }
        else {
            return false;
        }
    },
    
    stopDraw: function(){
        this.isDraw = false;
    },
    
    onMouseOut: function(){
        if (!this.isMouseUp) {
            this.isDraw = false;
        }
    },
    
    onMouseUp: function(){
        this.isDraw = false;
        this.isMouseUp = true;
        this.IMG.releaseCapture();

		if(this._onMouseUp) {
			this._onMouseUp.call(this, this.currentDrawRectangle);
		}
    },
    
    onMouseOver: function(){
        if (!this.isMouseUp) {
            this.isDraw = true;
        }
    },
    
    getAbsolutePosition: function(obj){
        var t = obj.offsetTop;
        var l = obj.offsetLeft;
        var w = obj.offsetWidth;
        var h = obj.offsetHeight;
        
        while (obj = obj.offsetParent) {
            t += obj.offsetTop;
            l += obj.offsetLeft;
        }
        
        return {
            top: t,
            left: l,
            width: w,
            height: h
        }
    }
};


测试页面:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>DrawRectangle</title>

<style type="text/css">
<!--
body {
margin-top: 0px;
margin-left: 0px;
}
div {
 margin:0;
padding:0;
}
.innerbg {
  background:#ff0000;
  filter:Alpha(Opacity=40, FinishOpacity=90, Style=0, StartX=0, StartY=0, FinishX=100, FinishY=100);
width:100%;
height:100%;
}
-->
</style>
<script language="javascript" type="text/javascript" src="DrawRectangle.js"></script>
<script>
window.onload = function() {
	new DrawRectangle('bigimg', function(div){
		alert(div.outerHTML);
	});
}
</script>
</head>
<body>
<img src="test.gif" name="bigimg" border="0" id="bigimg" style="margin-left:0px;margin-top:0px;border:1px solid #ccc;" >
</body>
</html>



@version 1.1
@description 采用div替换原来的img作为画布,修复不兼容其他浏览器bug
@author Darkness
@date 2012-07-27

问题:1.0版本中采用IMG.setCapture(true);方式在图片上实现鼠标拖动等事件监听,该方式在最新的ie9下行不通,也不兼容其他浏览器
改进:采用一个div作为画布替换原来的img,将img作为其背景并删除原来的img,然后监听div上的鼠标拖动等事件达到原来同样的效果,此方式兼容其他浏览器

代码:
DrawRectangle = function(id, onMouseUp, className){  
	
	document.oncontextmenu=function() {  
       return true;  
    };
	    
    this.IMG = document.getElementById(id);  
    
    var masker = document.createElement("div");
    masker.id = "mask_" + id;
    var position = this.getAbsolutePosition(this.IMG);
    
    masker.style.width = position.width + "px";
    masker.style.height = position.height + "px";
    masker.style.left = position.left;
    masker.style.top = position.top;
    masker.style["background-image"] = "url("+this.IMG.src+")";
    masker.className = "imgmasker";

    this.masker = masker;
    this.IMG.parentNode.appendChild(masker);
    this.IMG.parentNode.removeChild(this.IMG);
    
    this.isDraw = false;  
    this.isMouseUp = true;  
    this.index = 0;  
    this.currentDrawRectangle = null;  
    this.className = className;  
      
    this.RectangleDivs = [];  
      
    this.debug = true;  
  
    this._onMouseUp = onMouseUp;  
      
    this.bindListener();  
};
  
DrawRectangle.prototype = {  
    bindListener: function(){  
      
        this.masker.onmousemove = this.dragSize.bind(this);  
        this.masker.onmouseup = this.onMouseUp.bind(this);  
        this.masker.onmouseout = this.onMouseOut.bind(this);  
        this.masker.onmouseover = this.onMouseOver.bind(this);  
        this.masker.onmousedown = this.drawLayer.bind(this);  
        this.masker.onmouseup = this.onMouseUp.bind(this);  
    },  
    drawLayer: function(){  
        //this.IMG.setCapture(true);  
        this.isDraw = true;  
        this.ismouseup = false;  
        this.index++;  
          
        var pos = this.getSourcePos();  
          
        var x = event.offsetX;   
        var y = event.offsetY;   
  
        var top = y + pos.top - 2;  
        var left = x + pos.left - 2;  
         
        var d = document.createElement("div");  
       // document.body.appendChild(d);
        this.masker.appendChild(d);
        d.style.border = "1px solid #ff0000";  
        d.style.width = 0;  
        d.style.height = 0;  
        d.style.overflow = "hidden";  
        d.style.position = "absolute";  
        d.style.left = left + "px";
        d.style.top = top + "px"; 
        d.style.opacity = 0.5;
        
        d.style["z-index"] = 2;
        if(this.className) {  
            d.className = this.className;  
        }  
        d.id = "draw" + this.index;  
        if (this.debug) {  
            d.innerHTML = "<div class='innerbg'>x:" + x + ",y:" + y + "..</div>";  
        }  
          
        this.currentDrawRectangle = d;  
          
        this.RectangleDivs[this.index] = {  
            left: left,  
            top: top,  
            el: d  
        };  
    },  
    getSourcePos: function(){  
        return this.getAbsolutePosition(this.masker);  
    },  
    dragSize: function(){  
        if (this.isDraw) {
            if (!(event.srcElement.tagName.toLowerCase() == "div" && event.srcElement.className == "imgmasker"))   
                return;  
              
            var pos = this.getSourcePos();  
            var img_x = pos.top;   
            var img_y = pos.left;   
            var x = event.offsetX;  
            var y = event.offsetY;  
            var drawW = (x + img_x) - this.RectangleDivs[this.index].left;  
            var drawH = (y + img_y) - this.RectangleDivs[this.index].top;  
            this.currentDrawRectangle.style.width = (drawW > 0 ? drawW : -drawW) + "px";  
            this.currentDrawRectangle.style.height = (drawH > 0 ? drawH : -drawH) + "px"; 
            if (drawW < 0) {  
                this.currentDrawRectangle.style.left = (x + img_x) + "px";   
            }  
            if (drawH < 0) {  
                this.currentDrawRectangle.style.top = (y + img_y) + "px";    
            }  
              
            if (this.debug) {  
                this.currentDrawRectangle.innerHTML = "<div class='innerbg'>x:" + x + ",y:" + y +  
                ". img_x:" +  
                img_x +  
                ",img_y:" +  
                img_y +  
                ". drawW:" +  
                drawW +  
                ",drawH:" +  
                drawH +  
                ".  Dleft[i]:" +  
                this.RectangleDivs[this.index].left +  
                ",Dtop[i]:" +  
               this.RectangleDivs[this.index].top +  
                "src:" +  
                event.srcElement.tagName +  
                ",this.isDraw: " + this.isDraw +
                ",this.isMouseUp: " + this.isMouseUp +
                ".</div>";  
            }  
              
        }  
        else {  
            return false;  
        }  
    },  
      
    stopDraw: function(){  
        this.isDraw = false;  
    },  
      
    onMouseOut: function(){  
        if (!this.isMouseUp) {  
            this.isDraw = false;  
        }  
    },  
      
    onMouseUp: function(){  
        this.isDraw = false;  
        this.isMouseUp = true;  
        //this.IMG.releaseCapture();  
  
        if(this._onMouseUp) {  
            this._onMouseUp.call(this, this.currentDrawRectangle);  
        }  
    },  
      
    onMouseOver: function(){  
        if (!this.isMouseUp) {  
            this.isDraw = true;  
        }  
    },  
      
    getAbsolutePosition: function(obj){  
        var t = obj.offsetTop;  
        var l = obj.offsetLeft;  
        var w = obj.offsetWidth;  
        var h = obj.offsetHeight;  
          
        while (obj = obj.offsetParent) {  
            t += obj.offsetTop;  
            l += obj.offsetLeft;  
        }  
          
        return {  
            top: t,  
            left: l,  
            width: w,  
            height: h  
        };
    }  
};


测试:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
<title>DrawRectangle</title>  
  
<style type="text/css">  
<!--  
body {  
margin-top: 0px;  
margin-left: 0px;  
}  
div {  
	margin:0;  
	padding:0;  
}  
.innerbg {  
	background:#ff0000;  
	filter:Alpha(Opacity=40, FinishOpacity=90, Style=0, StartX=0, StartY=0, FinishX=100, FinishY=100);  
	width:100%;  
	height:100%;  
}

div.imgmasker {
	position: absolute;
	z-index: 1;
	cursor: pointer;
	border:1px solid red;
	background:#000000;
	opacity: 1;
}
-->  
</style>  
<script language="javascript" type="text/javascript" src="arkjs/lang.js"></script>
<script language="javascript" type="text/javascript" src="DrawRectangle.js"></script>  
<script>  
window.onload = function() {  
    new DrawRectangle('bigimg', function(div){  
        //alert(div.outerHTML);  
    });  
}
</script>  
</head>  
<body>  
	<img src="test.jpg" name="bigimg" border="0" id="bigimg" style="margin-left:0px;margin-top:0px;border:1px solid #ccc;"/>
</body>  
</html>

效果图:

本文转载自:http://depravedangel.iteye.com/blog/740278

暗之幻影
粉丝 20
博文 377
码字总数 71245
作品 0
南京
高级程序员
私信 提问
ASP.NET误人子弟教程:在MVC下如何返回图片

这几天忙着一些小事,也没有写什么了,今天,我们来玩一个比较简单的东东。就是在MVC下如何返回图片,相信,在传统WebForm下,大家都晓得怎么弄,方也不限于一种,但是,在架构较为严格的MVC...

junwong
2012/04/18
767
0
基于Html+js实现的瓦片式的Webgis栅格地图管理平台

基于Html+js实现的Webgis栅格平台 成都领君科技提供的基于HTML5+js开发的瓦片式地图发布平台,适用于几乎所有浏览器(IE6+,遨游,火狐,搜狗,谷歌,360,世界之窗,Opera等)。功能模块包括如...

成都领君科技
2012/04/04
2.3K
0
jQuery zxxbox弹出框插件(v3.0)测试页面

源文件下载.zip 16.6k 一、内置弹框 显示最简单的内置的信息确定提示框:点击我 $("#test1").click(function(){ $.zxxbox.remind("你已成功受邀参加威尼斯电影节。"); }); 带回调函数的信息确...

mickelfeng
2013/01/07
158
0
input type="button" 和button区别

来源: https://www.jianshu.com/p/687aabeedae5 在一个页面上画一个按钮,有四种办法: 1、 这就是一个按钮。如果你不写javascript 的话,按下去什么也不会发生。 2、 这样的按钮用户点击之...

codingcoge
2018/05/16
0
0
原创jquery图片上传预览插件uploadView

勾国印原创jquery图片上传前预览插件uploadView,支持自定义允许上传图片的最大尺寸、允许上传图片的格式、预览图片的宽度和高度以及上传成功后回调函数,兼容手机端和PC端。 大家在开发网站...

够过瘾
2015/10/24
5.5K
0

没有更多内容

加载失败,请刷新页面

加载更多

java通过ServerSocket与Socket实现通信

首先说一下ServerSocket与Socket. 1.ServerSocket ServerSocket是用来监听客户端Socket连接的类,如果没有连接会一直处于等待状态. ServetSocket有三个构造方法: (1) ServerSocket(int port);...

Blueeeeeee
5分钟前
0
0
用 Sphinx 搭建博客时,如何自定义插件?

之前有不少同学看过我的个人博客(http://python-online.cn),也根据我写的教程完成了自己个人站点的搭建。 点此:使用 Python 30分钟 教你快速搭建一个博客 为防有的同学不清楚 Sphinx ,这...

王炳明
昨天
3
0
黑客之道-40本书籍助你快速入门黑客技术免费下载

场景 黑客是一个中文词语,皆源自英文hacker,随着灰鸽子的出现,灰鸽子成为了很多假借黑客名义控制他人电脑的黑客技术,于是出现了“骇客”与"黑客"分家。2012年电影频道节目中心出品的电影...

badaoliumang
昨天
12
0
很遗憾,没有一篇文章能讲清楚线程的生命周期!

(手机横屏看源码更方便) 注:java源码分析部分如无特殊说明均基于 java8 版本。 简介 大家都知道线程是有生命周期,但是彤哥可以认真负责地告诉你网上几乎没有一篇文章讲得是完全正确的。 ...

彤哥读源码
昨天
13
0
jquery--DOM操作基础

本文转载于:专业的前端网站➭jquery--DOM操作基础 元素的访问 元素属性操作 获取:attr(name);$("#my").attr("src"); 设置:attr(name,value);$("#myImg").attr("src","images/1.jpg"); ......

前端老手
昨天
6
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部