React中使用canvas画图
开发环境: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" }}
获取真实DOM
都知道react虚拟DOM,既然用canvas绘图肯定要获取真实DOM。dome如下:
<canvas ref={this.canvas} width="780" height="1800"> 您的浏览器不支持canvas,请更换浏览器. </canvas>
constructor(){ super(); this.canvas = React.createRef(); }
componentDidMount(){ const canvas = this.canvas.current; }
说明:经过这样这个对象的canvas属性指向被ref包装了一层的canvas元素。然后在元素被渲染之后通过canvas属性的current获取真实canvasDOM。
ref的用法(英文):https://reactjs.org/docs/refs-and-the-dom.html
ref的用法(中文):https://doc.react-china.org/docs/refs-and-the-dom.html
绘画技巧
1、获取当前CanvasRenderingContext2D实例的原型。
看看这个。
componentDidMount() { const canvas = this.canvas.current; if (canvas.getContext) { var ctx = canvas.getContext("2d"); console.log(ctx); console.log(Object.getPrototypeOf(ctx)); } }
Object.getPrototypeOf()用于获取对象的原型,自己在浏览器上打印对比上面两的输出项的区别
2、给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
更多前端开发知识,请查阅 HTML中文网 !!
以上就是怎么在react中画图?的详细内容,更多请关注易知道|edz.cc其它相关文章!