我想对我的小画布项目进行代码审查,所以我想我会在jsfiddle上提供它但是由于某种原因我的画布不会在jsfiddle上绘制。它在我的电脑上本地工作正常。请指教
https://jsfiddle.net/wastelandtime/su2q5pp9/1/
HTML:
<body>
<canvas id="canvas"></canvas>
<button onclick="resetCanvas()">Reset</button>
<button onclick="isSym(arr)">Check</button>
<script>
// Pageload
window.addEventListener("load", function load(event) {
//Call only the functions you want to use on this page here
//and pass the elements as parameters if you use abstract functions
arr = genArray(6);
canvasCreate(300, 300);
drawGrid(arr);
canvas.addEventListener('mousedown', mouseClick, false);
});
</script>
</body>
的script.js
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext("2d");
var canvasCreate = function(w, h) {
canvas.width = w;
canvas.height = h;
};
function resetCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
arr = genArray(6);
drawGrid(arr);
}
// Generate a 6x6 array of 0s or 1s
function genArray(aSize) {
var a = [];
var count = 0
for (var i=0;i<aSize;i++) {
a[i] = [];
for (var j=0;j<aSize;j++) {
a[i][j] = (count < 10) ? Math.floor(Math.random() * 2) : 0;
count = (a[i][j]== 1) ? count+=1 : count;
}
}
return a;
}
function drawGrid(arr) {
var n = 6;
for (var i = 0; i < n; i++) {
for (var j = 0; j < n; j++) {
ctx.beginPath();
ctx.strokeStyle = '#555';
if (arr[i][j] === 1) {
ctx.fillStyle = '#3399ff';
ctx.fillRect(i * 50, j * 50, 50, 50);
} else {
ctx.fillStyle = '#ffffff';
ctx.fillRect(i * 50, j * 50, 50, 50);
}
ctx.rect(i * 50, j * 50, 50, 50);
ctx.stroke();
}
}
var hw = canvas.width / 2;
ctx.beginPath();
ctx.strokeStyle = '#ff0000';
ctx.moveTo(hw, 0);
ctx.lineTo(hw, canvas.height);
ctx.stroke();
}
// Get mouse position within canvas
function mouseClick(e) {
var mouseX, mouseY;
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
var gridX = Math.floor(mouseX / 50);
var gridY = Math.floor(mouseY / 50);
var xy = arr[gridX][gridY];
if (xy == 0) {
arr[gridX][gridY] = 1;
}
else if (xy == 1) {
arr[gridX][gridY] = 0;
}
drawGrid(arr);
}
function isSym(arr) {
var diff = 5;
var tot = 0
for (var i = 0; i < arr.length / 2; i++) {
var l = arr[i].join("");
var r = arr[i + diff].join("");
var comp = (l == r) ? 1 : 0;
diff -= 2;
tot += comp;
}
var isIt = (tot != 3) ? "wrong" : "right";
alert("You are " + isIt + "!!!");
}
编辑:检查了jsfiddle中的控制台错误,如下所示,我发现了以下内容: genArray未定义(从HTML文件调用)。有一个原因我想从html调用它,而不是script.js,但这是代码审查问题,而不是现在。所以问题是如何在嵌入html的注入脚本之前首先在jsfiddle中加载JavaScript部分?