Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

407
Visualizações
How do I add canvas drawings to an array and determine if an array value is an image or canvas drawing?

I need an array which can include canvas drawings and/or images.

Drawing example below:

function drawCircle() {
ctx.beginPath();
ctx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
ctx.fillStyle = 'black;
ctx.fill();
ctx.strokeStyle = 'orange';
ctx.stroke();
ctx.closePath();
}

Image example below:

const LIFE_IMG=new Image();
LIFE_IMG.src="images/life.png"

Array;

let LIFE_ARRAY=[LIFE_IMG,LIFE_IMG,LIFE_IMG];

Draw:

function drawLife(imgY2,imgWidth,imgHeight){
LIFE_ARRAY.forEach(function(item, index) {

let offsetY,imgX,imgY;
offsetY=(imgHeight+5)*(index+1)
imgX=(SCOREBOARD_WIDTH/2)-(imgWidth/2)
imgY=imgY2
    }
ctx.drawImage(item, imgX, imgY+offsetY, imgWidth, imgHeight);
  })
}

I need to be able to

  1. push the canvas drawing to the array

  2. determine if the array value is an image or canvas drawing

  3. draw the canvas drawing or the image

Part 2 was answered on an old stack overflow thread with:

function isImage(i) {return i instanceof HTMLImageElement;}

but I can't figure out how to tie it into my code.

Any help would be greatly appreciated!

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Usually you just have one on-screen <canvas> element. So your sample code:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let Life = {
  x: 100,
  y: 100,
  radius: 50
};

function drawCircle() {
  ctx.beginPath();
  ctx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
  ctx.fillStyle = 'black';
  ctx.fill();
  ctx.strokeStyle = 'orange';
  ctx.stroke();
  ctx.closePath();
}

drawCircle();
<canvas id="canvas"></canvas>

draws a circle on the on-screen canvas' context. This is just a drawing operation though, so there is no reference to it making it sort of an object. In the end it's just pixel data somewhere on the canvas.

Although I don't see an use-case, what you want to achieve can be done of course. The trick here is to create individual off-screen canvases for all canvas drawings you want to store in the array.

A <canvas> element can be created at runtime using:

document.createElement('canvas')

If we modify your drawCircle() function a little so it draws to an off-screen canvas and returns it, you can even call this function from within your array to push it's reference into.

function drawCircle() {
  let tempCanvas=document.createElement('canvas');
  let tempCtx=tempCanvas.getContext('2d');
    tempCtx.beginPath();
    tempCtx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
    tempCtx.fillStyle = 'black';
    tempCtx.fill();
    tempCtx.strokeStyle = 'orange';
    tempCtx.stroke();
    tempCtx.closePath();
  return tempCanvas;
}

As you already figured yourself an image is an instance of HTMLImageElement. Likewise a canvas is of HTMLCanvasElement. This can be used in the forEach loop to distinct one from the other.

Here's an example:

let canvas = document.getElementById('canvas');
let ctx = canvas.getContext('2d');

let Life = {
    x: 100,
    y: 100,
    radius: 50
};

function drawCircle() {
    let tempCanvas = document.createElement('canvas');
    let tempCtx = tempCanvas.getContext('2d');
    tempCtx.beginPath();
    tempCtx.arc(Life.x, Life.y, Life.radius, 0, Math.PI * 2);
    tempCtx.fillStyle = 'black';
    tempCtx.fill();
    tempCtx.strokeStyle = 'orange';
    tempCtx.stroke();
    tempCtx.closePath();
    return tempCanvas;
}

drawCircle();

const LIFE_IMG = new Image();
LIFE_IMG.src = "images/life.png";

let LIFE_ARRAY = [LIFE_IMG, drawCircle(), LIFE_IMG];

LIFE_ARRAY.forEach(function(item, index) {
    if (item instanceof HTMLImageElement) {
        console.log("an Image");
    }
    if (item instanceof HTMLCanvasElement) {
        console.log("a Canvas");
    }
});
 <canvas id="canvas"></canvas>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda