3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個贊
在畫布上,您可以getAttribute()用來檢索尺寸。看我的片段:
let canvas = document.getElementById('canvas');
let cheight = parseInt(canvas.getAttribute("height"));
let cwidth = parseInt(canvas.getAttribute("width"));
let context = canvas.getContext('2d');
context.fillStyle = "green";
context.fillRect(0,0,cwidth,cheight);
<canvas width="200" height="200" id="canvas">

TA貢獻(xiàn)2016條經(jīng)驗(yàn) 獲得超9個贊
您可以使用以下代碼設(shè)置畫布的背景顏色。
var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");
context.fillStyle = "green";
context.fillRect(0, 0, canvas.width, canvas.height);
canvas{ border: 1px solid black; }
<canvas width=300 height=150 id="canvas">

TA貢獻(xiàn)1873條經(jīng)驗(yàn) 獲得超9個贊
在您的draw()函數(shù)中,您需要專門添加這樣的背景:
const canvas = document.querySelector('#draw');
const ctx = canvas.getContext('2d');
ctx.strokeStyle = '#BADA55';
ctx.fillStyle = "#ffffff"; //HERE, use HEX format in 6 digits
ctx.fillRect(0, 0, canvas.width, canvas.height); //HERE
...
function draw(e) {
...
}
為什么?
您需要在所有內(nèi)容之前繪制背景,否則一遍又一遍地繪制背景,或者在所有內(nèi)容之上都會導(dǎo)致白色矩形與畫布上的所有內(nèi)容重疊。
添加回答
舉報(bào)