<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<!-- 可视区域效果 + preserveAspectRatio -->
<h3>可视区域效果 + preserveAspectRatio + viewBox</h3>
<!-- 配置区域 -->
<span>preserveAspectRatio - </span>
<span>align:</span>
<select id="align" onchange="onAlignChange(this)">
<option value="none">none</option>
<option value="xMinYMin" selected>xMinYMin</option>
<option value="xMidYMin">xMidYMin</option>
<option value="xMaxYMin">xMaxYMin</option>
<option value="xMinYMid">xMinYMid</option>
<option value="xMidYMid">xMidYMid</option>
<option value="xMaxYMid">xMaxYMid</option>
<option value="xMinYMax">xMinYMax</option>
<option value="xMidYMax">xMidYMax</option>
<option value="xMaxYMax">xMaxYMax</option>
</select>
<span>meetOrSlice:</span>
<select id="meetOrSlice" onchange="onMeetOrSliceChange(this)">
<option value="meet">meet</option>
<option value="slice">slice</option>
</select>
<div style="margin-top: 10px;">
<span>viewBox - </span>
x:<input type="number" value="0" placeholder="x" onchange="onChangeX(this)" style="width: 50px;">
y:<input type="number" value="0" placeholder="y" onchange="onChangeY(this)" style="width: 50px;">
width:<input type="number" value="200" placeholder="width" onchange="onChangeWidth(this)" style="width: 50px;">
height:<input type="number" value="200" placeholder="height" onchange="onChangeHeight(this)" style="width: 50px;">
</div>
<!-- 画布 -->
<div style="margin-top: 20px;">
<!-- svg画布-->
<svg id="svg" xmlns="http://www.w3.org/2000/svg" width="300" height="200" viewBox="0 0 200 200" preserveAspectRatio="none meet" style="background-color: green;">
<rect id="rect" x="0" y="0" width="200" height="200" fill="red"/>
</svg>
</div>
<!-- JS 切换配置 -->
<script>
// 默认配置
var alignType = 'xMinYMin'
var meetOrSliceType = 'meet'
var x = 0
var y = 0
var width = 200
var height = 200
// 监听切换
function onAlignChange (e) {
// 记录
alignType = e.value
// 更新
reloadUI()
}
function onMeetOrSliceChange (e) {
// 记录
meetOrSliceType = e.value
// 更新
reloadUI()
}
function onChangeX (e) {
// 记录
x = e.value
// 更新
reloadUI()
}
function onChangeY (e) {
// 记录
y = e.value
// 更新
reloadUI()
}
function onChangeWidth (e) {
// 记录
width = e.value
// 更新
reloadUI()
}
function onChangeHeight (e) {
// 记录
height = e.value
// 更新
reloadUI()
}
// 组装赋值
function reloadUI () {
// 组装
var viewBox = [x, y, width, height].join(' ')
var preserveAspectRatio = [alignType, meetOrSliceType].join(' ')
// 赋值
svg.setAttribute('viewBox', viewBox)
svg.setAttribute('preserveAspectRatio', preserveAspectRatio)
rect.setAttribute('x', x)
rect.setAttribute('y', y)
rect.setAttribute('width', width)
rect.setAttribute('height', height)
}
// 初始化
reloadUI()
</script>
</body>
</html>