I'm trying to create a class that I have in another js file, but can't figure out why I'm getting unexpected identifier error. What am I doing wrong?
<html>
<body>
<canvas id="graph" width="800" height="600"></canvas>
<script src="./MyGraph.js"></script>
<script>
window.onload = function() {
MyGraph g = new MyGraph('graph');
g.drawLine();
}
</script>
</body>
</html>
And the MyGraph.js file:
class MyGraph {
constructor(containerId) {
this.canvas = document.getElementById(containerId);
this.canvasContext = canvas.getContext('2d');
}
drawLine() {
this.canvasContext.moveTo(25,25);
this.canvasContext.lineTo(125,125);
}
}
You need to put this.canvas.getContext('2d')
, because otherwise canvas
is undefined. And you might want to add stroke()
to your draw function (I'm guessing that's what you want).
class MyGraph {
constructor(containerId) {
this.canvas = document.getElementById(containerId);
this.canvasContext = this.canvas.getContext('2d');
}
drawLine() {
this.canvasContext.moveTo(25,25);
this.canvasContext.lineTo(125,125);
this.canvasContext.stroke();
}
}
And you have to use const
, let
or var
to define variables:
window.onload = function() {
let g = new MyGraph('graph');
g.drawLine();
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments