1

I am trying to draw rectangle with one diagonal line using canvas and script. But, unfortunately rectangle alone is getting displayed in my browser. It looks like the script is not executed.

Code:

import React, { Component } from 'react';
import '../App.css';

class Graphics extends Component{

    render(){
        return(
            <div id="canvas">
            Draw a diagonal Line in Rectangular

            <canvas id="myCanvas" className="canvas-style" width="200" height="100">
</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
</script>
</div>
        );
    }
}

export default Graphics;

3 Answers 3

2

You should write your script tag inside componentDidMount().

Sign up to request clarification or add additional context in comments.

Comments

0
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
  componentDidMount () {
    let c = document.getElementById("myCanvas");
    let ctx = c.getContext("2d");
    ctx.moveTo(0, 0);
    ctx.lineTo(200, 100);
    ctx.stroke();
  }
  render () {
    return (
      <div className="App">
        <div id="canvas">
          Draw a diagonal Line in Rectangular
        <canvas
          id="myCanvas"
          className="canvas-style"
          width="200"
          height="100" />
        </div>
      </div>
    );
  }
}

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

Comments

0

You can use the below code,

import React, { Component } from 'react';
import '../App.css';
class Graphics extends Component{
 componentDidMount(){
   var c = document.getElementById("myCanvas");
   var ctx = c.getContext("2d");
   ctx.moveTo(0,0);
   ctx.lineTo(200,100);
   ctx.stroke();
  }
    render(){
        return(
            <div id="canvas">
            Draw a diagonal Line in Rectangular

            <canvas id="myCanvas" className="canvas-style" width="200" height="100">
            </canvas>

            </div>
        );
    }
}

export default Graphics;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.