请帮助弄清楚为什么这不起作用。 drawTest函数(显示为概念证明)有效但不是drawGrid函数。我做错了什么?
'use strict';
window.onload = init;
function init() {
let can = document.getElementById('canvas');
let ctx = can.getContext('2d');
drawTest(ctx);
drawGrid(ctx);
}
function drawTest(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);
}
function drawGrid(ctx, elSize = 10, width = .3, color = 'green') {
ctx.lineWidth = width;
ctx.stroke.style = color;
var lineX = ctx.width/elSize - 1;
var lineY = ctx.height/elSize - 1;
for (var i = 1; i <= lineX; i++) {
ctx.beginPath();
ctx.moveTo(elSize * i, 0);
ctx.lineTo(elSize * i, ctx.height);
ctx.stroke();
}
for (var i = 1; i <= lineY; i++) {
ctx.beginPath();
ctx.moveTo(0, elSize * i);
ctx.lineTo(ctx.width, elSize * i);
ctx.stroke();
}
}
答案 0 :(得分:1)
上下文没有宽度,因此未定义ctx.width和ctx.height。相反,使用ctx.canvas.width和ctx.canvas.height。
function drawGrid(ctx, elSize = 10, width = .3, color = 'green') {
ctx.lineWidth = width;
ctx.stroke.style = color;
var lineX = ctx.canvas.width/elSize - 1;
var lineY = ctx.canvas.height/elSize - 1;
for (var i = 1; i <= lineX; i++) {
ctx.beginPath();
ctx.moveTo(elSize * i, 0);
ctx.lineTo(elSize * i, ctx.canvas.height);
ctx.stroke();
}
for (var i = 1; i <= lineY; i++) {
ctx.beginPath();
ctx.moveTo(0, elSize * i);
ctx.lineTo(ctx.canvas.width, elSize * i);
ctx.stroke();
}
}