image does not appear in javascript

Asked

Viewed 75 times

-2

 var canvas = document.getElementById("canvas"); 
 var contexto = canvas.getContext("2d");
 contexto.fillStyle = "dimgray";
 contexto.fillRect(0,0, canvas.width, canvas.height);
 contexto.fillStyle = "lightgray";
 contexto.fillRect(0,0, canvas.width, 80);
 contexto.fillStyle = "lightgray";
 contexto.fillRect(0,380, canvas.width,100);
 contexto.fillStyle = "white";

for(var i = 0; i <25; i++)
{
    contexto.fillRect(i*30-5, 185, 20, 4);
    contexto.fillRect(i*30-5, 280, 20, 4);
}
var imagem = new image();
imagem.src = "http://a-dilminha.appspot.com/dilminha.png"

var x = 320;
var y = 400;

imagem.onload = function(){
//a imagem não aparece
contexto.drawImage(imagem, x, y, imagem.width, imagem.height)
}

the image does not appear or load, I tried everything and did not find an answer.

complete code

  • didn’t work...

2 answers

1


The Javascript image builder is actually called Image. In your code, you put new image() instead of new Image(), with a capital "I".

I hope I’ve helped!

  • Thanks!!! it worked! just didn’t give upvote because I can’t...

0

In addition to the error cited by Gustavo Sampaio, the event onload should be applied to imagem which is the image to be uploaded, and not to contexto which refers to the canvas. Simply change contexto.onload for imagem.onload:

var canvas = document.getElementById("canvas"); 
var contexto = canvas.getContext("2d");
contexto.fillStyle = "dimgray";
contexto.fillRect(0,0, canvas.width, canvas.height);
contexto.fillStyle = "lightgray";
contexto.fillRect(0,0, canvas.width, 80);
contexto.fillStyle = "lightgray";
contexto.fillRect(0,380, canvas.width, 100);
contexto.fillStyle = "white";

for(var i = 0; i <25; i++)
    {
        contexto.fillRect(i*30-5, 185, 20, 4);
        contexto.fillRect(i*30-5, 280, 20, 4);
    }
var imagem = new Image();
imagem.src = "http://a-dilminha.appspot.com/dilminha.png"

var x = 320;
var y = 0;

imagem.onload = function(){
   contexto.drawImage(imagem, x, y, imagem.width, imagem.height);
}
<canvas id="canvas" width="640" height="480" style="border: solid 1px black; margin: 0px auto; display: block;"></canvas>

  • thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.