I want to draw a couple of simple lines to a canvas but it will not work if I do not have beginPath() and restore() in my scripting code. Do you have to have these to draw something to the HTML 5 Canvas?
Code:
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.lineWidth="5";
ctx.strokeStyle="green"; // Green path
ctx.moveTo(0,75);
ctx.lineTo(250,75);
ctx.strokeStyle="purple"; // Purple path
ctx.moveTo(50,0);
ctx.lineTo(150,130);
</script>
</body>
</html>
A canvas deals with paths.
So, as the name suggests, beginPath will starts a new path.
Each retained draw command you will call after-wise will add-up to the current path.
( retained draw command are commands that have no direct effect : moveTo, lineTo, (Curve)To, arc, rect. )
Rq1 : Using moveTo is a special command : it will begin a new sub-path, it's like releasing the pen from the paper.
Rq2 : closePath is not required, use it if you want to link the last point to the first one easily.
When using fill or stoke, the current retained path (=all the sub-path of the current path) will get stroked/filled using current transform, clipping and color setting.
Notice that there are also direct command : fill/strokeRect, fill/strokeText, drawImage, get/putImageData.
Those commands do not require to begin a new path, and do not affect the current path -they directly draw on the canvas-.
So rule is simple :
• if you use retained commands, you must use beginPath.
• If you use direct commands do not use beginPath, just send the command.
As you noticed, you can change a lot of settings on the canvas :
• you have render settings : strokeStyle / fillStyle / globalCompositeOperation / globalAlpha / lineWidth / font / textAlign/ shadow / ...
• you have transform settings that allow you to translate/scale/rotate the next draw.
• you can define clipping to avoid the draw to occur in some areas.
save() and restore() allows you not to get lost in the status of the current canvas.
Rule is : anyway you change the context in a way that could affect the render of other drawings you make, just save() before, and restore after.
example 1 :
function strokeLine ( x1, y1, x2, y2, color) {
ctx.beginPath();
ctx.strokeStyle = color;
ctx.moveTo(x1, y1);
ctx.lineTo(x2,y2);
ctx.stroke();
}
i used moveTo/lineTo (retained) command, so without thinking i use beginPath.
here the strokeStyle is set on each call, so no need to save context.
example 2 :
function drawImageRotated( img, x, y, rotation ) {
ctx.save();
ctx.translate(x + img.width/2, y + img.height/2); // translate to the middle of the image
ctx.rotate(rotation); // rotate context
ctx.drawImage(img, x - img.width/2, y - img.height/2 ); // draw the image in rotated context
ctx.restore();
}
here no need to use beginPath() since i use only a direct command (drawImage).
But concerning canvas status, i don't want the context to remain translated/rotated after the call. So i started by a save, and ended by a restore, so the caller keeps the same context after the call.
beginPath() is used to start drawing a contour, you will need it. Then we use stroke() to actually draw to the HTML5 Canvas visually.
ctx.beginPath(); // Start drawing
// Drawing Methods Here
ctx.stroke() // Show what we drew.
Fiddle
restore() is for changes in the state of the Canvas: rotation, scaling, skew, etc. This method reverts it to the last state of the Canvas that was saved. But it isn't used for actually drawing on our canvas, but changing it's state.
Related
I want to draw something like a donut, so a circle with a hole in the middle. I tried using ctx.clip(), but I realized it limits the path to inside, and I want it to limit the path to the outside.
Things to note:
this.lineWidth is how thick the "rim" or the outside portion is
ctx.beginPath();
// this should be the hole
ctx.arc(this.x,this.y,this.r,0,Math.PI*2,false);
ctx.clip();
// this should be the outside part
ctx.arc(this.x,this.y,this.r+this.lineWidth,0,Math.PI*2,false);
ctx.fillStyle = "#00ff00";
ctx.fill();
Instead I'm getting a filled-in circle because it's limiting the path to inside the smaller arc instead of outside it. Is there another method that does the opposite of clip()?
I found this solution http://jsfiddle.net/Hnw6a/:
var can = document.getElementById('canvas1');
var ctx = can.getContext('2d');
//ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise);
ctx.beginPath()
ctx.arc(100,100,100,0,Math.PI*2, false); // outer (filled)
ctx.arc(100,100,55,0,Math.PI*2, true); // outer (unfills it)
ctx.fill();
With following canvas node:
<canvas id="canvas1" width="500" height="500"></canvas>
Set the linewidth to the desired width, draw your circle, and use "ctx.stroke();". Note that this doesn't allow you to fill the inner circle with a color.
I have been trying to print arc in the html page. How can i remove the already drawn arch from the page?. i have written the below code.
<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="1200" height="1000"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
/*ctx.beginPath();
ctx.arc(600,500,20, 0.5*Math.PI,2*Math.PI);
ctx.stroke();
ctx.beginPath();
ctx.arc(600,500,40, 0.5*Math.PI,2*Math.PI);
ctx.stroke();
*/
var radius=20;
for (i=0; i<10; i++)
{
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(600,500,radius, 0.5*Math.PI, 2*Math.PI);
ctx.stroke();
radius= radius+30;
}
</script>
</body>
</html>
How can i achieve this?.
Call clearRect method:
ctx.clearRect(0, 0, 1200, 1000)
The four arguments are:
axis-X of left top corner of the area to wipe
axis-Y of left top corner of the area to wipe
width of the area to wipe
height of the area to wipe
So with this method, you could wipe either the whole canvas or just a certain part of it.
If you want to remove the whole previously drawn image please take a look at the other anwers. In the comments OP made it clear that this is not what he was trying to achieve. So instead I will answer the intended question:
How do I un-stroke a path?
A bitmap is not a vector graphic. You cannot simply remove or modify things you've drawn previously. By drawing on a canvas you modify the pixel color values of its image data. If you need to undo things you have to maintain a separate data structure with the relevant data yourself.
For example you could create a copy of the image data before drawing something. Then you could return to this snapshot afterwards. HTMLCanvasElement#toDataURL returns the complete image as an url which you can use as the src of an image. Later you can draw this image on the canvas to revert all subsequent changes. HTMLCanvasElement#toBlob does about the same but it returns a blob. This might consume less memory but it's a little more inconvenient to use. The most convenient method is CanvasRenderingContext2D#getImageData. You can even use it to copy only a small part of the image. This is useful if you have a big canvas but only modify pixels in a small region.
Another way to make modifications undoable is by maintaining a detailed list of your steps. For example whenever you draw an arc you store the exact parameters as one entry in the list. steps.push({type: 'stroke', style: 'rgb(0,0,0)', shapes: [{type: 'arc', x: 600, y: 500, radius: radius, from: 0.5 * Math.PI, to: 2 * Math.PI}]}) You can remove, rearrange or modify the elements in this list any way you like and have all necessary information to draw the resulting image from scratch. Basically you've implemented just another vector graphic library.
I've created a game that works with canvas, and i need it to be in a very low resolution to fit a software I'm working with. besically when I draw a diagonal line it should appear as a diagonal row of squares.
I did
context.mozImageSmoothingEnabled = false;
context.webkitImageSmoothingEnabled = false;
context.imageSmoothingEnabled = false;
but it's just blurry. How can I convert it?
the top picture is what it looks like now and the bottom is what i want it to look like
One approach is to use image smoothing disabled with a low-resolution canvas. Though you will get a blocky line, you will also get the anti-aliased pixels included. The only way to avoid this is to implement line algorithms etc. yourselves such as Bresenham (see below example).
You can also draw the lines, then run through the bitmap pixel by pixel and use a threshold value to filter the anti-aliased pixels away but this will give various results and is dependent on having isolated paths to work with, ie. draw to off-screen, filter with threshold, then draw result to main canvas.
An example:
var mctx = main.getContext("2d"),
lowRes = document.createElement("canvas"),
ctx = lowRes.getContext("2d");
// setup low-res canvas (invisible)
lowRes.width = 32;
lowRes.height = 20;
// setup main visible canvas
mctx.imageSmoothingEnabled =
mctx.msImageSmoothingEnabled =
mctx.mozImageSmoothingEnabled =
mctx.webkitImageSmoothingEnabled = false;
// draw a line to off-screen canvas
ctx.moveTo(0, lowRes.height);
ctx.lineTo(lowRes.width - 7, 4);
ctx.lineWidth=4;
ctx.strokeStyle = "#fff";
ctx.stroke();
// draw bacground on main canvas
mctx.fillRect(0,0,500,300);
// draw in low-res line
mctx.drawImage(lowRes, 0,0,lowRes.width,lowRes.height,
0,0,main.width,main.height);
<canvas id="main" width=500 height=300></canvas>
I would also like to propose to check out my Retro Context library (free/GPL3) which was made for this very reason. It has implemented all these line algorithms and has a full and simple API to access them (and much more "retro" related).
Optionally, you would need to implement these line algorithms yourselves. Here are some resources to help you get started if you chose this approach:
Bresenham line algorithm
Mid-point circle algorithm
I have few coordinates in an XML file. They are lines, circles and arcs. I am reading them in a data structure and then trying to plot them on a canvas. What i am trying to figure out is how to divide the canvas into sub canvases. e.g suppose my canvas is
<canvas id="myCanvas" width="800" height="600" role="img">
Your browser does not support the canvas element.
</canvas>
What I am trying to achieve is how to make an imaginary window of width and height of 200px starting from say x1=200px on canvas and y1=250. And draw the image I have only in that box.
I have managed to scale down the image based on the imaginary box but cannot get around the concept of how to draw only in that imaginary box. The points are randomly distributed.
There are other ways to achieve this but the one you'll probably find most useful in this context is to use translation and a clip mask:
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
/// for simplicity, save current settings
ctx.save();
/// move coordinate system to the upper left corner of isolated region
ctx.translate(offsetX, offsetY);
/// create a clipping mask by using a simple rectangle
ctx.beginPath();
ctx.rect(0, 0, width, height);
/// define the last path (rectangle) as clipping mask
ctx.clip();
/// ... draw other things into this region from offset 0...
ctx.restore(); /// done and back to full canvas
By moving the whole coordinate system to the upper left corner of your region you can use offsets relative to the new isolated area. By adding a clip mask anything drawn outside the region will be clipped.
You will need to do this for each region one by one.
Another way is to add an offset to all drawing points. For example:
ctx.lineTo(x + offsetX, y + offsetY);
where offsetX/Y is the upper left corner of the region.
However, it will get more complicated if you need clipping - not a huge issue with images as you can define the destination region but for lines and and other path operation you will need to clip yourself by using interpolation etc.
Here is a live demo demonstrating this:
Fiddle (updated link)
The demo sets up a canvas and context and then fills the whole with a red color.
Then if sets the clipping and mask and translate it.
We now have a "virtual canvas" and the other graphic is intact
We now fill the region with the same fill operation but with blue. Now we can see only this regions is filled even the size is outside the actual region
Then we remove the clip and draw a line as evidence that we are now back in full mode
Say I drew a rectangle on the canvas. Surely there is some sort of built in method to get the XY coordinates, and dimensions of that rectangle? But after some googling I came up with nothing. And just to clarify, I am not talking about the coordinates of the canvas element itself, but rather a shape/image that is drawn unto the canvas.
Any help is appreciated.
If you're talking about a 2D canvas drawing, then the drawing maps 1:1 with screen coordinates, so it is just location of <canvas> + location of the drawing.
To clarify, drawing on a <canvas> basically just changes the pixels of the canvas - after you draw to it, you can't reference the drawn object the same way you can reference an html element.
Canvas is 2D table (Array) of numbers (= pixels = colors). When drawing into canvas, you are just editing this table. When you draw into canvas (= change numbers in table), what should be the coordinates of your adjustment?
If you are drawing rectangles only and you can define the coordinates for your rectangle, you must know your coordinates inside a program, because you have just drawn it.
If you want your image to be separated into some "objects" (shapes), you should use SVG.
Basically, you should be using canvas as a means to output graphics to the screen and the rest of your logic goes straight into the JavaScript that powers your game/application. The best way to go about making something like this is to create objects and assign properties to them; in its simplest form that can look like this:
function Player(x, y)
{
this.x = x;
this.y = y;
}
var examplePlayerObject = new Player(20, 20);
By extending this object via prototyping you can create multiple copies of an object that has the exact same functions; such as draw. Drawing the player in this instance could just be a red square that is 20px*20px.
Player.prototype.draw = function()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = 'red';
context.fillRect(this.x, this.y, 20, 20);
}
Then, you should have an update step with some means of clearing what is on the screen and redrawing the parts which have changed.
function animationStep()
{
examplePlayerObject.x++;
examplePlayerObject.y++;
examplePlayerObject.draw();
}
This animation step should run each frame; look into requestAnimationFrame for smooth animation. Paul Irish has a good shim for older browsers. Add in requestAnimationFrame(animationStep) at the end of that function and you will have a red square moving slowly across the screen. Good luck!