How to properly clear a rotated HTML5 canvas context? - javascript

I need to clear a rotated rectangle and draw it again on a canvas, either at the same place or elsewhere. The problem is, the cleared part doesn't match the rectangle's bounds, leaving dirty bits behind.
var cvs = document.getElementById('testcanvas');
var ctx = cvs.getContext('2d');
var rectColor = 'green';
var x = 300;
var y = 10;
var width = 200;
var height = 150;
var rotation = 0;
setInterval(animate, 100);
function animate(){
clearRect();
update();
drawRect();
}
function clearRect(){
ctx.save();
ctx.rotate(rotation);
ctx.clearRect(x, y, width, height);
ctx.restore();
}
function update(){
rotation += 0.1;
x++;
}
function drawRect(){
ctx.save();
ctx.fillStyle = rectColor;
ctx.rotate(rotation);
ctx.fillRect(x, y, width, height);
ctx.restore();
}
​
http://jsfiddle.net/MFz2z/15/
Another issue, clearRect() behaves differently on Firefox when the canvas is rotated, by clearing the whole unrotated space used by the rotated rectangle.
http://jsfiddle.net/MFz2z/17/
Is there any workaround to this, other than clearing the whole canvas and drawing everything again ? I use Chrome 22 and Firefox 15.0.1.

It could be due to the anti-aliasing of the pixels that create the extra tidbits.
You could use this http://jsfiddle.net/MFz2z/28/ and basically clear 1 more pixel from each side.

Related

Is there a way to make a rectangular area 0 alpha (transparent) after it has been drawn on to? [duplicate]

