知識點系列一---上傳圖片並經過canvas展現

知識點1:

ctx.drawImage()的第一個參數的類型是react

  • CSSImageValue
  • HTMLImageElement
  • SVGImageElement
  • HTMLVideoElement
  • HTMLCanvasElement
  • ImageBitmap
  • OffscreenCanvas 因此咱們使用HTMLImageElement這個類型

知識點2:

使用window.URL.createObjectURL將blob對象轉換成url,使得img標籤正確生成,再將這個HTMLImageElement傳入ctx.drawImage()方法中。json

ps:

使用的是ts, 完整代碼以下canvas

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>
   );
 }
}
複製代碼
相關文章
相關標籤/搜索