zoukankan      html  css  js  c++  java
  • 取得图片原来的大小

    如果是在预加载的情况下,即没有把图片插入DOM树,它没有受到CSS规则的影响,直接取其img.width与img.height就行了。可以参考〈a href="http://www.cnblogs.com/rt0d/archive/2011/04/17/2018646.html"〉这一篇博文,做得相当棒了。

          function loadImage(url, callback) {
              var img = new Image(); 
              img.onload = function(){
                img.onload = null;
                callback.call(img,img.width,img.height)
              }
              img.src = url; 
            }
    

    但如果在DOM树建完之后,取得某一图片原来的尺寸,在safari,firefox,chrome,与opera10+中,有两个便捷的属性(naturalWidth,naturalHeight)可以做到这一点。

    对于IE与opera的早期版本,就没有这么幸运了,我们需要转换视角,从求当前图片的原来尺寸,变为求另一个同URL的图片的尺寸

         function getActualSize(img){
            var testee = new Image;//弄一个替身
            testee.style.position = 'absolute';
            testee.style.visibility = 'hidden';
            testee.style.top =  testee.style.left = '0px';
            document.body.appendChild(testee);
            testee.src = img.src;
            var width = testee.width;
            var height = testee.height;
            testee.parentNode.removeChild(testee);
            return {width, height:height};
          }
    

    此法虽然因为缓存而不会再发请求,但需要多创建一个元素作为测量对象,开销比较大。有没有更好的办法呢?我们可以考虑一下IE的那三组样式属性了,style,currentStyle与runtimeStyle。眼下,我们只需用到runtimeStyle。它有个特点是,不用同步style就能重绘原来的元素。我们可以直接在runtimeStyle进行设置,然后取得相关值,再重置回去就行了。

          function getActualSize(img) {
            var run = img.runtimeStyle;
            var mem = { w: run.width, h: run.height }; //保存原来的尺寸
            run.width  = run.height = "auto";//重写
            var w = img.width;//取得现在的尺寸
            var h = img.height;
            run.width  = mem.w; //还原
            run.height = mem.h;
            return {w, height:h};
          }
    

  • 相关阅读:
    大伯的八十岁寿辰
    收到 wincore.cpp 中一个 " ASSERT " BUG: 当 MFC 应用程序 Visual C++ 中 MFC 规则 DLL 中调用函数声明
    命名空间Microsoft.Office.Interop.Word不存在....
    中国测绘科学研究院招聘WEBGIS开发工程师与客座研究生
    开源GIS学习笔记 sinoly BLOGJAVA
    2007年7月9日星期一
    转载:使用感受: VC2005 VC6.0
    推荐:用ogr和PIL把矢量数据转化成栅格图像
    《赢在中国》感言
    VS2005的断点无效问题
  • 原文地址:https://www.cnblogs.com/rubylouvre/p/2037115.html
Copyright © 2011-2022 走看看