After experimenting with composite operations and drawing images on the canvas I'm now trying to remove images and compositing. How do I do this?
I need to clear the canvas for redrawing other images; this can go on for a while so I don't think drawing a new rectangle every time will be the most efficient option.
Given that canvas is a canvas element or an OffscreenCanvas object, use clearRect:
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
Use: context.clearRect(0, 0, canvas.width, canvas.height);
This is the fastest and most descriptive way to clear the entire canvas.
Do not use: canvas.width = canvas.width;
Resetting canvas.width resets all canvas state (e.g. transformations, lineWidth, strokeStyle, etc.), it is very slow (compared to clearRect), it doesn't work in all browsers, and it doesn't describe what you are actually trying to do.
Dealing with transformed coordinates
If you have modified the transformation matrix (e.g. using scale, rotate, or translate) then context.clearRect(0,0,canvas.width,canvas.height) will likely not clear the entire visible portion of the canvas.
The solution? Reset the transformation matrix prior to clearing the canvas:
// Store the current transformation matrix
context.save();
// Use the identity matrix while clearing the canvas
context.setTransform(1, 0, 0, 1, 0, 0);
context.clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
context.restore();
Edit:
I've just done some profiling and (in Chrome) it is about 10% faster to clear a 300x150 (default size) canvas without resetting the transform. As the size of your canvas increases this difference drops.
That is already relatively insignificant, but in most cases you will be drawing considerably more than you are clearing and I believe this performance difference be irrelevant.
100000 iterations averaged 10 times:
1885ms to clear
2112ms to reset and clear
If you are drawing lines, make sure you don't forget:
context.beginPath();
Otherwise the lines won't get cleared.
Others have already done an excellent job answering the question but if a simple clear() method on the context object would be useful to you (it was to me), this is the implementation I use based on answers here:
CanvasRenderingContext2D.prototype.clear =
CanvasRenderingContext2D.prototype.clear || function (preserveTransform) {
if (preserveTransform) {
this.save();
this.setTransform(1, 0, 0, 1, 0, 0);
}
this.clearRect(0, 0, this.canvas.width, this.canvas.height);
if (preserveTransform) {
this.restore();
}
};
Usage:
window.onload = function () {
var canvas = document.getElementById('canvasId');
var context = canvas.getContext('2d');
// do some drawing
context.clear();
// do some more drawing
context.setTransform(-1, 0, 0, 1, 200, 200);
// do some drawing with the new transform
context.clear(true);
// draw more, still using the preserved transform
};
This is 2018 and still there is no native method to completely clear canvas for redrawing. clearRect() does not clear the canvas completely. Non-fill type drawings are not cleared out (eg. rect())
1.To completely clear canvas irrespective of how you draw:
context.clearRect(0, 0, context.canvas.width, context.canvas.height);
context.beginPath();
Pros: Preserves strokeStyle, fillStyle etc.; No lag;
Cons: Unnecessary if you are already using beginPath before drawing anything
2.Using the width/height hack:
context.canvas.width = context.canvas.width;
OR
context.canvas.height = context.canvas.height;
Pros: Works with IE
Cons: Resets strokeStyle, fillStyle to black; Laggy;
I was wondering why a native solution does not exist. Actually, clearRect() is considered as the single line solution because most users do beginPath() before drawing any new path. Though beginPath is only to be used while drawing lines and not closed path like rect().
This is the reason why the accepted answer did not solve my problem and I ended up wasting hours trying different hacks. Curse you mozilla
Chrome responds well to: context.clearRect ( x , y , w , h ); as suggested by #Pentium10 but IE9 seems to completely ignore this instruction.
IE9 seems to respond to: canvas.width = canvas.width; but it doesn't clear lines, just shapes, pictures and other objects unless you also use #John Allsopp's solution of first changing the width.
So if you have a canvas and context created like this:
var canvas = document.getElementById('my-canvas');
var context = canvas.getContext('2d');
You can use a method like this:
function clearCanvas(context, canvas) {
context.clearRect(0, 0, canvas.width, canvas.height);
var w = canvas.width;
canvas.width = 1;
canvas.width = w;
}
Use clearRect method by passing x,y co-ordinates and height and width of canvas. ClearRect will clear whole canvas as :
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
A quick way is to do
canvas.width = canvas.width
Idk how it works but it does!
there are a ton of good answers here.
one further note is that sometimes it's fun to only partially clear the canvas.
that is, "fade out" the previous image instead of erasing it entirely.
this can give nice trails effects.
it's easy. supposing your background color is white:
// assuming background color = white and "eraseAlpha" is a value from 0 to 1.
myContext.fillStyle = "rgba(255, 255, 255, " + eraseAlpha + ")";
myContext.fillRect(0, 0, w, h);
This is what I use, regardless boundaries and matrix transformations:
function clearCanvas(canvas) {
const ctx = canvas.getContext('2d');
ctx.save();
ctx.globalCompositeOperation = 'copy';
ctx.strokeStyle = 'transparent';
ctx.beginPath();
ctx.lineTo(0, 0);
ctx.stroke();
ctx.restore();
}
Basically, it saves the current state of the context, and draws a transparent pixel with copy as globalCompositeOperation. Then, restores the previous context state.
I always use
ctx.fillStyle = "rgb(255, 255, 255)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
For a custom color, and
ctx.clearRect(0, 0, canvas.width, canvas.height);
For making the canvas transparent when clearing
This worked for my pieChart in chart.js
<div class="pie_nut" id="pieChartContainer">
<canvas id="pieChart" height="5" width="6"></canvas>
</div>
$('#pieChartContainer').html(''); //remove canvas from container
$('#pieChartContainer').html('<canvas id="pieChart" height="5" width="6"></canvas>'); //add it back to the container
the shortest way:
canvas.width += 0
I have found that in all browsers I test, the fastest way is to actually fillRect with white, or whataever color you would like. I have a very large monitor and in full screen mode the clearRect is agonizingly slow, but the fillRect is reasonable.
context.fillStyle = "#ffffff";
context.fillRect(0,0,canvas.width, canvas.height);
The drawback is that the canvas is no longer transparent.
private clearCanvas() {
const canvas: HTMLCanvasElement = this.ctx.canvas
this.ctx.save()
this.ctx.setTransform(1, 0, 0, 1, 0, 0)
this.ctx.clearRect(0, 0, canvas.width, canvas.height)
this.ctx.restore()
}
in webkit you need to set the width to a different value, then you can set it back to the initial value
function clear(context, color)
{
var tmp = context.fillStyle;
context.fillStyle = color;
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
context.fillStyle = tmp;
}
A simple, but not very readable way is to write this:
var canvas = document.getElementId('canvas');
// after doing some rendering
canvas.width = canvas.width; // clear the whole canvas
Context.clearRect(starting width, starting height, ending width, ending height);
Example: context.clearRect(0, 0, canvas.width, canvas.height);
I always use this
ctx.clearRect(0, 0, canvas.width, canvas.height)
window.requestAnimationFrame(functionToBeCalled)
NOTE
combining clearRect and requestAnimationFrame allows for more fluid animation if that is what you're going for
If you use clearRect only, if you have it in a form to submit your drawing, you'll get a submit instead the clearing, or maybe it can be cleared first and then upload a void drawing, so you'll need to add a preventDefault at the beggining of the function:
function clearCanvas(canvas,ctx) {
event.preventDefault();
ctx.clearRect(0, 0, canvas.width, canvas.height);
}
<input type="button" value="Clear Sketchpad" id="clearbutton" onclick="clearCanvas(canvas,ctx);">
Hope it helps someone.
This is a Free hand drawing Canvas with a Clear Canvas Button.
See this live example of a canvas which you can draw on and also when required clear it for redrawing clearRect() is used to delete the prersent canvas and fillRect() is used to again draw the initial canvas which was clean and had no drawings on it.
var canvas = document.getElementById("canvas"),
ctx = canvas.getContext("2d"),
painting = false,
lastX = 0,
lastY = 0,
lineThickness = 1;
canvas.width=canvas.height = 250;
ctx.fillRect(0, 0, 250, 250);
canvas.onmousedown = function(e) {
painting = true;
ctx.fillStyle = "#ffffff";
lastX = e.pageX - this.offsetLeft;
lastY = e.pageY - this.offsetTop;
};
canvas.onmouseup = function(e){
painting = false;
}
canvas.onmousemove = function(e) {
if (painting) {
mouseX = e.pageX - this.offsetLeft;
mouseY = e.pageY - this.offsetTop;
// find all points between
var x1 = mouseX,
x2 = lastX,
y1 = mouseY,
y2 = lastY;
var steep = (Math.abs(y2 - y1) > Math.abs(x2 - x1));
if (steep){
var x = x1;
x1 = y1;
y1 = x;
var y = y2;
y2 = x2;
x2 = y;
}
if (x1 > x2) {
var x = x1;
x1 = x2;
x2 = x;
var y = y1;
y1 = y2;
y2 = y;
}
var dx = x2 - x1,
dy = Math.abs(y2 - y1),
error = 0,
de = dy / dx,
yStep = -1,
y = y1;
if (y1 < y2) {
yStep = 1;
}
lineThickness = 4;
for (var x = x1; x < x2; x++) {
if (steep) {
ctx.fillRect(y, x, lineThickness , lineThickness );
} else {
ctx.fillRect(x, y, lineThickness , lineThickness );
}
error += de;
if (error >= 0.5) {
y += yStep;
error -= 1.0;
}
}
lastX = mouseX;
lastY = mouseY;
}
}
var button=document.getElementById("clear");
button.onclick=function clearcanvas(){
canvas=document.getElementById("canvas"),
ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, 250, 250);
canvas.width=canvas.height = 250;
ctx.fillRect(0, 0, 250, 250);}
#clear{border-radius:10px;
font-size:8px !important;
position:absolute;
top:1px;}
#canvas{border-radius:10px}
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<button id="clear" class="w3-padding w3-xxlarge w3-pink" type="button">Clear Canvas</button>
<canvas id="canvas"></canvas>
There is now a .reset() method which will not only clear the canvas buffer but also completely reset all the properties of the context (styles etc.), reset its transformation matrix, clear its current sub-path, clear its states stack (the one controlled by save() and restore()), and remove all the clipping regions.
context.reset();
// now 'context' is clear as new
Basically, it has the same effects as canvas.width += 0, except that it's more idiomatic.
However it seems that in current Chromium's implementation it's as slow as canvas.width += 0, it also does generate a new buffer instead of simply clearing the previous one (resulting in more memory garbage). Another caveat is that it's currently only supported in Chromium browsers.
Though to polyfill it you can go the Chrome way
if (!CanvasRenderingContext2D.prototype.reset) {
CanvasRenderingContext2D.prototype.reset = function() {
this.canvas.width += 0;
};
}
if (!OffscreenCanvasRenderingContext2D.prototype.reset) {
OffscreenCanvasRenderingContext2D.prototype.reset = function() {
this.canvas.width += 0;
};
}
These are all great examples of how you clear a standard canvas, but if you are using paperjs, then this will work:
Define a global variable in JavaScript:
var clearCanvas = false;
From your PaperScript define:
function onFrame(event){
if(clearCanvas && project.activeLayer.hasChildren()){
project.activeLayer.removeChildren();
clearCanvas = false;
}
}
Now wherever you set clearCanvas to true, it will clear all the items from the screen.
fastest way:
canvas = document.getElementById("canvas");
c = canvas.getContext("2d");
//... some drawing here
i = c.createImageData(canvas.width, canvas.height);
c.putImageData(i, 0, 0); // clear context by putting empty image data

