If you click the button on the top left corner, a rectangle plus a coordinate grid is drawn on the canvas. But when the page is refreshed, all elements drawn on canvas is wiped out because of the “ctx.clearRect(0, 0, 800, 700);” command.
How do I modify the code so that when the page is refreshed, only the coordinate grid remain visible. Also, is it better to use SVG than canvas?. Thank you for your time.
<html>
<body>
<button type = "button" id = "btn1">Enter</button><br>
<canvas id="rightCanvas" width="800" height="700" style="border:1px solid grey;">
Your browser does not support the canvas element.
</canvas>
<script>
document.getElementById("btn1").onclick = calculate;
function calculate(){
var canvas = document.getElementById("rightCanvas");
var ctx = canvas.getContext("2d");
var canvas_width = document.getElementById("rightCanvas").width;
var canvas_height = document.getElementById("rightCanvas").height;
var x0 = 50, y0 = 50;
var width = canvas_width - x0 - y0;
var height = canvas_height - x0 - y0;
var xy_thickness = 4, grid_space = 10;
var origin_x = x0+50, origin_y = x0 + height-50;
ctx.clearRect(0, 0, 800, 700);
for (var i = 0; i <= height/grid_space; i++) {
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(x0, y0 + grid_space * i);
ctx.lineTo(x0 + width, y0 + grid_space * i);
ctx.strokeStyle = 'rgb(180, 180, 180)';
ctx.stroke();
}
for (var i = 0; i <= width/grid_space; i++) {
ctx.beginPath();
ctx.moveTo(x0 + grid_space * i, y0);
ctx.lineTo(x0 + grid_space * i, y0 + height);
ctx.strokeStyle = 'rgb(180, 108, 180)';
ctx.stroke();
}
var ax1 = 2, ay1 = 3, ax2 = 8, ay2 = 7; // coordinates of 1st rectangle
var ax1_rel = origin_x + ax1*50;
var ay1_rel = origin_y - ay1*50;
var ax2_rel = origin_x + ax2*50;
var ay2_rel = origin_y - ay2*50;
ctx.globalAlpha = 0.5;
ctx.fillStyle = "yellow";
ctx.fillRect(ax1_rel, ay1_rel, (ax2-ax1)*50, (ay1-ay2)*50);
ctx.lineWidth = 3;
ctx.globalAlpha = 1;
ctx.beginPath();
ctx.moveTo(ax1_rel, ay1_rel);
ctx.lineTo(ax1_rel, ay2_rel);
ctx.lineTo(ax2_rel, ay2_rel);
ctx.lineTo(ax2_rel, ay1_rel);
ctx.closePath();
ctx.strokeStyle = 'black';
ctx.stroke();
}
</script>
</body>
</html>