gpt4 book ai didi

javascript - 从输入中绘制多个 Canvas 并计算如何对齐它们

转载 作者:行者123 更新时间:2023-11-28 00:16:31 33 4
gpt4 key购买 nike

一个小元素在以下地址:PLEASE CLICK HERE

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

当前成功绘制一个矩形的 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 ;)
});

关于javascript - 从输入中绘制多个 Canvas 并计算如何对齐它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55078786/

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