Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - My canvas wouldn't load unless I started to inspect the page?

This is my Javascript code:

var x = document.querySelector('canvas')
    var ctc = x.getContext("2d")
    var score = 0;
    var speed = 0.2;
    var container1 = [];
    var container2;

window.addEventListener("resize", function(){
    x.width = window.innerWidth
    x.height = window.innerHeight

})

window.addEventListener("mousemove", function(e){
    console.log("x: " + e.clientX)
    console.log("y: " + e.clientY)
})


function initiation() {
    let xcord = 599
    let ycord = 200
    let snakeSpeed = speed;
    let length = 2;
    let color = "black";
    container1.push(new Snake(xcord,ycord,length,snakeSpeed,color))
    console.log(container1[0])
}
initiation()

container1[0].draw()
function loop() {
    window.requestAnimationFrame(loop)
    ctc.clearRect(0,0, innerWidth, innerHeight)
    container1[0].update()
}
loop()
container1[0].showLocation()

function Snake(xcord,ycord,length,speed,color) {
    this.x = xcord
    this.y = ycord
    this.length = length
    this.speed = speed
    this.color = color
    this.xtail = 0
    this.ytail = 0
    
    this.update = function() {
        this.x += 0.1
        this.draw()
    }
    this.showLocation = function() {
        console.log(this.x + "    " + this.y)
    }
    this.draw = function() {
        ctc.beginPath()
        ctc.arc(this.x + this.xtail, this.y + this.ytail , 10, 0, Math.PI*2, true);
        ctc.strokeStyle = "black";
        ctc.stroke()
        ctc.fill()
    }
}

That is my Javascript code, and below is my HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="snake.css">
</head>
<body>
    <canvas id="screen"></canvas>
</body>
<script src="snake.js"></script>
</html>

what I don't understand is that when I refresh the page or open it up from visual code studio, the canvas won't load in the animation I had in mind. Only after I inspect the page, the animation would start to run on canvas. Afterward, when I close the inspect space, the animation re-run again. I don't know how to fix this? What even caused this?

question from:https://stackoverflow.com/questions/65865805/my-canvas-wouldnt-load-unless-i-started-to-inspect-the-page

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...