javascript - 如何在 React js 中加载图像?
问题描述
我正在尝试制作具有** 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
解决方案
有很多工作要做,但您可以从以下步骤开始:
- 所有对方法的调用都必须以 开头
this.
,因此将clear()
anddrawImage()
替换为this.clear()
andthis.drawImage()
。 - 为了使变量
currentScale
保持不变,您可以将其设为全局、对象属性或反应状态的一部分。我建议从对象属性开始,因此将所有出现的替换currentScale
为this.currentScale
. 为了初始化这个属性,你必须调用this.resetImage()
.componentDidMount
- 当你传递像 in 这样的回调时
onClick={this.zoomIn}
,你必须将它们绑定到this
. 有几种方法可以做到这一点,最简单的是将其替换为onClick={this.zoomIn.bind(this)}
有几个小错别字:你有两种zoomIn
方法,但没有const image
在drawImage
.
推荐阅读
- c# - 为 1 列更新 200 万行
- microsoft-cognitive - 必应 Web 搜索 API - 片段结果不正确
- reporting-services - 动态 365 SSRS | 打印报告 添加边距顶部
- java - 如何将多类型布局设置为 RecyclerView?
- firefox - 旧 Firebug 建议 html 类和 ID,但新内置的 firebug 不建议
- reactjs - flatlist 显示类型错误:null 不是键
- javascript - 带有文本换行符的 JavaScript 语法错误
- javascript - 无法通过featherjs中的find函数将参数传递给服务挂钩
- mysql - 如何使用 django 模型将数组存储在 mysql 数据库中?
- c# - [BotFramework][Cortana] 用户如何在 Cortana 中向 Bot 发送附件?