已经完成的异型图
1、带倒角的矩形 2、带箭头的直线
效果图
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<canvas id='container' width="500" height="500" style="border:1px solid #30f">您的浏览器不支持 HTML5 canvas 标签</canvas>
</body>
<script>
const canvas = document.getElementById('container');
const context = canvas.getContext("2d");
// 边框
strokeRoundRect(context, 100, 200);
fillRoundRect(context, 300, 200);
drawLineTriangle(context, 100 + 120, 200 + 25, 300, 200 + 25)
drawLineTriangle(context, 100 + 60, 200 + 50, 100 + 60, 300)
drawLineTriangle(context, 300 + 60, 200 + 50, 100 + 60, 300)
fillRoundRect(context, 100, 300);
// 直线
function drawLineTriangle(ctx, startX, startY, endX, endY) {
ctx.save();
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(endX, endY);
ctx.strokeStyle = '#C0C5CF';
ctx.lineWidth = 1;
ctx.stroke();
ctx.restore();
const atan = Math.atan((startY - endY) / (startX - endX));
const radians = atan + ((startX >= endX ? -90 : 90) * Math.PI) / 180;
drawTriangle(ctx, endX, endY, radians)
}
//渲染文字
function drawText(ctx, x, y, text, font, fillColor) {
ctx.save();
//ctx.beginPath();
ctx.translate(x, y);
ctx.font = font || 'normal 12px PingFangSC-Regular';
ctx.fillStyle = fillColor || '#4E4E4E';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text || '', 60, 25);
ctx.restore();
}
// 三角形
function drawTriangle(ctx, x, y, radians) {
ctx.save();
ctx.beginPath();
ctx.translate(x, y);
ctx.rotate(radians);
ctx.moveTo(0, 0);
ctx.lineTo(4, 8);
ctx.lineTo(-4, 8);
ctx.closePath();
ctx.fillStyle = '#C0C5CF';
ctx.lineWidth = 1;
ctx.fill();
ctx.restore();
}
//填充圆角
function fillRoundRect(ctx, x, y) {
ctx.save();
ctx.beginPath();
ctx.translate(x, y);
drawRoundRectPath(ctx, 120, 50, 10);
ctx.fillStyle = '#ff6420'
ctx.fill();
ctx.restore();
drawText(ctx, x, y, '这是测试')
}
// 边框
function strokeRoundRect(ctx, x, y) {
// x,y偏移量
ctx.save();
ctx.beginPath();
ctx.translate(x, y);
//绘制圆角矩形的各个边
drawRoundRectPath(ctx, 120, 50, 10);
ctx.lineWidth = 1;
ctx.strokeStyle = "#f00";
ctx.stroke();
ctx.restore();
drawText(ctx, x, y, '文字')
}
function drawRoundRectPath(ctx, w, h, r) {
// w:宽,h表示高,r表示半径
ctx.beginPath();
//左上圆角
ctx.arc(r, r, r, Math.PI, Math.PI * 3 / 2);
// 上边线
ctx.lineTo(w - r, 0);
// 又上圆角
ctx.arc(w - r, r, r, Math.PI * 3 / 2, Math.PI * 2);
// 右侧边线
ctx.lineTo(w, h - r);
// 右下圆角
ctx.arc(w - r, h - r, r, 0, Math.PI / 2);
// 下边线
ctx.lineTo(r, h);
// 下左圆角
ctx.arc(r, h - r, r, Math.PI / 2, Math.PI);
// 左侧边线
ctx.lineTo(0, r);
}
</script>
</html>