加载后调整图像大小

时间:2015-07-30 10:32:44

标签: javascript jquery

我尝试从网址加载图片然后使用它。如何将加载的图片设置为100x150内的onload()



var img = new Image();
var theurl = "furits/lychee.png";
img.onload = function() {
  //how can I set 100 width and 150 height?
  //do something from resized image
};
img.src = theurl; 




2 个答案:

答案 0 :(得分:3)

尝试this



var img = new Image();
var theurl = 'http://www.sunhome.ru/UsersGallery/wallpapers/78/gomer-simpson-kartinka.jpg';
img.onload = function() {
    this.width = 100;
    this.height = 150;
    document.body.appendChild(this);
};
img.src = theurl;




答案 1 :(得分:0)

无论如何你也可以使用' img'而不是这个',因为他们引用相同的。

在JavaScript中,这总是指我们正在执行的函数的“所有者”,或者更确切地说,指向函数是其方法的对象。



var img = new Image();
var theurl = 'http://www.sunhome.ru/UsersGallery/wallpapers/78/gomer-simpson-kartinka.jpg';
img.onload = function() {
    img.width = 100;
    img.height = 150;
    document.body.appendChild(this);
};
img.src = theurl;




但是在这种情况下不应该使用它我们不确定'这个'属于。

function doSomething() {
   this.style.color = '#cc0000';
}

在这里,'这个'属于页面或'窗口'换一种说法。

最好只在编写OO Javascript / Constructor Functions时使用它。

相关问题