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

如何将可运行的canvas绘画ES5代码无损转换为ES6规范代码

ES6 转换后完整代码

JS 部分

完全保留原有绘画逻辑,仅做语法适配,同时修复原代码遗漏的语法漏洞:

// 可变状态变量 用let替换var
let flag = false
let prevX = 0
let currX = 0
let prevY = 0
let currY = 0
let dot_flag = false
// 固定宽高比 用const声明常量
const RATIO = 400 / 800
// 补全原代码缺失的画笔配置 默认值可自行调整
let strokeColor = '#000'
let lineWidth = 2

// 初始化画布
function init(fieldId) {
  const canvas = document.getElementById(`can-${fieldId}`)
  const ctx = canvas.getContext('2d')
  
  canvas.width = document.body.clientWidth < 800 ? document.body.clientWidth : 800
  canvas.height = canvas.width * RATIO

  // 补全原代码遗漏的事件绑定逻辑
  canvas.addEventListener('mousedown', (e) => findxy('down', e, canvas))
  canvas.addEventListener('mousemove', (e) => findxy('move', e, canvas))
  canvas.addEventListener('mouseup', (e) => findxy('up', e, canvas))
  canvas.addEventListener('mouseout', (e) => findxy('out', e, canvas))
}

// 绘制线条
function draw(ctx) {
  ctx.beginPath()
  ctx.moveTo(prevX, prevY)
  ctx.lineTo(currX, currY)
  ctx.strokeStyle = strokeColor
  ctx.lineWidth = lineWidth
  ctx.stroke()
  ctx.closePath()
}

// 计算坐标触发绘制
function findxy(res, e, canvas) {
  const ctx = canvas.getContext('2d')
  const rect = canvas.getBoundingClientRect()
  
  if (res === 'down') {
    prevX = currX
    prevY = currY
    currX = e.clientX - rect.left
    currY = e.clientY - rect.top

    flag = true
    dot_flag = true
    if (dot_flag) {
      ctx.beginPath()
      ctx.fillStyle = strokeColor
      ctx.fillRect(currX, currY, 2, 2)
      ctx.closePath()
      dot_flag = false
    }
  }
  if (res === 'up' || res === 'out') {
    flag = false
  }
  if (res === 'move') {
    if (flag) {
      prevX = currX
      prevY = currY
      currX = e.clientX - rect.left
      currY = e.clientY - rect.top
      draw(ctx)
    }
  }
}

// 自适应调整画布尺寸
function resizeCanvas(canvas) {
  canvas.width = document.body.clientWidth < 800 ? document.body.clientWidth : 800
  canvas.height = canvas.width * RATIO
}

CSS 部分

无功能改动,保留原逻辑:

img {
  display: none;
}

适配说明

  1. 变量声明:所有var替换为let/const,固定常量用const声明避免被误改,可变状态用let声明消除变量提升隐患
  2. 字符串拼接替换为ES6模板字符串can-${fieldId},可读性更强
  3. 补全原代码遗漏的init函数闭合逻辑、未声明的画笔配置变量、事件绑定逻辑,确保代码可正常运行
  4. 重复调用的getBoundingClientRect提取为局部变量,减少重复计算不影响原有功能
  5. 全等判断替换==为===,避免隐式类型转换带来的异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:15:03