如何用JS改变图像的原始大小

JavaScript08

如何用JS改变图像的原始大小,第1张

用JS改变图像的原始大小方法:

var canvas = document.getElementById("canvas")

var context = canvas.getContext("2d")

$('input[type=file]').change(function(){

var file=this.files[0]

var reader=new FileReader()

var image=new Image()

reader.readAsDataURL(file)

reader.onload=function(){

// 通过 reader.result 来访问生成的 DataURL

var url=reader.result

image.src=url

alert(image.width)

alert(image.height)

image.height /=4

image.width /=4

canvas.setAttribute("width", image.width+"px")

canvas.setAttribute("height", image.height+"px")

alert(image.naturalWidth)

alert(image.naturalHeight)

context.drawImage(image,0,0,image.width,image.height)

}

})

这种情况用CSS来控制最合适。例如你想让初始图片显示为100px*100px,则:

<img src="images/pic.png" width="100" height="100" />

或者:

<img src="images/pic.png" style="width:100pxheight:100px" />

当页面中图片非常多,且要求每张图片的大小依据其父容器来固定怎么办?可以使用max-weight:

img {max-weight:100%}

这样图片会自动缩放到和其父容器等宽。

这种情况用CSS来控制最合适。例如你想让初始图片显示为100px*100px,则:

<img src="images/pic.png" width="100" height="100" />

或者:

<img src="images/pic.png" style="width:100pxheight:100px" />

当页面中图片非常多,且要求每张图片的大小依据其父容器来固定怎么办?可以使用max-weight:

img {max-weight:100%}

这样图片会自动缩放到和其父容器等宽。