渐变示例哪儿好像是根据整个画布创建的渐变,所以在定位的时候渐变和径向的颜色填充是没达到预期效果,期待大佬们可以教我一些好方法?非常感谢!
<body>
<canvas id="canvas" width="1200" height="800"></canvas>
<script>
let cav = document.querySelector("#canvas");
let ctx = cav.getContext("2d");
// 使用线画一个你想要的简易形状,五角星
ctx.beginPath();
// ctx.lineWidth = 10;
ctx.moveTo(360, 60);
ctx.lineTo(320, 180);
ctx.lineTo(180, 180);
ctx.lineTo(310, 240);
ctx.lineTo(270, 360);
ctx.lineTo(360, 270);
ctx.lineTo(440, 360);
ctx.lineTo(410, 240);
ctx.lineTo(540, 180);
ctx.lineTo(400, 180);
ctx.lineTo(360, 60);
ctx.stroke();
// 矩形
ctx.beginPath();
// ctx.rect(x, y, width, height)
ctx.lineWidth = 10;
ctx.strokeStyle = "#ccc";
ctx.rect(150, 30, 420, 360);
ctx.stroke();
// 圆
ctx.beginPath();
// arc(x,y,r,start,end)
ctx.arc(720, 160, 100, 0, 2 * Math.PI);
ctx.stroke();
// 曲线 使用圆的方法,传的参数不一样
// 上半圆
ctx.beginPath();
ctx.arc(900, 160, 50, 1.1 * Math.PI, 1.9 * Math.PI);
ctx.stroke();
// 下半圆
ctx.beginPath();
ctx.arc(900, 160, 50, 0.1 * Math.PI, 0.9 * Math.PI);
ctx.stroke();
// 线性渐变 createLinearGradient(x,y,x1,y1)
const grds = ctx.createLinearGradient(0, 0, 150, 0); // 创建
grds.addColorStop(0, "red"); // 添加颜色
grds.addColorStop(1, "yellow");
ctx.fillStyle = grds;
ctx.fillRect(60, 400, 150, 100);
// 径向渐变 createRadialGradient(x,y,r,x1,y1,r1)
const grd = ctx.createRadialGradient(60, 520, 5, 60, 520, 100); // 创建
grd.addColorStop(0, "red"); // 添加颜色
grd.addColorStop(1, "yellow");
ctx.fillStyle = grd;
ctx.fillRect(60, 520, 150, 100);
// 文字字体
ctx.font = "30px 黑体";
ctx.fillStyle = "red";
ctx.fillText("Hello canvas", 300, 500);
ctx.font = "30px 黑体";
ctx.textAlign = "center";
ctx.fillText("Hello canvas", canvas.width / 2, canvas.height / 1.5);
</script>
整体示例效果