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

Canvas动画无法绘制线条,请求排查HTML/JS代码问题

问题排查:Canvas无法绘制随机线条

核心问题

你代码里的线条起点和终点用了完全相同的坐标:

context.moveTo(horPos, verPos);
context.lineTo(horPos, verPos);

Canvas的stroke()方法只会渲染有长度的路径,当起点和终点重合时,不会显示任何内容——这就是你看不到线条的根本原因。

其他需要修正的细节

  • 全局变量notRunning未声明,建议用let声明避免污染全局作用域
  • CSS中width: 100 vw;存在空格,应改为100vw
  • HTML中容器div的属性错误,<div container3>需改为<div id="container3">
  • 每次执行discoShow()都重新获取canvas和context,可提前获取一次提升性能

修正后的完整代码

HTML

<div id="container3">
  <div id="canvasDiv">
    <button id="startShow" class="aniButton">Start animation</button>
    <button id="stopShow" class="aniButton">Stop animation</button>
    <canvas id="animationDisplay" width="400" height="400"></canvas>
    <p id="displayColor"></p>
  </div>
</div>

CSS

#container3 {
  width: 100vw;
}

#canvasDiv {
  width: 500px;
  margin: 10px auto;
  text-align: center;
  z-index: 10;
}

#animationDisplay {
  border: 1px dashed black;
  margin: 0 auto;
}

.aniButton {
  width: 60px;
  margin: 0 10px;
}

JavaScript

let notRunning = true;
// 提前获取canvas和context,避免重复DOM查询
const canvas = document.getElementById("animationDisplay");
const context = canvas.getContext("2d");
const colorDisplay = document.getElementById("displayColor");

function randomColor() {
  const letters = "0123456789ABCDEF".split('');
  let color = "#";
  // 用let声明循环变量i,避免全局污染
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}

function discoShow() {
  // 生成独立的起点和终点坐标
  const startX = Math.floor(Math.random() * 400);
  const startY = Math.floor(Math.random() * 400);
  const endX = Math.floor(Math.random() * 400);
  const endY = Math.floor(Math.random() * 400);
  const theColor = randomColor();

  context.lineWidth = 10;
  context.strokeStyle = theColor;

  context.beginPath();
  context.moveTo(startX, startY);
  context.lineTo(endX, endY);
  context.stroke();

  console.log(`起点: (${startX}, ${startY}),终点: (${endX}, ${endY})`);
  colorDisplay.textContent = theColor;
}

let animation;

document.getElementById("startShow").onclick = function() {
  if (notRunning) {
    animation = setInterval(discoShow, 100);
    discoShow();
    notRunning = false;
  } else {
    alert("Sorry, already running!");
  }
}

document.getElementById("stopShow").onclick = function() {
  clearInterval(animation);
  notRunning = true;
}

修正说明

  • 生成独立的起点和终点坐标,确保路径有长度,stroke()能正常渲染线条
  • 提前获取DOM元素和canvas上下文,减少重复查询的性能开销
  • 修复了变量声明、CSS和HTML的语法错误
  • 优化了console日志的可读性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:55:18