javascript - 从输入中绘制多个画布并计算如何对齐它们
问题描述
一个小项目位于以下地址:请点击这里
计划是根据用户输入(宽度、高度、颜色)在画布中绘制多个矩形,并将它们对齐在下面的字段中,并尽可能地占用更小的区域。字段是网格预览。
当前成功绘制一个矩形的 JavaScript 是:
var canvas = document.getElementById('canvasgrid');
canvas.width = 855;
canvas.height = 500;
var context = canvas.getContext('2d');
function draw(){
var x = document.getElementById("width").value;
var y = document.getElementById("height").value;
var boja = document.getElementById("color").value;
var arr = [x,y,boja];
let pos = {x: 0, y: 0};
arr.forEach(p => {
context.rect(pos.x, pos.y, p.w, p.h);
pos.x += p.w; // should return to zero at the edge of the canvas
pos.y += p.h;
context.beginPath();
context.stroke();
context.fillStyle = boja;
context.fill();
context.fillStyle = "white";
context.font="bold 10px sans-serif";
context.textAlign="center";
context.textBaseline = "middle";
context.fillText(x+'x'+y, 10+(x/2),10+(y/2));
});
}
在用户单击绿色按钮后,我确实在加载其他输入时遇到问题。我使用的彩色 JavaScript 插件是jsoclor,也不确定如何在每个重复字段中加载它。
如果需要任何其他信息,请告诉我。所有代码都可以通过提到的链接在源文件中看到。
谢谢。
解决方案
一个简单的答案可能是将用户输入存储在对象数组中(例如 [{w: ..., h: ..., color: ...}, {...}...])并迭代在你的功能中。
在您的函数中,您可能会有以下内容:
let pos = {x: 0, y: 0};
arr.forEach(p => {
context.rect(pos.x, pos.y, p.w, p.h);
pos.x += p.w; // should return to zero at the edge of the canvas
//pos.y += left as an exercise to the reader ;)
});
推荐阅读
- font-awesome-5 - FontAwesome with JS Kit ::before 伪类不起作用?
- sql - 如何针对以下条件编写 SQL 查询?
- javascript - 如何将 PDF 文档上的缩放事件与 Angular 6 中的函数绑定?
- asp.net-core-2.0 - Asp.Net Core:如何正确地将数据从视图传递到控制器?
- javascript - 使用 JavaScript 的搜索栏中的词序
- node.js - 如何使用 Material-UI 创建 onSubmit
- apache-kafka - 如何将消息类型绑定到单个消费者组上的 Kafka 消费者?
- rabbitmq - 如果已经存在,RabbitMQ 是否创建队列/交换?
- spring-boot - 结合 oauth2+jwt 配置多个身份验证提供程序
- node.js - 在此示例中,如何使用 docker-compose 允许 2 个容器正确共享 .sock 文件?