I am trying to replace a image I have added to a canvas with a mouseOver event. I don’t think I am doing this right.
<script>
function loadImage(){
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
var cat = new Image();
cat.src = "images/paul01.jpg";
cat.onload = function() {
context.drawImage(cat, 0, 0, 166, 276);
};
}
</script>
<script>
function mouseOver(); {
var canvas = document.getElementById("e");
var context = canvas.getContext("2d");
var cat = new Image();
cat.src = "images/paul02.jpg";
cat.onload = function() {
context.drawImage(cat, 0, 0, 166, 276);
};
}
</script>
<a href=""onmouseover="mouseOver"()>
<div class="canvas">
<canvas id="e" width="166" height="276">
<p>No Canvas Support in Browser, old fashion image?</p>
<img src="images/paul01.jpg">
</canvas>
</div>
</a>
New Code:
I am trying to change the image in canvas ID ‘A’ with mouse out on canvas ‘e’ I have been able to get the mousover to work and add a image to canvas ‘A’, but not remove it.
<script>
function init() {
setImageOne();
}
function setImageOne() { setImage('images/paul01.jpg'); }
<!--function setImageTwo() { setImage('images/paul02.jpg'); }-->
function unsetImageOne() { largeImage('images/full/cartoonPaul02.jpg'); }
function setImageTwo() { largeImage('images/full/cartoonPaul01.jpg'); }
function setImage(src) {
var canvas = document.getElementById("l");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.src = src;
context.drawImage(img, 0, 0, 166, 276);
}
function largeImage(src){
var canvas = document.getElementById("A");
var context = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.src = src;
context.drawImage(img, 0, 0, 300, 400);
}
</script>
<div id="container">
<header>
<a href='../../'><h3>Everything else</h3></a>
</header>
<div id="main" role="main">
<body onload="init()">
<div class="canvas">
<canvas id="l" width="166" height="276" onmouseover="setImageTwo()" onmouseout="unsetImageOne()"></canvas>
</div>
<div class="canvas">
<canvas id="A" width="300" height="400"></canvas>
</div>
There are a couple syntax errors and misconceptions in your code. Below is a simplified, working example. You can put the mouse handlers right onto the canvas element. Your loadImage() function isn’t even used. I also added an onmouseout() to revert the image, although I’m not sure that’s your intended behavior.