Rotating element on canvas object, relative to parent

I'm trying to draw a pair of skis (two rectangles) on a skier (a square) at varying rotations. I don't quite understand how you line up rotated elements on a canvas as you rotate the whole canvas, not just the object.
At the moment I have this:
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = skiier.color;
ctx.fillRect(skiier.x, skiier.y, skiier.width, skiier.height);
ctx.fillStyle = '#00f';
var angle = 20;
ctx.rotate(angle*Math.PI/180);
ctx.fillRect(skiier.x, skiier.y,100,10);
ctx.fillRect(skiier.x, skiier.y + 20,100,10);
ctx.rotate(-angle*Math.PI/180);
Which gives me this:
But what I'd like to do is the following:
Bearing in mind the x and y coords of the skier is constantly changing, how can I adjust and position the skis relative to him?
I have a demo here if it helps:
http://codepen.io/EightArmsHQ/pen/cfa7052ed205b664b066450910c830c5?editors=001
You should consider the context save, restore and translate as follows:
// ...
var angle = 20;
ctx.save(); // save the state of the ctx
ctx.translate(skiier.x, skiier.y); // translate your context point to be the same as skiier.
ctx.rotate(angle * Math.PI / 180);
ctx.fillRect(-25, 0, 100, 10); // You can draw from new context point.
ctx.fillRect(-25, 20, 100, 10); // Same here.
// Instead of rotating back, use restore()...
// Useful to restore all ctx options as they were before the save()
ctx.restore();
To rotate around a point: you need to translate context to the point, rotate context, translate context back.
For example...
ctx.fillStyle = 'rgba(0,0,0,0.8)';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = skiier.color;
ctx.fillRect(skiier.x, skiier.y, skiier.width, skiier.height);
ctx.fillStyle = '#00f';
var angle = 20;
ctx.translate(skiier.x, skiier.y);
ctx.rotate(angle*Math.PI/180);
ctx.translate(-skiier.x, -skiier.y);
ctx.fillRect(skiier.x, skiier.y,100,10);
ctx.fillRect(skiier.x, skiier.y + 20,100,10);
ctx.rotate(-angle*Math.PI/180);

