前言:自從開始學(xué)習(xí)react,我再次確認(rèn)了中西方思想差異。中國解決問題之道在于,利用最少、最好是現(xiàn)成的基本元素解決。西方就一個字:造。好了不說這些偽結(jié)論了。雖然在中國,百度在搜索引擎方面是老大,可是它的搜索能力卻落后于潮流。完全搜不到react開發(fā)的項目。其它不那么出名的搜索引擎都實(shí)現(xiàn)了搜索基于react開發(fā)的項目。百度頹勢初現(xiàn)。
正題
開發(fā)環(huán)境:package.json
{
"name": "antd-react",
"version": "0.1.0",
"private": true,
"dependencies": {
"antd": "^3.7.0",
"install": "^0.12.1",
"npm": "^6.2.0",
"react": "^16.4.1",
"react-amap": "^1.2.7",
"react-dom": "^16.4.1",
"react-player": "^1.6.4",
"react-router-dom": "^4.3.1",
"react-scripts": "1.1.4",
"string.prototype.startswith": "^0.2.0"
},
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom",
"eject": "react-scripts eject"
},
"devDependencies": {
"babel-plugin-import": "^1.8.0",
"react-app-rewired": "^1.5.2"
}
}
獲取真實(shí)DOM
都知道react虛擬DOM,既然用canvas繪圖肯定要獲取真實(shí)DOM。dome如下:
<canvas ref={this.canvas} width="780" height="1800">
您的瀏覽器不支持canvas,請更換瀏覽器.
</canvas>
constructor(){
super();
this.canvas = React.createRef();
}
componentDidMount(){
const canvas = this.canvas.current;
}
說明:經(jīng)過這樣這個對象的的canvas屬性指向被被ref包裝了一層的canvas元素。然后在元素被渲染之后通過canvas屬性的current獲取真實(shí)canvasDOM。
ref的用法(英文):https://reactjs.org/docs/refs-and-the-dom.html
ref的用法(中文):https://doc.react-china.org/docs/refs-and-the-dom.html
繪畫技巧
獲取當(dāng)前CanvasRenderingContext2D實(shí)例的原型。
看看這個。
componentDidMount() {
const canvas = this.canvas.current;
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
console.log(ctx);
console.log(Object.getPrototypeOf(ctx));
}
}
Object.getPrototypeOf()用于獲取對象的原型,自己在瀏覽器上打印對比上面兩的輸出項的區(qū)別.
給CanvasRenderingContext2D原型添加方法
componentDidMount() {
const canvas = this.canvas.current;
if (canvas.getContext) {
var ctx = canvas.getContext("2d");
console.log(ctx);
console.log(Object.getPrototypeOf(ctx));
(function () {
Object.getPrototypeOf(ctx).Triangle = function (x, y, r) {
this.save();
this.translate(x, y);
this.rotate(r);
this.beginPath();
this.moveTo(0, 0);
this.lineTo(10, 0);
this.lineTo(0, 10);
this.lineTo(-10, 0);
this.closePath();
this.fill();
this.restore();
}
Object.getPrototypeOf(ctx).line = function (x, y, x1, y1) {
this.save();
this.beginPath();
this.moveTo(x, y);
this.lineTo(x1, y1);
this.stroke();
this.restore();
}
})();
ctx.strokeStyle = "#7C8B8C";
ctx.line(90, 130, 320, 210);
ctx.Triangle(320, 210, -Math.PI * .4);
}
}
ok