简体   繁体   中英

ASP.NET Render HTML5 Canvas from MVC Model Data

I am using ASP.NET Core 2.0. How can I draw on an HTML5 Canvas using data from a model? I want to loop through records in my model.

public IEnumerable<BodyPain> painRecs;

I tried the following code in my Razor View:

<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);** produces the following output:

[{"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}]

But **alert(pr.painType);** causes error UNDEFINED .

Finally got it working with this syntax:

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM