我正在尝试创建一个绘制文本的响应式画布。当浏览器的大小发生变化时,画布的大小需要改变。字体大小也随浏览器大小的变化而变化,这需要更改画布的高度。目前我给它固定的高度。设置字体后,我无法指定高度。出于某种原因,字体大小也会受到影响。
PS。请忽略各种div中使用的类。他们在那里是因为存在css框架。
HTML
<div class="col-lg-12 col-sm-12 col-md-12 col-xs-12" id="canvasdiv">
<canvas id="quesCanvas"></canvas>
</div>
的javascript
<script type="text/javascript">
(function() {
var htmlCanvas = document.getElementById('quesCanvas'),
context = htmlCanvas.getContext('2d'),
fontBase = 1000,
fontSize = 22;
var text="<?php echo "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque dolor nunc, accumsan a blandit eu, malesuada ac justo. Sed vel nibh tempor, pretium felis id, tempor elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum quis vestibulum sem. Quisque ullamcorper velit et ultrices blandit. Aenean turpis mauris, tincidunt vel interdum semper, interdum in odio. Ut venenatis, turpis non vestibulum porta, ligula nisi scelerisque massa, eget vulputate urna urna non mauris. Integer faucibus lacinia purus sit amet tempor. Aenean in orci vel justo condimentum faucibus. Integer congue eleifend ipsum volutpat aliquam. Vivamus varius dui at dolor lacinia, at luctus metus vestibulum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent rutrum leo quis mi porttitor, at euismod magna sollicitudin. Nam aliquam sodales libero, id vulputate nulla tempus ac." ?>";
var words=text.split(' ');
initialize();
function initialize() {
window.addEventListener('resize', resizeCanvas, false);
resizeCanvas();
}
function redraw() {
context.font=getFont();
context.fillStyle="#000";
var line = '';
var x=0, y=40, lineHeight=30, maxWidth = htmlCanvas.width;
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
}
else {
line = testLine;
}
}
context.fillText(line, x, y);
}
function resizeCanvas() {
htmlCanvas.height = 500;
htmlCanvas.width = $("#canvasdiv").width();
redraw();
}
function getFont() {
var ratio = fontSize / fontBase;
var size = htmlCanvas.width * ratio;
if (size<10) size = 10;
return (size|0) + 'px sans-serif';
}
})();
</script>