我正在尝试制作具有** {rotate and zoom in and zoom out
**功能的图像查看器,因此我使用画布来绘制图像,但是我认为它不起作用,因此我直接添加了image
src 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
答案 0 :(得分:0)
有很多工作要做,但是您可以从以下步骤开始:
this.
开始,因此将clear()
和drawImage()
替换为this.clear()
和this.drawImage()
。currentScale
保持不变,可以将其设置为全局,对象属性或部分反应状态。我建议从对象属性开始,因此用currentScale
替换所有出现的this.currentScale
。为了初始化此属性,您必须在this.resetImage()
中调用componentDidMount
。onClick={this.zoomIn}
中那样传递回调时,必须将它们绑定到this
。有几种方法可以做到这一点,最简单的方法是将其替换为onClick={this.zoomIn.bind(this)}
有几种小错别字:您有两种zoomIn
方法,而在const image
中没有drawImage
声明。