Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

javascript - How to rotate one image in a canvas?

I am making an HTML5 canvas game, and I wish to rotate one of the images.

var link = new Image();
link.src='img/link.png';
link.onload=function(){
    ctx.drawImage(link,x,y,20,20); // draws a chain link or dagger
}

I wish to rotate this image. The standard way of rotating image was to set a rotation on the canvas context object. However, that rotates the entire game! I don't want to do that, and only wish to rotate this one sprite. How do I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use .save() and .restore() (more information):

link.onload=function(){
    ctx.save(); // save current state
    ctx.rotate(Math.PI); // rotate
    ctx.drawImage(link,x,y,20,20); // draws a chain link or dagger
    ctx.restore(); // restore original states (no rotation etc)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...