需求:canvas画布上画六边形
使用HTML5 Canvas原生方法是对context(代表整个画布位图的对象)进行操作,而使用Fabric.js,我们是对对象操作,只需要去实例化对象,设置对象的属性,然后将它们添加到canvas中。
参考文章
一、HTML5 Canvas
onMounted(()=>{
//组件加载后绘制六角格形状
if (hexCanvas.value) {
drawHexagon(hexCanvas.value);
}
})
// 引用canvas画六边形
const hexCanvas = ref()
function drawHexagon(canvas: HTMLCanvasElement) {
const ctx = canvas.getContext('2d');
if (!ctx) return;
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制竖直六角格
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
// 确保六边形的高不超过画布的高度
let height = Math.min(canvas.width, canvas.height);
if (canvas.width > canvas.height) {
// 如果画布更宽,则六边形高度为画布高度
height = canvas.height;
} else {
// 如果画布更高,则按正六边形高比宽为2:sqrt(3)计算
height = canvas.width * (Math.sqrt(3) / 2);
}
// 六边形半宽
const halfWidth = (height * Math.sqrt(3)) / 4;
// 计算起始角度(从上开始)
const startAngle = -Math.PI / 2;
// 绘制竖直六角格
ctx.beginPath();
for (let i = 0; i < 6; i++) {
// 使用角度来计算每个顶点的位置
const angle = startAngle + i * (Math.PI / 3);
const x = centerX + halfWidth * Math.cos(angle);
const y = centerY + halfWidth * Math.sin(angle);
// 确保顶点在画布内
if (x >= 0 && x <= canvas.width && y >= 0 && y <= canvas.height) {
ctx.lineTo(x, y);
}
}
ctx.closePath();
// 设置样式
ctx.strokeStyle = 'black';
ctx.lineWidth = 2;
ctx.fillStyle = 'lightgray';
ctx.stroke();
ctx.fill();
}
二、Fabric.js
onMounted(() => {
const canvas = new fabric.Canvas(hexCanvas.value);
drawHexagon(canvas);
})
// 引用canvas画六边形
const hexCanvas = ref()
function drawHexagon(canvas: fabric.Canvas) {
// 让六边形占据画布的中心
const centerX = canvas.width / 2;
const centerY = canvas.height / 2;
// 确保六边形的高不超过画布的高度
let height = Math.min(canvas.width, canvas.height);
if (canvas.width > canvas.height) {
// 如果画布更宽,则六边形高度为画布高度
height = canvas.height;
} else {
// 如果画布更高,则按正六边形高比宽为2:sqrt(3)计算
height = canvas.width * (Math.sqrt(3) / 2);
}
// 六边形半宽
const halfWidth = (height * Math.sqrt(3)) / 4;
// 创建一个包含六边形顶点坐标的数组
const points = [];
const startAngle = -Math.PI / 2; // 从顶部开始
for (let i = 0; i < 6; i++) {
// 使用角度来计算每个顶点的位置
const angle = startAngle + i * (Math.PI / 3);
const x = centerX + halfWidth * Math.cos(angle);
const y = centerY + halfWidth * Math.sin(angle);
points.push({ x: x, y: y });
}
// 创建一个 Polygon 对象
const hexagon = new fabric.Polygon(points, {
fill: '#b9c099', // 设置填充颜色
originX: 'center', // 围绕中心缩放和旋转
originY: 'center'
});
// 添加六边形到画布上
canvas.add(hexagon);
// 渲染画布上的所有对象
canvas.renderAll();
}
<div class="contain">
<canvas ref="hexCanvas" width="100" height="100"></canvas>
</div>
.contain{
color: white;
font-size: 14px;
overflow: hidden;
width: 50%;
height: 85%;
float: left;
background: #19ADE5FF;
}
.containcanvas {
border: 1px solid #ccc;
}