我使用此代码从 .json 文件加载行描述并在 Canvas 上绘制描述的行:
<html>
<head>
<script type="text/javascript" src="jQuery.js"> </script>
<script type="text/javascript">
var canvas;
var context;
function Line(x1, y1, x2, y2, color)
{
canvas = document.getElementById("canvas_1");
context = canvas.getContext("2d");
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.color = color;
}
Line.prototype.draw = function() {
context.beginPath();
context.moveTo(this.x1, this.y1);
context.lineTo(this.x2, this.y2);
context.strokeStyle = this.color;
context.stroke();
}
onload=function simpleExample()
{
$(document).ready(function()
{
// draw line with cordinates read from points.json file
$.getJSON('points.json', function(data)
{
var line = new Line(data.line.point1.x, data.line.point1.y, data.line.point2.x, data.line.point2.y, data.line.color);
line.draw(context);
});
});
}
</script>
<head>
<body>
<canvas height="500" width="500" id="canvas_1"></canvas>
</body>
</html>`
我的 points.json 文件如下所示:
{
"line": {
"point1": {
"x": "50",
"y": "50"
},
"point2": {
"x": "100",
"y": "100"
},
"color": "red"
}
}
现在我想添加在 Canvas 上移动这条线的能力,但我现在不知道如何。我需要建议,因为我的任务是从 .json 文件加载行描述并在 Canvas 上绘制该行(它不必像我那样用 jQuery 加载,如果有人知道其他方法,请写一些如何做到这一点的例子)。
谢谢,亚历山大