本文主要是介绍HTML5 Canvas与Fabric.js画自定义六边形,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
需求: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;
}
这篇关于HTML5 Canvas与Fabric.js画自定义六边形的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!