admin管理员组

文章数量:1426480

I am making a game in HTML5 Canvas and JavaScript, and I am making my canvas as such:

<canvas id="gameCanvas" width="800" height="600"></canvas>

And in my JavaScript:

var canvas;

function myFunction() {
    canvas = document.getElementById("gameCanvas");
    canvas.style.display = "block";
}

And I want my canvas to appear when I run myFunction(), so I have this CSS:

canvas {
    display: none;
}

However, when I run myFunction(), I get the sounds from my game, which means the canvas is on the page, however the canvas is not displayed. Even if I apply this CSS:

canvas {
    display: none;
    border: 10px solid lime;
}

And run myFunction(), I see nothing on the page. What am I doing wrong here? Is there something else I have to do?

I am making a game in HTML5 Canvas and JavaScript, and I am making my canvas as such:

<canvas id="gameCanvas" width="800" height="600"></canvas>

And in my JavaScript:

var canvas;

function myFunction() {
    canvas = document.getElementById("gameCanvas");
    canvas.style.display = "block";
}

And I want my canvas to appear when I run myFunction(), so I have this CSS:

canvas {
    display: none;
}

However, when I run myFunction(), I get the sounds from my game, which means the canvas is on the page, however the canvas is not displayed. Even if I apply this CSS:

canvas {
    display: none;
    border: 10px solid lime;
}

And run myFunction(), I see nothing on the page. What am I doing wrong here? Is there something else I have to do?

Share Improve this question asked Nov 1, 2018 at 8:02 Jack BashfordJack Bashford 44.2k11 gold badges55 silver badges82 bronze badges 4
  • did you inspect what your code does?, i think display: block gets overwritten by a none with !important or something – Ramon de Vries Commented Nov 1, 2018 at 8:13
  • @RamondeVries Of course, the styles inspector! – Jack Bashford Commented Nov 1, 2018 at 8:13
  • @RamondeVries Yes, I figured it out - I had an overriding statement in inline HTML. Please can you add your ment as an answer for future reference? – Jack Bashford Commented Nov 1, 2018 at 8:14
  • @RamondeVries If you add your answer, I will mark it as accepted and upvote it – Jack Bashford Commented Nov 1, 2018 at 8:17
Add a ment  | 

3 Answers 3

Reset to default 2

remove css canvas {display: none;} instead on page load

canvas = document.getElementById("gameCanvas");
canvas.style.display = "none";

and when u calling function it will be display block

Did you inspect what your code does?, I think display: block gets overwritten by a none with !important or something.

If so, change your script code or try to remove the overwriting !important tag when its not necessary.

Hope this helps.

Change at the last block of your code, You are using display: none which terminate the canvas

canvas {
    display: block;
    border: 10px solid lime;
}

本文标签: htmlSetting HTML5 canvas display properties with JavaScript makes canvas invisibleStack Overflow