javascript - ASP.NET 从 MVC 模型数据渲染 HTML5 画布
问题描述
我正在使用 ASP.NET Core 2.0。如何使用模型中的数据在 HTML5 Canvas 上绘图?我想遍历模型中的记录。
public IEnumerable<BodyPain> painRecs;
我在 Razor 视图中尝试了以下代码:
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var data = '@Html.Raw(Json.Serialize(Model.painRecs))';
alert(data);
//console.log(data);
for (b = 0; b < data.length; b++) {
var pr = data[b];
alert(pr.painType);
ctx.beginPath();
ctx.arc(pr.xPos, pr.yPos, 8, 0, 2 * Math.PI);
ctx.fillStyle = "#DC143C";
ctx.fill();
}
</script>
**alert(data);**
产生以下输出:
[{"memberID":9048,"painID":6880,"painScale":1,"painType":4,"xPos":497.333344,"yPos":385.333344}
,{"memberID":9048,"painID":6888,"painScale":1,"painType":4,"xPos":313.333344,"yPos":428.0}]
但是**alert(pr.painType);** causes error UNDEFINED
。
解决方案
最后让它使用这种语法:
function displayPainRecs() {
try {
var x = 0;
var y = 0;
var cvs = document.getElementById('myCanvas');
var ctx = cvs.getContext('2d');
var data = @Html.Raw(Json.Serialize(Model.painRecs));
for (i = 0; i < data.length; i++) {
var pr = data[i];
x = pr["xPos"].toFixed(0);
y = pr["yPos"].toFixed(0);
ctx.beginPath();
ctx.arc(x, y, 8, 0, 2 * Math.PI);
ctx.fillStyle = "#DC143C";
if (pr["painType"] == 1) {
ctx.fillStyle = "#DC143C";
}
else if (pr["painType"] == 2) {
ctx.fillStyle = "#EA728A";
}
ctx.fill();
}
}
catch (err) {
alert(err);
}
}
推荐阅读
- postgresql - PostgreSQL:在数据库重新启动时,为什么启动序列号不可预测?
- regex - 正则表达式不适用于可选()?句子
- docker-compose - 在 gitlab-ci.yml 中使用来自 docker-compose 的容器
- c# - 在 BuildServiceProvider 之前访问服务
- java - Jackson - 使用 JsonTypeInfo.DEDUCTION 反序列化时出现 java.lang.EnumConstantNotPresentException
- android - 在库 Kotlin Android 中找不到提供程序的元数据
- php - 我在 woocommerce 高级订单导出 (CSV) 中的每个 woocommerce 订单后添加文本行时遇到问题
- node.js - 当内容类型为“multipart/form-data”时更改 axios 请求标头的默认字符集
- javascript - 对于每个选项不同的选择 [formControl]
- android - ftp4j - 连接过多异常