I want to be able to freely reproduce the painting function in JS.
I would like to be able to draw the template HTML from ajax if it exists (if there is a canvas tag).

$(document) .on ("change", "[id = templates_number]", function () {
    $.post ("templates.php", {
      data: template_data,
    }, function (data) {
   // Loading data with html
   // If the tag is canvas, canvas settings
Canvas = document.getElementById ("canvas tag id");
   ctx = canvas.getContext ('2d');
   undoImages = [];
   pointer = -1;
   canvas.addEventListener ('mousemove', draw_canvas);

I'm sorry to omit a lot of code. If i read the data information of the form with json, loop it, and if the tag type is canvas, I want to set the canvas.
Currently it looks like this. Perhaps you can't do more than one setting. Also, it is suspicious that EventListener can be set in a loop.
I am looking forward to your advice because I have little experience with JS

  • Answer # 1

    This is a difficult story for the beginner level.
    If it is difficult to understand,When using a new variable in JavaScript, just remember to usevar(orlet)It ’s good.
    Code fixes includechanging variables in loops toletdeclarationsanddraw_canvas ()functions in loops I ’d like to define it.

    The reason why the code of the question text cannot support multiple<canvas>is considered to be because the variable used in the loop is a "global variable". The If it is left as it is, the<canvas>tag for the second and subsequent times will overwrite the previous value.
    In JavaScript, when you use a new variable, if you declare the variable usingvarorlet, the variable becomes a "local variable" and limits the range in which the variable can be used. Can be used.
    Grammar and data types-JavaScript | MDN

    By rewriting the code of the question sentence as follows, I think that the variable can be used as a local variable and the overwriting by the loop can be avoided.

    let canvas = document.getElementById ("canvas tag id");
    let ctx = canvas.getContext ('2d');
    let undoImages = [];
    let pointer = -1;

    Theletused here is a{}← variable that can be used only within the parentheses. Is declared. This will create a new variable each time theforloop is looped.
    (Theforloop's first variablecanvasis different from the loop's second variablecanvas.)

    Note that foraddEventListener (), the functiondraw_canvas ()given to the argument isforloop{}< Must be defined in/code>. Because the variablecanvasexists only in{}.
    In addition, the variable that is referenced outside the function becomes a local variable at the time the function is defined, so the variablecanvasis properly a variable for each loop.