Ciao a tutti sto attualmente testando l'elemento canvas per disegnare tutti gli sfondi (aggiungerò effetti più tardi a queste immagini ed è la ragione per cui non uso CSS per caricare le immagini), detto che attualmente sto avendo difficoltà a caricare un'immagine sulla tela. Ecco il codice:Caricamento di un'immagine su una tela con javaScript
<html>
<head>
<title>Canvas image testing</title>
<script type="text/javascript">
function Test1() {
var ctx = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
//Loading of the home test image - img1
var img1 = new Image();
img1.src = 'img/Home.jpg';
//drawing of the test image - img1
img1.onload = function() {
//draw background image
ctx.drawimage(img1, 0, 0);
//draw a box over the top
ctx.fillStyle = "rgba(200, 0, 0, 0.5)";
ctx.fillRect(0, 0, 500, 500);
};
}
}
</script>
<style type="text/css">
canvas { border: 2px solid black; width: 100%; height: 98%; }
</style>
</head>
<body onload="Test1();">
<canvas id="canvas" width="1280" height="720"></canvas>
</body>
penso che non sto caricando l'immagine correttamente, ma non sono sicuro.
freejosh è giusto, ma volevo solo aggiungere che non è uno stile molto buono usare la variabile 'ctx' per la tela e sovrascriverla con il contesto successivo. Si potrebbe usare 'var canvas' per il riferimento del canvas. – Mathias
Grazie: D che risolve il problema mi sento un po 'noob ma grazie !!! –
Una domanda, perché dobbiamo impostare l'origine dell'immagine dopo l'evento onload? – Eliyah