When submitting a form, canvas should be drawn on the page. But after the form is submitted, canvas is drawn for a split second and then disappears. How to make so that after sending, canvas remained in place.

html code:

<form id="mainForm"> <span id="header">Enter math expression:</span> <input type="text" id="inputExpr"> <input type="submit" id="submitBtn" onclick="drawShelves()"> </form> <canvas id="canvas"></canvas> <script src="scr.js"></script> 

js:

 function drawShelves() { var canvas = document.getElementById('canvas'), ctx = canvas.getContext('2d'); canvas.width = 800; canvas.height = 400; ctx.lineWidth = 1.0; ctx.strokeStyle = 'black'; ctx.beginPath(); // left shelve ctx.strokeRect(5, 100, 340, 10); ctx.moveTo(5, 110); for (var i = 5; i < 340; i+=10) { ctx.lineTo(i+10, 100); ctx.moveTo(i+10, 110); } // right shelve ctx.strokeRect(455, 100, 340, 10); ctx.moveTo(455, 110); for (var i = 455; i < 790; i+=10) { ctx.lineTo(i+10, 100); ctx.moveTo(i+10, 110); } ctx.stroke(); } 

    2 answers 2

    There are two options.

    1. Disable the default button press event:

       <input type="submit" id="submitBtn" onclick="drawShelves(); return false;"> 
    2. Disable the default form submission event:

       <form id="mainForm" onsubmit="return false;"> 

    But in both cases, you need to send the data to the server in some way without reloading the page. The surest way is to use an Ajax request. Therefore, it will be easier to rewrite the code as follows:

     <form id="mainForm" onsubmit="return drawShelves();"> function drawShelves() { // здесь отрисовка канвы // здесь ajax запрос return false; } 

    You can read more about Ajax here: http://javascript.ru/ajax/intro .

       ...function(event) { // Откоючает тригер события формы event.preventDefault(); ... some code... } 
      • To format the code, select it with the mouse and click on the {} button of the editor. - fori1ton