更改画布中单击的图像

时间:2011-09-12 18:05:42

标签: javascript html5 canvas

我正在制作这个简单的画布。它有三个图像(相同的图像)。我想只更改点击的图像。我想要做的是将图像顺序保存在数组中。并且只更改被点击的图像的索引。 到目前为止,我无能为力!我已经用硬编码完成了它,但cnt一般这样做,因为我知道用户点击的位置。如果我可以在点击鼠标时获得鼠标的位置或点击图像的ID我可以做一些事情,但我是新的html5所以我不知道怎么做,任何人都可以指出我在右边方向?这是我的代码

    <style> 
        body {
            margin: 0px;
            padding: 0px;
        }

        #myCanvas {
            border: 2px solid #9C9898;
        }
    </style> 
    <script> 

       if(window.addEventListener) {

window.addEventListener('load', function ()
{

           var my = new Array();
var i=0;
            var canvas = document.getElementById("myCanvas");
            var context = canvas.getContext("2d");
            var imageObj = new Image();
            var imageObj1 = new Image();
            imageObj.onload = function(){
 imageObj1.src = "watermelon-duck-outline.png";
 for (var x = 0; x <= 1200;x += 400 ) { alert(i,x);
  my[i]=imageObj;
 context.drawImage(imageObj, x, 0);
++i;
}
context.drawImage(imageObj, 0, 0);
            }
            imageObj.src = "tomato2.jpg";

            change.addEventListener('mousedown', function ()      {ButtonDown (change)}, false);

            function ButtonDown (change)
{ canvas.width = canvas.width; 
 i--;
 for (var x = 800; x >= 0;x -= 400 ) {
  if(i!=2){my[i]=imageObj;}else{my[i]=imageObj1;}
 context.drawImage(my[i], x, 0);
i--;
}}



         init();
}, false); }
    </script> 
</head> 
<body >

    <canvas id="myCanvas" width="1250" height="650"> 
    </canvas>
    <button id="change" type="button">Change</button>

</body> 

1 个答案:

答案 0 :(得分:1)

<强> Live Demo

我就是这样做的。基本上你需要存储每个图像的x,y,width,height。您需要这些值,以便在画布中单击时可以检查每个图像的边界与鼠标单击的x和y。之后,很容易参考哪个图像被点击。希望以下代码足以让您走上正确的轨道。

var canvas = document.getElementById("myCanvas"),
    ctx = canvas.getContext("2d");

ctx.fillStyle = "#f00";
ctx.strokeStyle = "#0f0";

var images = [];
images.push({x : 10, y : 10, width:50, height:50}, {x : 70, y : 10, width:50, height:50}, {x : 130, y : 10, width:50, height:50});

//draw some rects, this would be your images
for(var i = 0; i < images.length; i++){
    ctx.fillRect(images[i].x, images[i].y, images[i].width, images[i].height); 
}

canvas.onclick = function(e){
    var x = 0,
        y = 0;

    if (e.pageX || e.pageY) { 
        x = e.pageX;
        y = e.pageY;
    }
    else { 
        x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; 
        y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; 
    } 

    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;

// This is where you go through all the images, and check the x and y from the mouse event against your images.
    for(var i = 0; i < images.length; i++){
        if(x > images[i].x && x < images[i].x + images[i].width && y > images[i].y && y < images[i].y + images[i].height){
            ctx.strokeRect(images[i].x, images[i].y, images[i].width, images[i].height); 
          alert('Image ' + i + ' selected');  
        }
    }
}