Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

html - draw square and rotate it?

how come this doesn't work? does rotate only work with images?

            context.moveTo(60,60);
            context.lineTo(200,60);
            context.lineTo(200,200);
            context.lineTo(60,200);
            context.lineTo(60,60);


            context.stroke();
            context.rotate(45 * Math.PI / 180);
            context.restore();
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You are rotating the whole canvas when you use context.rotate, and since the pivot point is defaulted at the coordinates (0, 0), your square sometimes will be drawn out of bounds.

By moving the pivot point to the middle of the square, you can then rotate it successfully.

Note: Make sure you rotate the canvas before you draw the square.

// pivot point coordinates = the center of the square
var cx = 130; // (60+200)/2
var cy = 130; // (60+200)/2

// Note that the x and y values of the square 
// are relative to the pivot point.
var x = -70; // cx + x = 130 - 70 = 60
var y = -70; // cy + y = 130 - 70 = 60
var w = 140; // (cx + x) + w = 60 + w = 200
var h = 140; // (cy + y) + h = 60 + h = 200
var deg = 45;

context.save();

context.translate(cx, cy);
context.rotate(deg * Math.PI/180);

context.fillRect(x, y, w, h);

context.restore();


Explanation:

  • context.save(); saves the current state of the coordinate system.

  • context.translate(cx, cy); moves the pivot point.

  • context.rotate(deg * Math.PI/180); rotates the square to deg degrees (Note that the parameter is in radians, not degrees)

  • context.fillRect( x, y, w, h ); draws the square

  • context.restore(); restores the last state of the coordinate system.

Here is a JS Fiddle example.

Here is another JS Fiddle example that features a HTML5 slider.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...