Canvas polygons not touching properly

So I've been fiddling with the canvas element, and I seem to have run into a situation that is highly irritating, yet I haven't been able to find a solution.
Say that two polygons are drawn on a canvas, and that they should be touching each other. Where one polygon is drawn like this:
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
A simple version is implemented in this fiddle.
As you can probably see there is a thin line between these shapes. How can I avoid it? I have tried the solutions here, but they don't really seem to refer to this case, because I'm dealing with diagonal lines.
One solution
You could always use the stroke-line trick, but depending on your goal:
If it is to show many polygons next to each other, you could look at the polygons as simple squares.
Draw them in as such in an off-screen canvas next to each other. This will produce a result with no gaps.
Then transform the main canvas into the position you want those polygons to appear. Add rotation and/or skew depending on goal.
Finally, draw the off-screen canvas onto the main canvas as an image. Problem gone.
This will give you an accurate result with no extra steps in stroking, and the calculations for the boxes becomes very simple and fast to do (think 2d grid).
You have to use an off-screen canvas though. If you transform main canvas and draw in the shapes you will encounter the same problem as already present. This is because each point is transformed and if there is need for interpolation it will be calculated for each path shape separately. Drawing in an image will add interpolation on the whole surface, and only where there are gaps (non-opaque alpha). As we already are "gap-free" this is no longer a problem.
This will require an extra step in planning to place them correctly, but this is a simple step.
Example
Step 1 - draw boxes into an off-screen canvas:
This code draws on the off-screen canvas resulting in two boxes with no gap:
(the example uses an on-screen to show result, see next step for usage of off-screen canvas)
var ctx = document.querySelector("canvas").getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);
ctx.fillRect(60, 10, 50, 50);
<canvas/>
Step 2 - transform main canvas and draw in off-screen canvas
When drawn into main canvas with transformation set, the result will be (pseudo-random transformation just to show):
var ctx = document.querySelector("canvas").getContext("2d");
// off-screen canvas
var octx = document.createElement("canvas").getContext("2d");
octx.fillStyle = "red";
octx.fillRect(10, 10, 50, 50);
octx.fillRect(60, 10, 50, 50);
// transform and draw to main
ctx.translate(80, 0);
ctx.rotate(0.5, Math.PI);
ctx.transform(1, 0, Math.tan(-0.5),1, 0,0); // skew
ctx.drawImage(octx.canvas, 0, 0);
<canvas />
Step 3 (optional) - Interaction
If you want to interact with the boxes you simply apply the same transform, then add path for a box and hit-test it against the mouse position. Redraw a single state, erase by clearing and draw back the off-screen canvas on top:
var ctx = document.querySelector("canvas").getContext("2d");
// off-screen canvas
var octx = document.createElement("canvas").getContext("2d");
octx.fillStyle = "red";
octx.fillRect(10, 10, 50, 50);
octx.fillRect(60, 10, 50, 50);
// allow us to reuse some of the steps:
function getTransforms() {
ctx.setTransform(1,0,0,1,0,0);
ctx.translate(80, 0);
ctx.rotate(0.5, Math.PI);
ctx.transform(1, 0, Math.tan(-0.5),1, 0,0); // skew
}
function clear() {
ctx.setTransform(1,0,0,1,0,0);
ctx.clearRect(0,0,300,150);
}
function redraw() {
ctx.drawImage(octx.canvas, 0, 0);
}
getTransforms();
redraw();
ctx.canvas.onmousemove = function(e) {
var r = this.getBoundingClientRect(),
x = e.clientX - r.left, y = e.clientY - r.top;
// box 1 (for many, use array)
ctx.beginPath();
ctx.rect(10, 10, 50, 50);
clear(); // these can be optimized to use state-flags
getTransforms(); // so they aren't redraw for every move...
redraw();
// just one box check here
if (ctx.isPointInPath(x, y)) {
ctx.fill();
}
};
<canvas />
Yes, it's annoying when filled polygons result in that tiny gap. It's especially common on diagonals that should theoretically meet.
A common workaround is to put a half-pixel, same-colored stroke around the polygons:
//Some basic setup ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var oX = 50;
var oY = 50;
var h = 33;
var k = 50;
ctx.fillStyle = 'red';
ctx.strokeStyle='red';
ctx.lineWidth=0.50;
//Draw one polygon
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
//Draw another polygon
oX = oX+k;
oY = oY+h;
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
//Some basic setup ...
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var oX = 50;
var oY = 50;
var h = 33;
var k = 50;
ctx.fillStyle = 'red';
ctx.strokeStyle='red';
ctx.lineWidth=0.50;
//Draw one polygon
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
//Draw another polygon
oX = oX+k;
oY = oY+h;
ctx.beginPath();
ctx.moveTo(oX,oY);
ctx.lineTo(oX=oX+k,oY=oY-h);
ctx.lineTo(oX=oX+k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY+h);
ctx.lineTo(oX=oX-k,oY=oY-h);
ctx.fill();
ctx.stroke();
#canvas{border:1px solid red;}
<canvas id="canvas" width=300 height=300></canvas>

