Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js 画布

作者:惨美歌   发布日期:2026-05-01   浏览:112

// HTML部分
<canvas id="myCanvas" width="500" height="500"></canvas>

// JavaScript部分
<script>
  // 获取画布元素
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');

  // 设置矩形的填充颜色
  ctx.fillStyle = 'blue';

  // 绘制一个矩形
  ctx.fillRect(50, 50, 200, 100);

  // 设置线条的颜色和宽度
  ctx.strokeStyle = 'red';
  ctx.lineWidth = 5;

  // 开始绘制路径
  ctx.beginPath();

  // 移动到起始点
  ctx.moveTo(300, 50);

  // 绘制一条线到终点
  ctx.lineTo(450, 150);

  // 关闭路径并描边
  ctx.closePath();
  ctx.stroke();

  // 绘制圆形
  ctx.beginPath();
  ctx.arc(250, 250, 50, 0, Math.PI * 2);
  ctx.fillStyle = 'green';
  ctx.fill();
  ctx.closePath();
</script>

解释说明:

  1. HTML部分:定义了一个 <canvas> 元素,用于绘制图形。widthheight 属性指定了画布的尺寸。
  2. JavaScript部分
    • 使用 getElementById 获取画布元素,并通过 getContext('2d') 获取 2D 绘图上下文对象 ctx
    • 使用 fillStyle 设置填充颜色,fillRect 方法绘制一个矩形。
    • 使用 strokeStylelineWidth 设置线条的颜色和宽度,beginPathmoveTolineTostroke 方法绘制一条直线。
    • 使用 arc 方法绘制一个圆形,fill 方法填充圆形。

如果你需要更复杂的绘图功能,可以继续使用 CanvasRenderingContext2D 提供的其他方法。

上一篇:js trimend

下一篇:js touppercase()的用法

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站