单击时,使图像开始显示在画布上

时间:2012-12-12 22:09:37

标签: javascript image canvas onclick

基本上我已经让我的代码工作了,因为当页面加载图像时开始在画布上一个接一个地显示,但是我希望图像在鼠标点击时开始显示,你能告诉我吗?怎么做?

<script>

window.onload = function() {



var canvas=document.getElementById("myCanvas").addEventListener("mousedown",    function() // Selects the canvas element
var context=canvas.getContext("2d"); 

var img1 =new Image() //creates a variable for a new image
var img2 =new Image() //creates a variable for a new image
var img3 =new Image() //creates a variable for a new image
var img4 =new Image() //creates a variable for a new image

img1.src = "canvasimg1.png" // Gets image
img2.src = "canvasimg2.png" // Gets image
img3.src = "canvasimg3.png" // Gets image
img4.src = "canvasimg4.png" // Gets image

setTimeout(                                             // Settimeout - execute the passed function after the amount of milliseconds
    function() { context.drawImage(img1,23,20); }       // Function to be executed
, 1000);                                                // Amount of milliseconds to delay for

setTimeout(                                             // Settimeout - execute the passed function after the amount of milliseconds
    function() { context.drawImage(img2, 23, 60); }     // Function to be executed
, 6000);                                                // Amount of milliseconds to delay for

setTimeout(                                             // Settimeout - execute the passed function after the amount of milliseconds
    function() { context.drawImage(img3, 25, 120); }    // Function to be executed
, 11000);                                               // Amount of milliseconds to delay for

setTimeout(                                             // Settimeout - execute the passed function after the amount of milliseconds
    function() { context.drawImage(img4, 150, 180); }   // Function to be executed
, 16000);                                               // Amount of milliseconds to delay for
}

</script>

1 个答案:

答案 0 :(得分:0)

如果您需要在单击画布时开始显示图像,则将四个setTimeout函数放在另一个函数中,并且只有在画布上单击时才调用此函数!

 <canvas id="exemple" width="200" height="200" onclick="showImage()">


function showImage(){
    setTimout.....
     ....
   }