Canvas animation pixelated

I want to animate an Arc on Canvas, and it works (with a really basic animation, interval), but the outcome is very pixelated/edgy. On the left side I draw an arc (animated), on the right side without animation (smooth).
JsFiddle: http://jsfiddle.net/C8CXz/2/
function degreesToRadians (degrees) {
return degrees * (Math.PI/180);
}
function radiansToDegrees (radians) {
return radians * (180/Math.PI);
}
var canvas = document.getElementById('circle');
var ctx = canvas.getContext('2d');
var start = 0, end = 0;
var int = setInterval(function(){
end++;
ctx.beginPath();
ctx.arc(80, 80, 50, degreesToRadians(0)-Math.PI/2, degreesToRadians(end)-Math.PI/2, false);
ctx.lineWidth = 10;
ctx.stroke();
if(end >= 360) {
clearInterval(int);
}
}, 10);
ctx.beginPath();
ctx.arc(220, 80, 50, degreesToRadians(0)-Math.PI/2, degreesToRadians(360)-Math.PI/2, false);
ctx.lineWidth = 10;
ctx.stroke();
(raw simple code, dont mind the sloppiness)
You need a:
ctx.clearRect(0, 0, w, h);
In each draw loop.
Basically, you are drawing the same arc over itself hundreds of times. The edge pixels that are only partially black are bing darkened over and over until they are completely black.
Things like this are way nearly all canvas animations clear the canvas and draw fresh for each iteration.
Try clearing the drawing rectangle on every frame
ctx.clearRect(x,y,width,height);
http://jsfiddle.net/C8CXz/3/
I found that I first need the clear the canvas.
ctx.clearRect(0, 0, canvas.width, canvas.height);

