gpt4 book ai didi

javascript - 无法通过 HTML 在屏幕上显示 Canvas

转载 作者:行者123 更新时间:2023-11-28 16:55:29 25 4
gpt4 key购买 nike

在我的代码中,我只得到定义宽度和高度的黑色 Canvas 。并且红色和白色未在屏幕上呈现。

提前致谢。

var canvas;
var canvasContext;
var ballx = 50;

window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
drawCanvas();
drawCanvasRed();
// drawCanvas();
}

function drawCanvas() {
canvasContext.fillStyle = 'black';
canvasContext.fillRect(0, 0, canvas.width, canvas.height);


canvasContext.fillStyle = 'white';
canvasContext.fillRect(225, 200, 50, 25);
};

function drawCanvasRed() {
canvasContext.fillStyle = 'red';
canvasContext.fillRect(ballx, 200, 50, 25);
}
#gameCanvas {
width: 500px;
height: 500px;
}
<canvas id="gameCanvas"></canvas>

最佳答案

您需要检查 Canvas 的大小。我改变了一些尺寸。所以它可以帮助你。

<!DOCTYPE html>
<html>
<head></head>
<style>
#gameCanvas {
width: 1000px;
height: 1000px;
}
</style>
<body>
<canvas id="gameCanvas"></canvas>
<script>
var canvas;
var canvasContext;
var ballx = 50;

window.onload = function() {
canvas = document.getElementById('gameCanvas');
canvasContext = canvas.getContext('2d');
drawCanvas();
drawCanvasRed();
// drawCanvas();
}

function drawCanvas() {
canvasContext.fillStyle = 'black';
canvasContext.fillRect(0, 0, 500, 500); // In your size you need to check, because you passed canvas width and canvas height

canvasContext.fillStyle = 'white';
canvasContext.fillRect(10, 10, 50, 25);
};

function drawCanvasRed() {

canvasContext.fillStyle = 'red';
canvasContext.fillRect(ballx, 50, 50, 25);
}
</script>
</body>
</html>

关于javascript - 无法通过 HTML 在屏幕上显示 Canvas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59320915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com