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!
Related
Say I have drawn a circle on a canvas that has something else drawn on it that stops me from clearing the canvas - due to the other element being randomly generated
var circleX = 50;
var circleY = 10;
var moveCircX = 2;
var moveCircY = 3;
function createCirc(){
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(circleX, circleY, 10, 0, Math.PI*2, true);
ctx.fill();
}
function circMove(){
circleY = (circleY + circMoveY)
//then validation to stop it from being drawn of the canvas
So what I'm trying to do is move the circle but clear the previous drawn circle from the canvas. So is there a solution to clearing the circle or would it be easier to create a sprite that replicates the circle?
Since your background isn't changing, the simplest strategy is to copy the background before you first draw your circle, then draw your circle. When you're moving, redraw that part of the background from the copy you kept, then draw your circle in the new place.
An efficient way to do that is to use getImageData and putImageData.
So, (my javascript is rusty, so this may not be perfect. Feel free to correct any mistakes), before the first time you createCirc, simply do:
imageData = ctx.getImageData(0,0, ctx.canvas.width, ctx.canvas.height)
And, in your circMove function, before you move and redraw the circle, you want:
ctx.putImageData(imageData, circleX, circleY, circleX, circleY, 2*circle_radius, 2*circle_radius)
(You don't define circle_radius, but I'm sure you must have a similar value. I'm using 2x the radius to presumably be the size of the image that is drawn.)
I want to use an image like this on canvas:
The user will "paint and fill" the image, but not on top of the outline.
The problem is:
If I put behind the canvas, the paint will cover the outline.
If I put over the canvas the image block canvas interaction.
Can you help me guys?
Use compositing mode "destination-over" to draw behind existing content (from image, vectors etc.). It's necessary that the existing content provide an alpha channel or composition won't work. If there is no alpha-channel you can convert inverse luma / matte (the white) to alpha channel.
// a quick-n-dirty demo
var ctx = c.getContext("2d");
ctx.lineWidth = 10;
ctx.moveTo(100, 0); ctx.lineTo(150, 150); ctx.stroke();
ctx.fillStyle = "#09f";
// KEY: composite mode -
ctx.globalCompositeOperation = "destination-over";
// draw behind the line
c.onmousemove = function(e) {
ctx.fillRect(e.clientX - 10, e.clientY - 10, 20, 20);
};
body {margin:0}
canvas {border:#777 solid 1px}
<canvas id="c"></canvas>
Here is the example of drawImage function. You can draw any preloaded image onto canvas. You can also try to place the <img> overlay in front of the canvas and disable mouse events for it using pointer-events: none CSS property.
I am drawing on a canvas object using JavaScript and somehow Internet Explorer (don't ask, I have to), Version 11 scales the drawings along the x axis.
Here is the JavaScript code:
var c = document.getElementById('canvas1');
var ctx = c.getContext('2d');
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#000000';
ctx.lineWidth = 5;
ctx.stroke();
You would expect a circle to appear. But instead I get an Ellipse:
(Don't mind the horizontal line on the left, that just the surrounding div. The canvas is the small square.)
EDIT: The size of the canvas is 100 x 100.
Following the comments the answer is to set height and width of the canvas object as attributes of the canvas-tag. Like this:
<canvas height="200" width="400"></canvas>
See this post for further explanation.
I am trying to make a 2d top-down game in Javascript at the moment. I've currently got a day/night system working where a black rectangle gradually becomes more opaque (as the day goes on) before it finally is fully opaque, simulating the peak of the night where the player can not see.
I want to implement an artificial light system, where the player could use a torch that will illuminate a small area in-front of them. However, my problem is that I don't seem to be able to find a way to 'cut out' a shape from my opaque rectangle. By cutting out a shape, it would look like the player has a torch.
Please find an example mock-up image I made below to show what I mean.
http://i.imgur.com/VqnTwoR.png
Obviously the shape shouldn't be as roughly drawn as that :)
Thanks for your time,
Cam
EDIT: The code used to draw the rectangle is as follows:
context.fillStyle = "#000033";
context.globalAlpha = checkLight(gameData.worldData.time);
context.fillRect(0, 0, 512, 480);
//This is where you have to add the cut out triangles for light!
context.stroke();
Instead of drawing a rectangle over the scene to darken it when the "light" is on, instead draw an image with the "lit" area completely transparent and the rest of the "dark" area more opaque.
One way is to use declare a triangular clipping area and draw your revealed scene. The scene would display only inside the defined clipping area.
Example code and a Demo:
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var x = canvas.width / 2;
var y = canvas.height / 2;
var radius = 75;
var offset = 50;
var img = new Image();
img.onload = function() {
knockoutAndRefill(50,100,300,50,75,350);
};
img.src = 'http://guideimg.alibaba.com/images/trip/1/03/18/7/landscape-arch_68367.jpg';
function knockoutAndRefill(x0,y0,x1,y1,x2,y2){
context.save();
context.fillStyle='black';
context.fillRect(0,0,canvas.width,canvas.height);
context.beginPath();
context.moveTo(x0,y0);
context.lineTo(x1,y1);
context.lineTo(x2,y2);
context.closePath();
context.clip();
context.drawImage(img,0,0);
context.restore();
}
<canvas id=myCanvas width=500 height=400>
How can I draw only a circular part of an image using HTML 5 canvas?
For instance, to take a photo and only draw the face inside the canvas.
The way to achieve this is to use clip to define a clipping region:
var ctx;
var canvas;
var img = new Image();
img.onload = function() {
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 100, 60, 0, 6.28, false); //draw the circle
ctx.clip(); //call the clip method so the next render is clipped in last path
ctx.stroke();
ctx.closePath();
ctx.drawImage(img, -190, 0);
};
img.src = "http://www.antiquiet.com/wp-content/uploads/2011/03/Free-Trapper_Remasters_The-Kills-467x311.jpg";
You can see a working fiddle here: http://jsfiddle.net/hJS5B/47/
Code reused from my answer to this question: Draw multiple circles filled with image content
As I found this thread long before I found the solution for what I was searching for: the code above works great. But if you want to draw circular areas of an image again and again, e.g. in an onmouseup event, then you have to save and restore the state of the context. More is explained here: Can you have multiple clipping regions in an HTML Canvas?