Html 在 div 元素中动态调整画布大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16736619/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically resize canvas within div element
提问by Timothy Trageser
I am working on a website and I want to take what I put in between the title tags and make it an element on the page itself. I am also wanting to do some manipulating of the text like adding borders. I am trying to do this with the canvas element, which I have been able to do successfully, but I cannot figure out how to make it scale.
我在一个网站上工作,我想把我放在标题标签之间的东西变成页面本身的一个元素。我还想对文本进行一些操作,例如添加边框。我正在尝试使用 canvas 元素来做到这一点,我已经能够成功地做到这一点,但我无法弄清楚如何使其缩放。
I have found several answers to how to scale if it is taking up the whole screen, but not within div elements. I have just started learning HTML5 and have never done anything like this before any help is appreciated.
如果它占据整个屏幕而不是在 div 元素内,我已经找到了几个关于如何缩放的答案。我刚刚开始学习 HTML5,在得到任何帮助之前从未做过这样的事情。
javascript code below:
javascript代码如下:
function makeCanvas(){
//1- Get Object
var canvas1 = document.getElementById('titlearea');
var ctx1 = canvas1.getContext('2d');
var title = document.getElementById('pagetitle').text;
//2- Set parameters
ctx1.font = '32pt Arial';
ctx1.fillStyle = 'DeepSkyBlue';
ctx1.strokeStyle = 'Black';
//3- Action
ctx1.fillText(title,200,50);
ctx1.strokeText(title,200,50);
}
HTML snippet below:
下面的 HTML 片段:
<div id="title">
<canvas id="titlearea" width="2000" height="75"></canvas>
</div>
CSS snippet below:
下面的 CSS 片段:
#title{
background-color: #E6E6FA;
color: #196405;
font-size: large;
border-bottom:1px solid #000000;
padding: 1px;
text-align: center;
margin:0;
width: 100%;
height: 75px;
}
Any help is appreciated.
任何帮助表示赞赏。
回答by Anthony Hessler
You need to set an explicit height and width on your canvas
tag. In my experience, using CSS to set width/height of a canvas tag results in distortion of the canvas.
您需要在canvas
标签上设置明确的高度和宽度。根据我的经验,使用 CSS 设置画布标签的宽度/高度会导致画布变形。
Take a look at this question for an example of how to resize a canvas dynamically via a resize handler in JavaScript: HTML5 Canvas 100% Width Height of Viewport?
看看这个问题,看看如何通过 JavaScript 中的调整大小处理程序动态调整画布大小的示例:HTML5 Canvas 100% Width Height of Viewport?
Hope it helps!
希望能帮助到你!