javascript - 根据json数据创建画布框
问题描述
我想根据 json 数据的宽度和高度制作一个盒子。但是我的盒子已经是这样了。请问如何根据json数据的宽度和高度制作水平多重框?而不是像这样创建ctx.rect(20, 21, 100, 100);
您可以在此处访问代码: https ://codesandbox.io/s/reverent-galois-nlp8g?file=/index.html
这是代码:
<canvas id="NodeList" width="900" height="2000"></canvas>
<script>
var data = [{
"name": "1",
"x": 225,
"y": 197,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2,
"version": "1.0.0"
},
{
"name": "2",
"x": 225,
"y": 297,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2
},
{
"name": "3",
"x": 225,
"y": 397,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2
},
{
"name": "4",
"x": 225,
"y": 497,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2
},
{
"name": "5",
"x": 225,
"y": 597,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2
}
];
var c = document.getElementById("NodeList");
var ctx = c.getContext("2d");
// for diagonal
ctx.rect(20, 21, 100, 100);
ctx.fillText(data[0].name, 25, 35);
// end
// for horizontal box
ctx.rect(127, 21, 100, 100);
ctx.fillText(data[0].name, 25, 35);
ctx.rect(234, 21, 100, 100);
ctx.rect(341, 21, 100, 100);
//end
ctx.stroke();
</script>
解决方案
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<canvas id="NodeList" width="900" height="2000"></canvas>
</body>
</html>
<script>
var data = [{
"name": "1",
"x": 225,
"y": 197,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2,
"version": "1.0.0"
},
{
"name": "2",
"x": 225,
"y": 297,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2
},
{
"name": "3",
"x": 225,
"y": 397,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2
},
{
"name": "4",
"x": 225,
"y": 497,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2
},
{
"name": "5",
"x": 225,
"y": 597,
"width": 121,
"height": 67,
"bgColor": "#00FF00",
"radius": 2
}
];
var c = document.getElementById("NodeList");
var ctx = c.getContext("2d");
ctx.strokeStyle = "black";
for (let i = 0; i < data.length; i++) { // loop through the data array
const _data = data[i];
ctx.beginPath(); // Call beginPath before drawing any shape
ctx.rect(_data.x, _data.y, _data.width, _data.height);
ctx.fillText(_data.name, _data.x + 10, _data.y + 10); // +10 means the offset
ctx.stroke();
}
</script>
推荐阅读
- android - 改造返回 200 响应代码,但我在访问字段时收到 null
- node.js - 如何使用自定义消息设置 Joi 验证?
- firebase - 如何在不使用 Firebase 控制台的情况下使用 FCM 在 Flutter 应用中触发推送通知?
- javascript - React 加载图片并在组件中动态显示
- c++ - 在本地机器和在线 IDE 中获取分段错误非常适合动态编程解决方案
- android - 使用 Map 值、Flutter 查询 Firebase
- reactjs - React Material UI TextField FormHelperTextProps 样式不起作用
- android - 使用底部导航删除 ConstraintLayout 中的上边距
- c# - 实体框架(Web API)中的 System.Data.SqlClient.SqlException
- ruby-on-rails - 导轨中的引导轮播 6