以下是一个简单的示例代码,使用JavaScript给上传的图片添加编号:

HTML代码:

<input type="file" id="fileInput">
<button onclick="upload()">上传图片</button>

JavaScript代码:

let currentNum = 1; // 当前编号

function upload() {
  const fileInput = document.getElementById('fileInput');
  const file = fileInput.files[0];
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function () {
    const img = new Image();
    img.src = reader.result;
    img.onload = function () {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      canvas.width = img.width;
      canvas.height = img.height;
      ctx.drawImage(img, 0, 0);
      ctx.font = '36px Arial';
      ctx.fillStyle = 'red';
      ctx.fillText(`#${currentNum}`, 10, 50); // 在左上角添加编号
      currentNum++; // 编号自增
      const newImg = new Image();
      newImg.src = canvas.toDataURL('image/png');
      document.body.appendChild(newImg); // 在页面中显示添加编号后的图片
    };
  };
}

上述代码会在选择图片后,将其添加到一个canvas中,并在左上角添加一个编号,然后将添加编号后的图片显示在页面中。每次上传图片时,编号会自动自增。

JavaScript前端上传图片时给图片添加编号

原文地址: https://www.cveoy.top/t/topic/X4Y 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录