问题
I am trying to change the image in canvas ID 'A' with mouseout on canvas ID '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>
回答1:
Removing something from a canvas is impossible in such that when you draw something, only pixels are saved. There is therefore no concept of an image anymore after drawing.
What you can do, however, is clearing the full canvas before drawing another image. This code might be appropriate for largeImage
. The same goes for smallImage
. I also advise you to use image.onload
to make sure the image is only drawn when it is fully loaded.
function largeImage(src){
var canvas = document.getElementById("A");
var context = canvas.getContext("2d");
var canvas2 = document.getElementById("l");
var context2 = canvas.getContext("2d");
if (context == null) return;
var img = new Image();
img.src = src;
context2.clearRect(0, 0, 166, 276);
img.onload = function() {
context.drawImage(img, 0, 0, 300, 400);
}
}
来源:https://stackoverflow.com/questions/7110555/how-to-remove-canvas-image-on-a-onmouseout