gpt4 book ai didi

python - 我可以有一个带有破折号的交互式 html5 Canvas 吗?

转载 作者:行者123 更新时间:2023-12-05 05:16:33 25 4
gpt4 key购买 nike

是否可以使用带破折号的交互式 html5 Canvas ?我希望能够像康威的人生游戏一样绘制网格。让它是交互式的,我可以点击一个单元格并激活/停用它。并能够设置 Canvas 大小。谢谢

最佳答案

Note: From the wording of the question the focus seems to be on having a canvas grid with clickable cells that can be toggled on and of in Dash, so I will address this in my answer. I won't go into Conway's Game of Life here, but this answer could serve as a starting point if you wanted to implement it or a variation of it.

dash_html_components模块让我们可以访问 Canvas组件。

我们可以做的是创建一个 clientside callback它运行一次,通过它我们可以使用 Javascript 访问 DOM,因此我们可以基于 Canvas Dash 组件呈现的 canvas 元素创建网格,并将点击事件监听器附加到

Dash 应用看起来像这样:

from dash import Dash
import dash_html_components as html
from dash.dependencies import ClientsideFunction, Output, Input

app = Dash(__name__)
app.layout = html.Canvas(id="canvas")


app.clientside_callback(
ClientsideFunction(namespace="clientside", function_name="init_grid"),
Output("canvas", "children"),
Input("canvas", "children"),
)


if __name__ == "__main__":
app.run_server()

然后你可以在你的 assets 目录中添加一个 .js 文件,里面有这个:

window.dash_clientside = Object.assign({}, window.dash_clientside, {
clientside: {
init_grid: function (_) {
const canvas = document.querySelector("canvas");
canvas.width = 400;
canvas.height = 400;
const ctx = canvas.getContext("2d");
const cellWidth = 50;
const cellHeight = 50;
const numRows = canvas.height / cellHeight;
const numCols = canvas.width / cellWidth;

const drawGrid = () => {
const coordinates = [];
for (let row = 0; row < numRows; row++) {
for (let col = 0; col < numCols; col++) {
ctx.strokeRect(
col * cellWidth,
row * cellHeight,
cellWidth,
cellHeight
);
coordinates.push({ row, col, filledIn: false });
}
}
return coordinates;
};

const grid = drawGrid();

canvas.addEventListener("click", (event) => {
const clickedRow = Math.floor(event.offsetY / cellHeight);
const clickedCol = Math.floor(event.offsetX / cellWidth);

const cell = grid.filter((cell) => {
return cell.row === clickedRow && cell.col === clickedCol;
})[0];

const rectDimensions = [
clickedCol * cellWidth, // x
clickedRow * cellHeight, // y
cellWidth,
cellHeight,
];

if (!cell.filledIn) {
ctx.fillStyle = "black";
} else {
ctx.fillStyle = "white";
}

ctx.fillRect(...rectDimensions);
ctx.fillStyle = "black";
ctx.strokeRect(...rectDimensions);

cell.filledIn = !cell.filledIn;
});

return [];
},
},
});

有关在 Dash 应用程序中包含 Javascript 的更多信息,请参阅文档 here .

所以上面代码的思路是使用嵌套循环来创建网格。我们根据当前行号、列号以及我们为所有单元格设置的宽度和高度绘制矩形。

除了绘制网格外,所有的网格坐标都会被保存,这样我们就可以确定用户点击了哪个单元格,是应该填充还是清除该单元格。为了解一个单元格是否应该被清除或填充,一个 filledIn 属性被设置为所有 xy 坐标对。


结果:

grid showcase

关于python - 我可以有一个带有破折号的交互式 html5 Canvas 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50301552/

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