Я пытаюсь создать небольшую видеоигру. Я использую P5.min.js для холста, но не могу найти ошибку.
Он сказал, что это в моих файлах p5.min.js: Uncaught TypeError: не удалось выполнить «getImageData» для «CanvasRenderingContext2D»: значение не имеет типа «длинный».
Я попытался заменить p5.min.js на CDN, но ничего не изменилось.
Есть мой код:
let cols, rows;
let w = 90;
let grid = [];
let stack = [];
let grenouille;
// Récuperation images
function preload(){
sac = loadImage("img/sac-bb-rond.png");
grenouille = loadImage("img/grenouillecanvas.png");
chinois = loadImage("img/usine_mechant.png");
}
// déplacement mobile
window.onload = function () {
let pozx1;
let pozy1;
let pozx;
let pozy;
let html = document.querySelector("#html");
// mettre les questions dans le tableau
setAvailableQuestions();
// call une question
getNewQuestion();
html.addEventListener("touchstart", function (e) {
e=e || window.event;
// x = horizontal
pozx = e.changedTouches[0].pageX;
pozy = e.changedTouches[0].pageY;
})
html.addEventListener("touchend", function (e) {
e=e || window.event;
// x = horizontal
pozx1 = e.changedTouches[0].pageX;
pozy1 = e.changedTouches[0].pageY;
horizontal = pozx1 - pozx;
vertical = pozy1 - pozy;
// aller à droite
if (horizontal > vertical && horizontal > 50){
// console.info("go droite");
goRight()
}
// aller à gauche
else if (horizontal < vertical && horizontal < -50){
// console.info("go gauche");
goLeft()
}
// aller en bas
else if (vertical > horizontal && vertical > 50){
// console.info("go bas");
goDown()
}
// aller en haut
else if (vertical < horizontal && vertical < -50){
// console.info("go haut");
goUp()
}
})
}
//
function setup() {
canvas = createCanvas(400, 400);
cols = floor(width/w);
rows = floor(height/w);
canvas.center();
// vitesse de carrés violets
// frameRate(1);
for (let j = 0; j < rows; j++){
for (let i = 0; i < cols; i++){
let cell = new Cell(i,j);
grid.push(cell);
}
}
current = grid[0];
goal = grid[cols * rows - 1];
// ennemi = grid[(cols * rows - 1) / 2];
ennemi = grid[floor((cols * rows / 2 - 1) )];
}
// derniere case
// grid[168]
function draw(){
background(51);
for (let i = 0; i < grid.length; i++){
grid[i].show();
}
current.visited = true;
// current.show();
current.highlight();
// current = image(grenouille, 10, 6, 20, 20);
goal.objectif ();
ennemi.zone();
// ETAPE 1
let next = current.checkNeighbors();
if (next){
next.visited = true;
// ETAPE 2
stack.push(current);
// ETAPE 3
removeWalls(current, next);
// ETAPE 4
current = next;
}
else if (stack.length > 0){
current = stack.pop();
}
}
function index(i, j){
if (i < 0 || j < 0 || i > cols-1 || j > rows-1){
return -1;
}
return i + j * cols;
}
function Cell(i, j){
this.i = i;
this.j = j;
// top right bottom left
this.walls = [true, true, true , true];
this.visited = false;
this.checkNeighbors = function() {
let Neighbors = []
let top = grid[index(i, j-1)];
let right = grid[index(i+1, j)];
let bottom = grid[index(i, j+1)];
let left = grid[index(i-1, j)];
if (top && !top.visited){
Neighbors.push(top);
}
if (right && !right.visited){
Neighbors.push(right);
}
if (bottom && !bottom.visited){
Neighbors.push(bottom);
}
if (left && !left.visited){
Neighbors.push(left);
}
if (Neighbors.length > 0){
let rand = floor(random(0, Neighbors.length));
return Neighbors[rand];
}
else{
return undefined;
}
}
this.checkVoisins = function() {
let voisins = []
let top = grid[index(i, j-1)];
let right = grid[index(i+1, j)];
let bottom = grid[index(i, j+1)];
let left = grid[index(i-1, j)];
if (top && !this.walls[0]){
voisins.push(top);
}
if (right && !this.walls[1]){
voisins.push(right);
}
if (bottom && !this.walls[2]){
voisins.push(bottom);
}
if (left && !this.walls[3]){
voisins.push(left);
}
if (voisins.length > 0){
let randoms = floor(random(0, voisins.length));
return voisins[randoms];
}
else{
return undefined;
}
}
// carré actif
this.highlight = function(){
let x = this.i*w;
let y = this.j*w;
noStroke();
image(grenouille, x, y, w, w);
// bg de la grenouille
// fill(51, 51, 51, 10000);
// rect(x, y, w, w);
}
this.objectif = function(){
let x = this.i*w;
let y = this.j*w;
noStroke();
image(sac, x, y, w, w);
}
this.zone = function(){
let x = this.i*w;
let y = this.j*w;
noStroke();
image(chinois, x, y, w, w);
}
this.show = function() {
let x = this.i*w;
let y = this.j*w;
stroke("black");
// épaisseur des murs
strokeWeight(8);
if (this.walls[0]){
line(x,y,x+w,y);
}
if (this.walls[1]){
line(x+w,y,x+w,y+w);
}
if (this.walls[2]){
line(x+w,y+w,x,y+w);
}
if (this.walls[3]){
line(x,y+w,x,y);
}
if (this.visited){
noStroke();
fill(255, 0, 255, 100);
rect(x, y ,w ,w);
}
}
}
function removeWalls(a, b){
let x = a.i - b.i;
if (x === 1){
a.walls[3] = false;
b.walls[1] = false;
}
else if (x === -1){
a.walls[1] = false;
b.walls[3] = false;
}
let y = a.j - b.j;
if (y === 1){
a.walls[0] = false;
b.walls[2] = false;
}
else if (y === -1){
a.walls[2] = false;
b.walls[0] = false;
}
}
// Déplacement dans le labyrinthe
let n = 0;
let t = 0;
function goUp(){
if (t > 0 && !current.walls[0]){
current = grid[index(n, t-1)];
t = t - 1;
let suite = ennemi.checkVoisins();
if (suite){
ennemi = suite;
}
// alerte victoire
if (current == grid[cols * rows - 1]){
alert("Vous avez gagné")
}
// alerte défaite
if (current == ennemi){
alert("Vous avez perdu")
}
}
}
function goRight(){
if (n < cols-1 && !current.walls[1]){
current = grid[index(n+1, t)];
n = n + 1;
let suite = ennemi.checkVoisins();
if (suite){
ennemi = suite;
}
// alerte victoire
if (current == grid[cols * rows - 1]){
alert("Vous avez gagné")
}
// alerte défaite
if (current == ennemi){
alert("Vous avez perdu")
}
}
}
function goDown(){
if (t < rows-1 && !current.walls[2]){
current = grid[index(n, t+1)];
t = t + 1;
// déplacement random chinois
let suite = ennemi.checkVoisins();
if (suite){
ennemi = suite;
}
// alerte victoire
if (current == grid[cols * rows - 1]){
alert("Vous avez gagné")
}
// alerte défaite
if (current == ennemi){
alert("Vous avez perdu")
}
}
}
function goLeft(){
if (n > 0 && !current.walls[3]){
current = grid[index(n-1, t)];
n = n - 1;
let suite = ennemi.checkVoisins();
if (suite){
ennemi = suite;
}
// alerte victoire
if (current == grid[cols * rows - 1]){
alert("Vous avez gagné")
}
// alerte défaite
if (current == ennemi){
alert("Vous avez perdu")
}
}
}
// déplacement ordinateur
window.addEventListener('keydown',doKeyDown,true);
function doKeyDown(evt)
{
switch (evt.keyCode) {
case 38: /* Up arrow was pressed */
goUp();
break;
case 40 : /* Down arrow was pressed */
goDown();
break;
case 37: /* Left arrow was pressed */
goLeft();
break;
case 39: /* Right arrow was pressed */
goRight();
break;
}
}
// Quiz random question
const questionText = document.querySelector(".question-text")
const optionContainer = document.querySelector(".option-container")
// const button = document.querySelector("#button")
let questionCounter = 0;
let currentQuestion;
let availableQuestions = [];
let availableOptions = [];
// push questions in availableQuestions array
function setAvailableQuestions(){
const totalQuestion = quiz.length;
for(let i =0; i<totalQuestion; i++){
availableQuestions.push(quiz[i])
}
}
function getNewQuestion(){
// numero de question
// questionNumber.innerHTML = "question " + (questionCounter+1) + " sur " + quiz.length;
// set question text
const questionIndex = availableQuestions[Math.floor(Math.random() * availableQuestions.length)]
currentQuestion = questionIndex;
questionText.innerHTML = currentQuestion.q;
const index1 = availableQuestions.indexOf(questionIndex);
// retirer la question de questionIndex pour ne pas la répéter
availableQuestions.splice(index1,1);
const optionLen = currentQuestion.options.length
for(let i = 0; i< optionLen; i++){
availableOptions.push(i)
}
for(let i = 0; i< optionLen; i++){
// random option
const optonIndex = availableOptions[Math.floor(Math.random() * availableOptions.length)];
// précup optionIndex dans availableOptions
const index2 = availableOptions.indexOf(optonIndex);
// enleve optionIndex de availableOptions no repeat
availableOptions.splice(index2, 1);
console.info(optonIndex);
const option = document.createElement("p");
option.innerHTML = currentQuestion.options[optonIndex];
option.id = optonIndex;
option.className = "option";
optionContainer.appendChild(option);
option.setAttribute("onclick", "get(this)");
}
questionCounter++
}
// changement de la class
function get(element){
document.getElementById(0).className = document.getElementById(0).className.replace(/(?:^|s)option correct(?!S)/g, 'option');
document.getElementById(1).className = document.getElementById(1).className.replace(/(?:^|s)option correct(?!S)/g, 'option');
document.getElementById(2).className = document.getElementById(2).className.replace(/(?:^|s)option correct(?!S)/g, 'option');
document.getElementById(3).className = document.getElementById(3).className.replace(/(?:^|s)option correct(?!S)/g, 'option');
element.classList.add("correct")
}
function test(){
const activeAnswer = document.querySelector(".correct");
console.info(activeAnswer.id);
if (currentQuestion.answer == activeAnswer.id){
console.info("correct");
}
}
// window.onload = function(){
// // mettre les questions dans le tableau
// setAvailableQuestions();
// // call une question
// getNewQuestion();
// }
А в консоли ошибка:
get
в вашем onclick
обработчике нет вашего function get(element)
это P5.js: https://p5js.org/reference/#/p5/get
Переименуйте свою функцию во что-то другое, например getElem
, и не устанавливайте атрибуты onevent
, вместо этого используйте addEventListener.
"onevent
атрибут", а не "одно событие" :-). Замените option.setAttribute("onclick", "get(this)");
на option.addEventListener("click", function(evt) { getElem(this); });
Не все герои носят плащ. Большое спасибо !
Спасибо за ответ, я изменил функцию «get» на «getElem», как вы сказали, но я не понимаю, что вы называете «одним событием», не могли бы вы дать мне строку, пожалуйста? Большое спасибо