知识点系列一---上传图片并通过canvas展示

569 阅读1分钟

知识点1:

ctx.drawImage()的第一个参数的类型是

  • CSSImageValue
  • HTMLImageElement
  • SVGImageElement
  • HTMLVideoElement
  • HTMLCanvasElement
  • ImageBitmap
  • OffscreenCanvas 所以我们使用HTMLImageElement这个类型

知识点2:

使用window.URL.createObjectURL将blob对象转换成url,使得img标签正确生成,再将这个HTMLImageElement传入ctx.drawImage()方法中。

ps:

使用的是ts, 完整代码如下

import * as React from 'react';
import './index.less';
import { Upload, message } from 'antd';
import { UploadChangeParam } from 'antd/lib/upload';

interface IState {
  imgUrl: any
}
export default class Edit extends React.Component<{},IState>{
  state = {
    imgUrl: ''
  }
  imageLoaded = () => {

  }
  onChangeHandler = (info: UploadChangeParam) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
     
      let cvs = document.getElementById('cvs');
      var ctx = cvs!.getContext('2d');
      let fileUrl = window.URL.createObjectURL(info.file.originFileObj!);
      var img = document.getElementById('uploadedImg');
      this.setState({ imgUrl: fileUrl });
      img!.onload = function() {
        console.info('xxx');
        ctx.drawImage(img, 0, 0);//this即是imgObj,保持图片的原始大小:470*480
    }
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  }
 render(){
   const uploadProps = {
    name: 'file',
    action: '//jsonplaceholder.typicode.com/posts/',//这个地址是antd的示例地址
    headers: {
      authorization: 'authorization-text',
    },
  };
   return (
    <div className="edit-page">
      <canvas height={500} width={500} id="cvs"></canvas>
      <br />
      <Upload {...uploadProps}
        onChange = {this.onChangeHandler}
      >
        <p>点击这里上传一张图片,开始你的创作吧!</p>
      </Upload>
      <img src={this.state.imgUrl} id="uploadedImg" style={{display: 'none'}}/>
    </div>
   );
 }
}