You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过读取JSON在HTML5 Canvas上动态绘制矩形

在HTML5 Canvas实现矩形动态绘制

我已经能在HTML5 Canvas上绘制基础矩形,现在需要实现动态绘制功能。

参数说明

  • x、y:矩形在Canvas元素中的位置坐标
  • w:矩形宽度
  • h:矩形高度
  • f:若为true,矩形填充无边框;若为false,矩形有边框无填充

基础绘制代码修正

你提供的基础代码存在问题:lineTo()方法仅用于绘制直线,无法直接创建矩形。正确的做法是根据f参数选择使用fillRect()(填充矩形)或strokeRect()(描边矩形),同时注意将字符串类型的坐标参数转为数值:

JavaScript代码

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
// 设置Canvas尺寸,避免拉伸变形
canvas.width = 300;
canvas.height = 300;

var rects = [
    { "x": 50, "y": 50, "w": 100, "h": 50, "f": true },
    { "x": 50, "y": 150, "w": 100, "h": 50, "f": false }
];

// 批量绘制矩形的函数
function drawRects() {
    // 清空画布
    context.clearRect(0, 0, canvas.width, canvas.height);
    rects.forEach(rect => {
        const x = Number(rect.x);
        const y = Number(rect.y);
        const w = Number(rect.w);
        const h = Number(rect.h);
        const needFill = rect.f === true || rect.f === "true";
        
        if (needFill) {
            context.fillRect(x, y, w, h);
        } else {
            context.strokeRect(x, y, w, h);
        }
    });
}

// 初始绘制
drawRects();

HTML代码

<canvas id="c" style="border: 1px solid #ccc;"></canvas>

动态绘制实现方案

下面提供两种常见的动态绘制场景:

场景1:鼠标拖拽绘制矩形

通过监听鼠标事件,实现拖拽过程中实时绘制矩形:

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 400;
canvas.style.border = "1px solid #ccc";

let isDrawing = false;
let startX, startY;

// 鼠标按下:记录起始点
canvas.addEventListener("mousedown", (e) => {
    isDrawing = true;
    const canvasRect = canvas.getBoundingClientRect();
    startX = e.clientX - canvasRect.left;
    startY = e.clientY - canvasRect.top;
});

// 鼠标移动:实时绘制临时矩形
canvas.addEventListener("mousemove", (e) => {
    if (!isDrawing) return;
    const canvasRect = canvas.getBoundingClientRect();
    const currentX = e.clientX - canvasRect.left;
    const currentY = e.clientY - canvasRect.top;
    
    context.clearRect(0, 0, canvas.width, canvas.height);
    const width = currentX - startX;
    const height = currentY - startY;
    // 这里默认绘制描边矩形,如需填充可替换为fillRect
    context.strokeRect(startX, startY, width, height);
});

// 鼠标松开:结束绘制,可将矩形参数存入数组保存
canvas.addEventListener("mouseup", () => {
    isDrawing = false;
});

场景2:定时自动添加矩形

实现每隔一段时间自动生成随机矩形并绘制到画布:

var canvas = document.getElementById("c");
var context = canvas.getContext("2d");
canvas.width = 600;
canvas.height = 400;
canvas.style.border = "1px solid #ccc";

let rects = [];

// 生成随机矩形参数
function createRandomRect() {
    return {
        x: Math.random() * (canvas.width - 100),
        y: Math.random() * (canvas.height - 50),
        w: 50 + Math.random() * 100,
        h: 30 + Math.random() * 70,
        f: Math.random() > 0.5 // 50%概率填充或描边
    };
}

// 绘制所有矩形
function drawRects() {
    context.clearRect(0, 0, canvas.width, canvas.height);
    rects.forEach(rect => {
        rect.f ? context.fillRect(rect.x, rect.y, rect.w, rect.h) : context.strokeRect(rect.x, rect.y, rect.w, rect.h);
    });
}

// 每隔2秒添加一个新矩形
setInterval(() => {
    rects.push(createRandomRect());
    drawRects();
}, 2000);

内容的提问来源于stack exchange,提问作者Jenni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 12:55:25