简体   繁体   中英

HTML5 canvas - text on rotated rectangle

I'm trying to place text on sqlare rotated 45 degrees. The problem is my text is under the rectangle shape. Can I change position of text?

my code is like

var c = document.getElementById("myCanvas");
var square= c.getContext("2d");
var text= c.getContext("2d");

text.fillStyle = "red";
text.fillText("1", 40, 50);
text.fillStyle = "#000000";

square.rotate(Math.PI / 4);
square.fillRect(50, 0, 50, 50);

jsfiddle

You're drawing the text first, then the rectangle, and then wondering why the text is behind the rectangle?

Firstly, you only need to getContext once, not twice.

Second, draw things in the right order: background first, then foreground.

It appears you may have a misconception about how the canvas context works.

You see, you only need one instance of the context , which you can then use to create all your shapes, paths and even write text on the canvas.

Also, you are drawing the text before the rectangle, which would cover it up.

With that in mind, I've created a new JSFiddle where you can check out a correct approach to do this.

HTML

<canvas id="myCanvas" width="300" height="150">
  Your browser does not support the HTML5 canvas tag.
</canvas>

JavaScript

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d"); //we get the canvas context

ctx.save(); //save context properties

ctx.rotate(Math.PI / 4);
ctx.fillRect(50, 0, 50, 50);

ctx.restore(); //restore saved properties

ctx.fillStyle = "red";
ctx.fillText("1", 40, 50);

As you can see, we only take one instance of the context, and we draw from there.

The context save() and restore() functions help prevent the rotation from affecting the text. You could also rotate the same amount in the opposite direction.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM