Last active
August 29, 2015 14:07
-
-
Save KitaitiMakoto/74897d9af38f7d662684 to your computer and use it in GitHub Desktop.
画像を画面に合わせて拡大縮小したりトリミングする ref: http://qiita.com/KitaitiMakoto/items/2ac522b92a063055bcbb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function adaptImage(image, width, height) { | |
// 作業場所としてのCanvasを作成 | |
var canvas = document.createElement("canvas"); | |
canvas.width = width; | |
canvas.height = height; | |
var workspace = new Stage(canvas); | |
var bitmap = new Bitmap(image); | |
// フィットさせたいコンテナ(?)と、画像の「横長ぐあい」を計算 | |
var aspectRatio = width / height; | |
var imageAspectRatio = image.width / image.height; | |
if (imageAspectRatio < aspectRatio) { | |
// コンテナの方が、より横長 | |
// だから、幅をフィットさせる。画像の上下にはみ出す部分を落とすことになる | |
var scale = width / image.width; | |
} else { | |
// 画像の方が、より横長 | |
// だから、高さをフィットさせる。画像の左右にはみ出す部分を落とすことになる | |
var scale = height / image.height; | |
} | |
bitmap.scaleX = bitmap.scaleY = scale; | |
// デフォルトでは、画像は左上を合わせて、右下部分がトリミングされるので、 | |
// 位置をずらして「作業場所Canvas」と中心を揃えるように移動させる | |
bitmap.x = (canvas.width - bitmap.scaleX * image.width) / 2; | |
bitmap.y = (canvas.height - bitmap.scaleY * image.height) / 2; | |
// 作業場所Canvasに実際にレンダリングする | |
workspace.addChild(bitmap); | |
workspace.update(); | |
// 画像を作って返す | |
var adaptedImage = new Image(); | |
adaptedImage.src = canvas.toDataURL(); | |
return adaptedImage; | |
} | |
var image = new Image(); | |
image.addEventListener("load", function(event) { | |
var adaptedImage = adaptImage(event.target, window.innerWidth, window.innerHeight); | |
// 画像を何かする。背景としてCSSで設定するとか。 | |
}); | |
image.src = "http://..."; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment