gpt4 book ai didi

javascript - 使用 box-sizing : border-box 将填充设置到 Canvas 容器中

转载 作者:行者123 更新时间:2023-11-28 15:55:12 25 4
gpt4 key购买 nike

我尝试将 SVG 元素插入到 Canvas 中。我想在 Canvas 内为数学方程式添加填充。

您可以在 this link 上看到没有填充的第一个结果

现在,如果我为填充取正值,则尺寸(宽度和长度)会增加。例如,填充等于 20px ,我得到以下结果:link for padding: 20px .

最后,如果我取一个更大的值 (padding: 60px),我会得到这个结果:

link for padding: 60px

您可以注意到我为“box-sizing: border-box;”放置了“<canvas width="400px" height="400px" id="textbox"></canvas>”这 3 个案例

#textbox {
position: absolute;
padding: 60px;
box-sizing: border-box;
background-color: #333333;
border: 2px solid #428bca;
z-index: 100;
}

我想在不改变 Canvas 大小的情况下为数学方程设置填充:我认为 box-sizing: border-box;可以让我得到这个结果。

谁能看出问题出在哪里?

谢谢

更新 1:

AlexK 给出的解决方案并不能准确解决我的问题。你可以看到this link在我添加数学方程式的地方,你会注意到方程式在绿色正方形内垂直和水平居中,但我想要得到的是将方程组(我的意思是从方程组的第一行开始)放在左上角绿色广场的一 Angular 。

最佳答案

设置 widthheight CSS 属性,以及它们对应的 HTML 属性。请注意,您需要保持相同的宽高比,否则图像会失真。

更新:图像也以其原始纵横比绘制,否则会被拉伸(stretch)!

var textCanvas = document.getElementById('textbox');
var contextTextBox = textCanvas.getContext('2d');

contextTextBox.fillStyle = "green";
contextTextBox.fillRect(0, 0, 400, 400);

var img = new Image;
img.onload = function() {
contextTextBox.drawImage(img, 0, 0, 378, 150);
};
img.src = "http://example.com/test_last/formulaWhite.svg";
#textbox {
position: absolute;
padding: 60px;
box-sizing: border-box;
background-color: #333333;
border: 2px solid #428bca;
z-index: 100;
height: 400px;
width: 400px;
}
#containerCanvas {
position: relative;
top: 0;
left: 0;
margin: 20px;
}
<div id="containerCanvas">
<canvas width="400" height="400" id="textbox"></canvas>
</div>

HTML heightwidth 属性控制绘图空间的分辨率 - 它们允许您在绘图中容纳更多或更少的内容区域。 CSS 尺寸将缩放 Canvas 以在屏幕上占据一定量的空间。

这是一个具有更多“绘图区域”但在屏幕上占据相同 400x400 像素的示例。

var textCanvas = document.getElementById('textbox');
var contextTextBox = textCanvas.getContext('2d');

contextTextBox.fillStyle = "green";
contextTextBox.fillRect(0, 0, 756, 756);

var img = new Image;
img.onload = function() {
contextTextBox.drawImage(img, 0, 0, 378, 150);
contextTextBox.drawImage(img, 378, 0, 378, 150);
contextTextBox.drawImage(img, 0, 150, 378, 150);
contextTextBox.drawImage(img, 378, 150, 378, 150);
};
img.src = "http://example.com/test_last/formulaWhite.svg";
#textbox {
position: absolute;
padding: 0;
box-sizing: border-box;
background-color: #333333;
border: 2px solid #428bca;
z-index: 100;
width: 400px;
height: 400px;
padding: 60px;
}

#containerCanvas {
position: relative;
top: 0;
left: 0;
margin: 20px;
}
<div id="containerCanvas">
<canvas width="756" height="756" id="textbox"></canvas>
</div>

关于javascript - 使用 box-sizing : border-box 将填充设置到 Canvas 容器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41272621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com