我正在尝试制作一个可以适应并根据浏览器窗口重新缩放的偏移矩形。我对 JavaScript 和 SVG 还很陌生,所以也许这里有人有更多的知识。
这是我一直试图找出的代码的 Codepen。 如您所见,矩形的行为不正确。如果能提供所有提示,我将不胜感激。
https://codepen.io/LinusFree/pen/jZNQxg
HTML
<div id="wrapper">
</div>
Javascript
var draw = SVG('wrapper').size(100, 100)
var rect = draw.rect(100, 100).move(30, 30).attr({ stroke: '#f06', fill: 'none' })
CSS
#wrapper {
width: 100vw;
height: 100vh;
}
svg {
width: 100vw;
height: 100vh;
}
rect {
width: 100%;
height: 100%;
max-width: 100%;
max-height: 100%;
}
最佳答案
您需要考虑到您的 rect
在 x 和 y 上以 30px 移动,因此您必须减小其大小并同时使用 vh
和 vw
单位。您还可以删除空格以避免出现滚动条:
var draw = SVG('wrapper').size(100, 100)
var rect = draw.rect(100, 100).move(30, 30).attr({
stroke: '#f06',
fill: 'none'
})
body {
margin: 0; /*Don't forget this*/
font-size:0; /*remove white space*/
}
/*
useless
#wrapper {
width: 100vw;
height: 100vh;
}
*/
svg {
width: 100vw;
height: 100vh;
}
rect {
width: calc(100vw - 60px); /* we remove 60px to keep the same offset (30px) on both sides*/
height: calc(100vh - 60px);
max-width: 100%;
max-height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.3/svg.min.js"></script>
<div id="wrapper">
</div>
更新
上面的解决方案似乎只适用于 chrome,所以这里有另一个更受支持的解决方案:
var draw = SVG('wrapper').size(100, 100)
var rect = draw.rect($(window).width() - 60, $(window).height() - 60).move(30, 30).attr({
stroke: '#f06',
fill: 'none'
})
$(window).resize(function() {
$('svg rect').attr('height', $(window).height() - 60);
$('svg rect').attr('width', $(window).width() - 60);
})
body {
margin: 0;/*Don't forget this*/
font-size: 0;/*remove white space*/
}
svg {
width: 100vw;
height: 100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.3/svg.min.js"></script>
<div id="wrapper">
</div>
关于javascript - 具有 100vw 和 100vh 的 SVG.JS 响应矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48491030/