Skip to content

Instantly share code, notes, and snippets.

@wushan
Created February 21, 2017 07:07
Show Gist options
  • Save wushan/5544c31f0f54e82a0db714dd16050f96 to your computer and use it in GitHub Desktop.
Save wushan/5544c31f0f54e82a0db714dd16050f96 to your computer and use it in GitHub Desktop.
根據外框比例計算 scale 程度
var canvas = window.canvas
// Scale Canvas to fit viewport
// var container = document.getElementById('artboard')
var container = document.querySelector('.canvas-wrapper')
var paintArea = document.getElementById('canvas')
// canvas.wrapperEl.style.transform = "scale(.8)"
;(function () {
// console.log(canvas)
// var aspectRatio = canvas.width / canvas.height
// Ratio = Canvas 寬(實際px) 與 artboard 寬的比值
// console.log(canvas.width)
// console.log(container)
// console.log(container.clientWidth)
var ratioW = canvas.width / container.clientWidth
var ratioH = canvas.height / container.clientHeight
// console.log('Canvas 實際寬度是視窗寬度的: ' + ratioW + ' 倍')
// console.log('Canvas 實際高度是視窗寬度的: ' + ratioH + ' 倍')
var motive
// 若寬度比值大於或等於高度比值 (代表此矩形為橫式或正方形)
if (ratioW >= ratioH) {
// 橫式或正方形情況下,Canvas 實際寬度大於視窗寬度 (必須 scale 縮減)
if (ratioW > 1) {
ratioW = container.clientWidth / canvas.width
// 再縮減 80% 以避免 canvas 貼邊。
motive = ratioW * 0.8
console.log(ratioW)
if (motive > 1) {
motive = 1
}
paintArea.style.transform = 'scale(' + motive + ')'
// paintArea.style.transformOrigin = "25% 25%"
} else {
motive = 1
paintArea.style.transform = 'scale(' + motive + ')'
// paintArea.style.transformOrigin = "25% 25%"
}
} else if (ratioW < ratioH) {
if (ratioH > 1) {
ratioH = container.clientHeight / canvas.height
// 再縮減 80% 以避免 canvas 貼邊。
motive = ratioH * 0.8
console.log(ratioH)
if (motive > 1) {
motive = 1
}
paintArea.style.transform = 'scale(' + motive + ')'
// paintArea.style.transformOrigin = "45% 25%"
} else {
motive = 1
paintArea.style.transform = 'scale(' + motive + ')'
// paintArea.style.transformOrigin = "25% 25%"
}
}
}())
// 天才
var doit
var resizedw = (function () {
this.fit()
}.bind(this))
window.onresize = function () {
clearTimeout(doit)
doit = setTimeout(resizedw, 100)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment