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

Canvas无法渲染Blaze Pose关键点问题求助

解决BlazePose关键点无法在Canvas渲染的问题

针对你遇到的关键点无法显示的问题,核心原因集中在Canvas尺寸匹配、层级控制以及绘制逻辑优化上,以下是具体修复方案:

1. 修复Canvas显示尺寸与实际画布尺寸不匹配问题

你在JS中设置了Canvas的实际像素尺寸(基于视频流的真实宽高),但CSS里未同步设置Canvas的显示尺寸,导致画布被默认以300x150的尺寸拉伸显示,关键点坐标基于视频真实尺寸,会错位到可视区域外,看起来像是没显示。

修改CSS:

#output {
  position: absolute;
  z-index: 6; /* 直接固定层级,无需在JS中动态修改 */
  top: 0; 
  left: 0;
  width: 640px; /* 与video标签的宽高属性一致 */
  height: 480px;
}

#webcam {
  position: relative;
  z-index: 5; /* 确保video在Canvas下方 */
}

同时移除enableCam函数中的document.getElementById('output').style.zIndex = "6";代码,统一用CSS控制层级更稳妥。

2. 优化Canvas尺寸重置逻辑

每次调用predictWebcam时都重置Canvas宽高会清空画布并重置上下文状态,可改为仅在视频尺寸变化时更新:

修改JavaScript的predictWebcam函数:

async function predictWebcam() {
  const videoHeight = video.videoHeight;
  const videoWidth = video.videoWidth;

  // 仅当尺寸变化时更新Canvas和Video的尺寸
  if (canvas.width !== videoWidth || canvas.height !== videoHeight) {
    video.width = videoWidth;
    video.height = videoHeight;
    canvas.width = videoWidth;
    canvas.height = videoHeight;
    // 同步更新Canvas的CSS显示尺寸
    canvas.style.width = `${videoWidth}px`;
    canvas.style.height = `${videoHeight}px`;
  }

  poses = await detector.estimatePoses(video)  

  if(poses && poses.length > 0){
    for(const pose of poses){
      if(pose.keypoints != null){
        drawKeypoints(pose.keypoints);
      }
    }
  }
  window.requestAnimationFrame(predictWebcam);
}

3. 过滤低可信度关键点

BlazePose返回的关键点包含visibility属性,值低于0.5的关键点可信度极低,建议只绘制有效关键点:

修改JavaScript的drawKeypoint函数:

function drawKeypoint(keypoint){
  // 跳过可见性低的关键点
  if (keypoint.visibility < 0.5) return;
  
  ctx.fillStyle = 'Orange';
  ctx.strokeStyle = 'Green';
  ctx.lineWidth = 2;
  const radius = 4; 
  const circle = new Path2D();
  circle.arc(keypoint.x, keypoint.y, radius, 0, 2 * Math.PI)
  ctx.fill(circle)
  ctx.stroke(circle)
}

完成以上修改后,关键点应该能正常显示在Canvas上。如果仍有问题,可以在drawKeypoint中添加console.log(keypoint.x, keypoint.y),确认坐标是否落在Canvas的可视范围内。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:40:22