我试图将 Canvas 上下文与实际的绘制函数分开,但不起作用。作为上下文的一部分,我希望包括调整不起作用的 Canvas 大小的功能。 HTML 工作得很好,因为 getElementbyID 的工作很明显。包含了可以正常工作的绘图功能以供引用。
window.onload = function() {
'use strict';
var ctx = getCanvas();
draw(ctx);
}
function getCanvas() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width = 200;
var h = canvas.height = 150;
return ctx;
}
function draw(ctx) {
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
ctx.fillRect(30, 30, 50, 50);
}
最佳答案
我发现您的代码没有问题。它按预期工作。
window.onload = function() {
'use strict';
var ctx = getCanvas();
draw(ctx);
};
function getCanvas() {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var w = canvas.width = 200;
var h = canvas.height = 150;
return ctx;
}
function draw(ctx) {
ctx.fillStyle = 'rgb(200, 0, 0)';
ctx.fillRect(10, 10, 50, 50);
ctx.fillStyle = 'rgba(0, 0, 200, 0.5)';
ctx.fillRect(30, 30, 50, 50);
}
canvas{border: 1px solid black}
<canvas id="canvas" width="1000" height="1000"></canvas>
注意: 不要使用 CSS 设置 Canvas 的宽度和高度(首先)。
关于javascript - Canvas Javascript 绘图功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44714025/