Moving Objects on html5 Canvas

I placed an text on html5 canvas object using fillText option, question is I need to move the text position or change the color of the text that is already rendered.
Shortly I need to know how to Manipulate particular child of canvas element
This will move a small circle over your canvas
var can = document.getElementById('canvas');
can.height = 1000; can.width = 1300;
var ctx = can.getContext('2d');
var x = 10, y = 100;
ctx.fillStyle = "black";
ctx.fillRect(700, 100, 100, 100);
function draw() {
ctx.beginPath();
ctx.arc(x, y, 20, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(250,0,0,0.4)';
ctx.fill();
x += 2;
ctx.fillStyle = "rgba(34,45,23,0.4)";
ctx.fillRect(0, 0, can.width, can.height);
requestAnimationFrame(draw);
//ctx.clearRect(0,0,can.width,can.height);
}
draw();
<canvas id="canvas" style="background:rgba(34,45,23,0.4)"></canvas>
I think there is no object model behind the canvas, so you cannot access a "child object" like a "text object" and change it.
What you can do is that you draw the text again with a different color that overwrites the "pixels" of the canvas.
If you want to move the text, first you have to either clear the canvas or re-draw the text with a background/transparent color to get rid of the text in the previous position. Then you can draw the text in the new position.
I've never tried it but I think this would be the way to do it.
var canvas = document.getElementById("canvas"); //get the canvas dom object
var ctx = canvas.getContext("2d"); //get the context
var c = { //create an object to draw
x:0, //x value
y:0, //y value
r:5; //radius
}
var redraw = function(){ // this function redraws the c object every frame (FPS)
ctx.clearRect(0, 0, canvas.width, canvas.height); // clear the canvas
ctx.beginPath(); //start the path
ctx.arc(c.x, c.y, c.r, 0, Math.PI*2); //draw the circle
ctx.closePath(); //close the circle path
ctx.fill(); //fill the circle
requestAnimationFrame(redraw);//schedule this function to be run on the next frame
}
function move(){ // this function modifies the object
var decimal = Math.random() // this returns a float between 0.0 and 1.0
c.x = decimal * canvas.width; // mulitple the random decimal by the canvas width and height to get a random pixel in the canvas;
c.y = decimal * canvas.height;
}
redraw(); //start the animation
setInterval(move, 1000); // run the move function every second (1000 milliseconds)
Here is a fiddle for it.
http://jsfiddle.net/r4JPG/2/
If you want easing and translations, change the move method accordingly.
Hope it is allowed to advertise somebody's project.
Take a look at http://ocanvas.org/ you can get inspiration there.
It is object like canvas library. Allows you to handle events, make animations etc.
<html>
<head>
<title>Canvas Exam</title>
</head>
<body>
<canvas id="my_canvas" height="500" width="500" style="border:1px solid black">
</canvas>
<script>
var dom=document.getElementById("my_canvas");
var ctx=dom.getContext("2d");
var x1=setInterval(handler,1);
var x=50;
var y=50;
r=40;
function handler()
{
ctx.clearRect(0,0,500,500);
r1=(Math.PI/180)*0;
r2=(Math.PI/180)*360;
ctx.beginPath();
//x=x*Math.random();
x=x+2;
r=r+10*Math.random();
ctx.arc(x,y,r,r1,r2);
ctx.closePath();
ctx.fillStyle="blue";
ctx.fill();
ctx.stroke();
if(x>400)
{
x=50;
y=y+10;
}
r=40;
}
</script>
</body>
</html>

Categories

Resources