html - How to copy a clip image on the canvas -


the code below works fine how can make copy of "stoplicht" , place copy elsewhere on canvas?

<!doctype html> <html> <body> <p>image 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;"> browser not support 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 goed ! </script> </body> </html> 

yes, can use canvas translate reposition stoplight x,y position on canvas:

context.translate(x,y) move canvas origin(0,0) x,y.

this means can existing drawimage commands without altering each of x,y positions.

function stoplicht(x,y) {      //save untransformed context state     ctx.save();      // move canvas 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 context untransformed state     ctx.restore();  } 

[ addition: example usage ]

this loop print 2 rows of 10 lights:

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

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -