初面网初面网

线

// 1、创建画布
const canvas = document.createElement('canvas');

canvas.width = 600;
canvas.height = 400;
document.body.append(canvas);

// 2、获取画笔
const ctx = canvas.getContext('2d');

// 3、画线
ctx.moveTo(100,100);  // 移动画笔到x,y为100,100的位置
ctx.lineTo(300,300);  // 画线到300,300的位置
ctx.stroke(); // 绘制出来,使图像可见

// 请在stoke之前处理好所有内容然后再绘制出来,否则stroke后没有其他处理的话,效果不会生效

连续路径

实际上lineTo可以连续使用,成为一个路径

// 其他省略
ctx.moveTo(0,0);
ctx.lineTo(100,100);
ctx.lineTo(200,0);
ctx.lineTo(300,300);
ctx.lineTo(400,0);
ctx.stroke();

设置线条宽度

ctx.lineWidth = 10; // 全局的

设置颜色

ctx.strokeStyle = '#f00';

两个图形

如果是声明两个图形,需要beginPath()和closePath()。这两个函数需要成对出现。

// 1、创建画布
const canvas = document.createElement('canvas');

canvas.width = 1920;
canvas.height = 1080;
document.body.append(canvas);
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();

ctx.beginPath();

ctx.arc(200, 175, 50, 0, 2 * Math.PI);
ctx.stroke();
ctx.closePath();

闭合并填充

fill

ctx.arc(300,200,100,0,180*Math.PI/180);

// ctx.fillStyle = '#0a0'; // 单色填充
const g = ctx.createLinearGradient(0,0,600,600);
g.addColorStop(0, 'yellow');
g.addColorStop(1, 'red');
ctx.fillStyle = g;
ctx.fill(); // 默认黑色

更新于 2025/2/26