js实现在图片上画矩形框

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>

效果图:

08155331_9UuP.bmp

转载于:https://my.oschina.net/darkness/blog/802216

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在MFC中,可以使用CRect类和CDC类的相关函数来在图片上画矩形框。 以下是一个简单的示例代码: 首先,我们需要为应用程序添加一个按钮和一个图片控件。在按钮的单击事件处理程序中,我们将使用CDC类的相关函数来在图片上画矩形框。 ``` // 头文件包含 #include <afxwin.h> #include <afxcmn.h> #include <afxdlgs.h> // 定义全局变量 CBitmap m_bitmap; // 图片 CRect m_rect; // 矩形框 // 按钮单击事件处理程序 void CMyDialog::OnBnClickedButtonDrawRect() { // 获取图片控件的CDC CDC* pDC = m_picture.GetDC(); // 创建画笔 CPen pen(PS_SOLID, 2, RGB(255, 0, 0)); // 选择画笔 CPen* pOldPen = pDC->SelectObject(&pen); // 画矩形框 pDC->Rectangle(m_rect); // 恢复画笔 pDC->SelectObject(pOldPen); // 释放CDC m_picture.ReleaseDC(pDC); } // 图片控件绘制事件处理程序 void CMyDialog::OnPaint() { CPaintDC dc(this); // 创建内存DC CDC dcMem; dcMem.CreateCompatibleDC(&dc); // 选择图片 CBitmap* pOldBitmap = dcMem.SelectObject(&m_bitmap); // 绘制图片 BITMAP bm; m_bitmap.GetBitmap(&bm); dc.StretchBlt(0, 0, bm.bmWidth, bm.bmHeight, &dcMem, 0, 0, bm.bmWidth, bm.bmHeight, SRCCOPY); // 恢复DC dcMem.SelectObject(pOldBitmap); } // 图片控件大小改变事件处理程序 void CMyDialog::OnSize(UINT nType, int cx, int cy) { CDialogEx::OnSize(nType, cx, cy); // 更新矩形框 m_rect = CRect(10, 10, cx - 10, cy - 10); } // 打开图片按钮单击事件处理程序 void CMyDialog::OnBnClickedButtonOpenImage() { // 打开文件对话框 CFileDialog dlg(TRUE, NULL, NULL, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, _T("Image Files (*.bmp;*.jpg;*.jpeg;*.png)|*.bmp;*.jpg;*.jpeg;*.png||"), this); if (dlg.DoModal() == IDOK) { // 加载图片 m_bitmap.LoadImage(dlg.GetPathName()); // 更新图片控件 m_picture.Invalidate(); } } ``` 在上面的代码中,我们首先在OnSize事件处理程序中更新矩形框的大小,然后在打开图片按钮单击事件处理程序中加载图片并更新图片控件。 在按钮单击事件处理程序中,我们获取图片控件的CDC,并使用CPen类创建一个红色的画笔。然后选择画笔,使用CDC的Rectangle函数在图片上画矩形框。最后,我们恢复画笔并释放CDC。 在图片控件的绘制事件处理程序中,我们使用CDC的StretchBlt函数绘制图片。在这个示例中,我们将图片缩放到与图片控件的大小相同。 请注意,在实际应用中,您可能需要在矩形框上添加文本或其他图形元素。您可以使用CDC的相关函数来实现这些效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值