首页 > 解决方案 > 如何在 React js 中加载图像?

问题描述

我正在尝试制作具有** rotate and zoom in and zoom out**功能的图像查看器所以我用画布绘制图像,但我认为它不起作用然后我直接添加了我的imagesrc url(我知道这不是好方法)。我需要使用画布绘制图像,以便我可以旋转和缩放图像。这是我的代码 https://codesandbox.io/s/6z651o698n

import React, { Component } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends Component {
  constructor() {
    super();
    this.state = {
      src:
        "https://img.timesnownews.com/story/1542606525-Sachin_Shaw.png?d=600x450"
    };
  }

  componentDidMount() {
    console.log("d");

    const canvas = document.getElementById("canvas");
    var context = canvas.getContext("2d");
    var image = document.getElementById("image");
  }

  resetImage() {
    //load the  image in canvas if the image is loaded successfully
    const canvas = document.getElementById("canvas");
    const image = document.getElementById("image");
    const element = canvas.getContext("2d");
    const currentScale = Math.min(
      canvas.width / image.width,
      canvas.height / image.height
    );
  }
  clear() {
    const canvas = document.getElementById("canvas");
    const element = canvas.getContext("2d");
    element.clearRect(-2000, -2000, 5000, 5000);
  }
  drawImage() {
    const canvas = document.getElementById("canvas");
    const element = canvas.getContext("2d");
    clear();
    element.save();
    element.translate(canvas.width / 2, canvas.height / 2);
    element.translate(-canvas.width / 2, -canvas.height / 2);
    element.drawImage(
      image,
      canvas.width / 2 / currentScale - image.width / 2,
      canvas.height / 2 / currentScale - image.height / 2
    );
    element.restore();
  }
  zoomIn() {
    currentScale += 0.5;
    drawImage();
  }

  zoomIn() {
    currentScale -= 0.5;
    drawImage();
  }

  render() {
    console.log("r");
    return (
      <div>
        <button id="zoomIn" onClick={this.zoomIn}>
          {" "}
          Zoom In
        </button>
        <button id="zoomIn" onClick={this.zoomOut}>
          {" "}
          Zoom In
        </button>

        <canvas id="canvas" height="350" data-girar="0">
          sdsd
        </canvas>
        <img id="image" src={this.state.src} />
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

**可能是我在这里犯了很多错误,因为我是新来的反应**目前zoom in and zoom out functionality not working

标签: javascriptreactjscanvashtml5-canvas

解决方案


有很多工作要做,但您可以从以下步骤开始:

  1. 所有对方法的调用都必须以 开头this.,因此将clear()anddrawImage()替换为this.clear()and this.drawImage()
  2. 为了使变量currentScale保持不变,您可以将其设为全局、对象属性或反应状态的一部分。我建议从对象属性开始,因此将所有出现的替换currentScalethis.currentScale. 为了初始化这个属性,你必须调用this.resetImage().componentDidMount
  3. 当你传递像 in 这样的回调时onClick={this.zoomIn},你必须将它们绑定到this. 有几种方法可以做到这一点,最简单的是将其替换为onClick={this.zoomIn.bind(this)}

有几个小错别字:你有两种zoomIn方法,但没有const imagedrawImage.


推荐阅读