知識點系列一---上傳圖片並通過canvas展示

Arthur同學發表於2018-12-17

知識點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>
   );
 }
}
複製程式碼

相關文章