I'm encountering an issue while attempting to draw on an HTML canvas. I've specified 50 circles and multiple lines within a canvas of size 1000x1000 px, but not all circles are appearing as expected.
My assumption is that the elements are being drawn on a canvas with a default size, which is then resized. However, my Style tag comes before any JavaScript code responsible for drawing on the canvas. How can I resolve this?
Below are snippets of my code (written through Servlet):
out.println("<style> \n canvas{\nheight:1000px;\nwidth:1000px;\n}\n</style>");
out.println("<canvas id=\"c\" style=\"border:1px solid #000000;\">Test</canvas>");
process(render, out);
public void process(String input, PrintWriter out)
{
out.println("<p id=\input\ style = \"display:none\"\>"+input+"</p>");
out.println("<script>\n"+
"var JSONProcess = function(){\n" +
" var JSONInfo = document.getElementById(\"input\");\n" +
" var Json = JSON.parse(JSONInfo.innerHTML);\n" +
" var canvas = document.getElementById(\"c\");\n" +
" var c = canvas.getContext(\"2d\");\n" +
" if(Json.nodes != null)\n" +
" {\n" +
" var n = Json.nodes;\n" +
" for(var i=0; i< n.length; i++)\n" +
" {\n" +
" c.beginPath();\n" +
" c.arc(n[i].x+500,n[i].y+500,n[i].size,0,2*Math.PI, false);\n" +
" c.stroke();\n" +
" }\n" +
" }\n" +
" if(Json.edges != null)\n" +
" {\n" +
" var e = Json.edges;\n" +
" for(var i=0; in< n.length; i++)\n" +
" {\n" +
" var s = e[i].source;\n" +
" var t = e[i].target;\n" +
" c.beginPath();\n" +
" c.moveTo(s.x+500, s.y+500);\n" +
" c.lineTo(t.x+500, t.y+500);\n" +
" c.stroke();\n" +
" }\n" +
" }\n" +
"}\n" +
"JSONProcess();</script>");
}
All input values have been validated. The x and y coordinates range from -500 to 500, so they need to be adjusted to fit within the canvas dimensions ranging from 0-1000.