js绘制平面直角坐标系并绘制图片加刻度显示
时间: 2023-08-02 08:05:44 浏览: 49
以下是一个简单的示例代码,使用Canvas绘制平面直角坐标系并添加图片和刻度:
```html
<!DOCTYPE html>
<html>
<head>
<title>绘制平面直角坐标系</title>
</head>
<body>
<canvas id="myCanvas" width="400" height="400"></canvas>
<script>
// 获取canvas元素
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
// 绘制坐标系
function drawCoordinate() {
// 设置线条颜色
ctx.strokeStyle = "#000000";
// 绘制x轴
ctx.beginPath();
ctx.moveTo(0, canvas.height / 2);
ctx.lineTo(canvas.width, canvas.height / 2);
ctx.stroke();
// 绘制y轴
ctx.beginPath();
ctx.moveTo(canvas.width / 2, 0);
ctx.lineTo(canvas.width / 2, canvas.height);
ctx.stroke();
// 绘制x轴刻度
for (var i = -10; i <= 10; i++) {
ctx.beginPath();
ctx.moveTo(canvas.width / 2 + i * 20, canvas.height / 2 - 5);
ctx.lineTo(canvas.width / 2 + i * 20, canvas.height / 2 + 5);
ctx.stroke();
}
// 绘制y轴刻度
for (var i = -10; i <= 10; i++) {
ctx.beginPath();
ctx.moveTo(canvas.width / 2 - 5, canvas.height / 2 - i * 20);
ctx.lineTo(canvas.width / 2 + 5, canvas.height / 2 - i * 20);
ctx.stroke();
}
}
// 加载图片并绘制
var img = new Image();
img.onload = function() {
ctx.drawImage(img, canvas.width / 2 - img.width / 2, canvas.height / 2 - img.height / 2);
drawCoordinate();
}
img.src = "https://picsum.photos/id/237/200/300";
</script>
</body>
</html>
```
这个示例代码绘制了一个400x400的平面直角坐标系,坐标原点位于canvas中心,x轴和y轴各绘制了-10到10之间的刻度。同时,加载了一张随机图片并将其居中绘制在坐标系上方。你可以根据实际需求修改坐标系、刻度和图片的大小、位置和样式。