效果
场景
根据坐标点使用canvas在画布上展示出来
html
<canvas ref="canvasImg" class="canvasImg" style="margin-top: 20px">
浏览器版本过低,请去下载最新版本浏览器
</canvas>
data数据
coordinates: [{x: 100, y: 50, }, { x: 100, y: -50, }, {x: -50, y: 50, }, { x: -50,y: -50, }, ],
绘制
created() {
this.$nextTick(() => {
this.canvas = this.$refs.canvasImg;
this.ctx = this.canvas.getContext("2d");
this.canvas.width = 880;
this.canvas.height = 460;
//设置canvas中心点
this.ctx.translate(0.5 * this.canvas.width, 0.5 * this.canvas.height);
// 原先y轴是向下的,现在改为向上
this.ctx.scale(1, -1);
});
},
mounted() {
this.getPoints();
},
created:{
getPoints() {
this.coordinates.forEach((item) => {
this.loadPoint(item, "#FF5562FF");
});
},
}
//画点方法
loadPoint(point, color) {
this.$nextTick(() => {
this.ctx.save();
this.ctx.beginPath();
this.ctx.arc(point.x, point.y, 2, 0, 2 * Math.PI, false); //更改点大小
this.ctx.fillStyle = color;
this.ctx.fill();
this.ctx.restore();
});
},
摘抄好文
canvas一开始的坐标系是这样的。
有时候为了方便可以,将起始点放在canvas中间,然后将y轴的方向改为向上:
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// 原来坐标系的起点在canvas的左上角(0, 0),现在将起点定在(128, 128)这个点上
ctx.translate(128, 128);
// 原先y轴是向下的,现在改为向上
ctx.scale(1, -1);
摘抄部分来源于:
https://blog.youkuaiyun.com/qq_34086980/article/details/110288051