如何在画布上复制剪辑图像

时间:2014-03-24 10:27:30

标签: html html5-canvas

下面的代码运行正常,但如何制作我的“StopLicht”副本并将副本放在画布的其他位置?

<!DOCTYPE html>
<html>
<body>
<p>Image to use:</p>
<img id="sprite-sheet" src="logi.bmp" alt="Logi" width="220" height="277">
<p>Canvas:</p>
<canvas id="myCanvas" width="512" height="380" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var img = document.getElementById("sprite-sheet"); 
    function StopLicht() {
//rij x groen stoplicht
ctx.drawImage(img, 64, 8,8,8,80, 0,8,8);
ctx.drawImage(img, 72, 8,8,8,88, 0,8,8);
ctx.drawImage(img, 80, 8,8,8,80, 8,8,8);
ctx.drawImage(img, 88, 8,8,8,88, 8,8,8);
ctx.drawImage(img,112,24,8,8,80,16,8,8);
ctx.drawImage(img,120,24,8,8,88,16,8,8);   
ctx.drawImage(img, 96, 8,8,8,80,24,8,8);
ctx.drawImage(img,104, 8,8,8,88,24,8,8);
}
StopLicht();   //geef het stoplicht weer. en is goed !
</script>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

是的,您可以使用canvas translate将红绿灯重新定位到画布上的任何x,y位置:

context.translate(x,y)会将画布原点(0,0)移动到x,y。

这意味着您可以在不改变x,y位置的情况下使用现有的drawImage命令。

function StopLicht(x,y) {

    //save the untransformed context state
    ctx.save();

    // move the canvas to the desired xy coordinate
    ctx.translate(x,y);

    //rij x groen stoplicht
    ctx.drawImage(img, 64, 8,8,8,80, 0,8,8);
    ctx.drawImage(img, 72, 8,8,8,88, 0,8,8);
    ctx.drawImage(img, 80, 8,8,8,80, 8,8,8);
    ctx.drawImage(img, 88, 8,8,8,88, 8,8,8);
    ctx.drawImage(img,112,24,8,8,80,16,8,8);
    ctx.drawImage(img,120,24,8,8,88,16,8,8);   
    ctx.drawImage(img, 96, 8,8,8,80,24,8,8);
    ctx.drawImage(img,104, 8,8,8,88,24,8,8);

    // restore the context to its untransformed state
    ctx.restore();

}

[补充:示例用法]

此循环将打印2行10个灯:

for(var row=0;row<2;row++){
for(var col=0;col<10;col++){
    StopLicht(row*12,col*12);
}}