简体   繁体   中英

Drawing graphics on canvas in node-js/Express

I want to draw a chart on canvas element. My Jade file contains following:

div
   canvas

In my index.js file in node.js web application, I tried the following:

var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.strokeStyle = "rgba(255, 0, 0, 1)";
height = canvas.height;
width = canvas.width;
context.moveTo(0, 0);
context.lineTo(width, height);
context.lineWidth = 1;
context.stroke();

However, it fails to recognize "document". My question is how do I obtain the reference to "canvas" in my.js file? Note that the actual chart would be more complex than the simple line drawing code shown above for brevity. The data for the chart is generated in index.js file at the server end. So the chart will be created on the server.

NodeJS cannot get a reference to the users browser to draw on the displayed page. Although it is Javascript, NodeJS executes on the server side. The same code will have to be written within your HTML page.

If your drawing needs some data to come from the backend NodeJS logic, then the page Javascript will have to invoke your NodeJS services to fetch the relevant data.

As of August 2021, it's possible to draw on Canvas in Node.js by using https://github.com/Automattic/node-canvas

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM