Change the style, "display" attribute, of a canvas in Javascript

Asked

Viewed 255 times

-1

I have a Javascript function that takes an empty canvas and fills it. Only that, as in a first moment I do not want to display the canvas, I set her style in the display attribute as "None". Now, I change the display to block (at runtime). How could I do this in Javascript?

This is the canvas in my html:

<canvas class="canvasCentral" id="bordas" width="400" height="500">

    </canvas>

The style applied to canvas is the "canvasCentral" class of a css file linked to my html:

.canvasCentral{
        position:absolute;
        top:50%;
        left:50%;
        transform:translate(-50%,-50%);
        border:3px solid #D8D8D8;
        border-radius: 20px;
        display:none

    }

How could I, in Javascript, at runtime change the canvas display to block?

  • What do you mean by execution time?

1 answer

1


You can pick it up by the id

document.getElementById('bordas').style.display = "block";

Or by class (if you want to change to all elements that use this class)

var elementos = document.getElementsByClassName("canvasCentral");
elementos.forEach(alteraDisplay)

function alteraDisplay(item, index) {
    item.style.display = "block";
}
  • I get it. it worked. Another thing: when passing the function "alteraDisplay" to foreach, foreach has set as its parameters the ones of alteraDisplay, right?

  • 1

    So the forEach has as callback a function whose parameters are the current_value, the index (optional) and the array (optional), why the function alterDisplay has as input parameters the item (which will receive the callback current_value) and the index (which will receive the callback index). In fact it could receive only the item, because it is the only thing we are using in this case. For more information, see the MDN documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Browser other questions tagged

You are not signed in. Login or sign up in order to post.