首页 > 解决方案 > 从输入中绘制多个画布并计算如何对齐它们

问题描述

一个小项目位于以下地址:请点击这里

计划是根据用户输入(宽度、高度、颜色)在画布中绘制多个矩形,并将它们对齐在下面的字段中,并尽可能地占用更小的区域。字段是网格预览。

当前成功绘制一个矩形的 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,也不确定如何在每个重复字段中加载它。

如果需要任何其他信息,请告诉我。所有代码都可以通过提到的链接在源文件中看到。

谢谢。

标签: javascripthtmlcss

解决方案


一个简单的答案可能是将用户输入存储在对象数组中(例如 [{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 ;)
});

推荐阅读