How do I clear text from the <canvas> element? - html

I have put text on an image in a <canvas> tag (the text was taken from an input box).
Now if I put a new text on the <canvas>, it is imposed on the previous text. How do I clear the existing text on the canvas before putting in the new text?
I have tried resetting the canvas by assigning canvas.width but the text stays on. Any help people?

If you know you're going to be adding and removing text a lot, it might make sense to keep track of the old text. Then you could just use this:
context.fillStyle = '#ffffff'; // or whatever color the background is.
context.fillText(oldText, xCoordinate, yCoordinate);
context.fillStyle = '#000000'; // or whatever color the text should be.
context.fillText(newText, xCoordinate, yCoordinate);
This way you don't have to redraw the whole canvas every time.

You use context.clearRect(), but first you have to figure out the rectangle to clear. This is based off a number of factors, such as the size of the text and the textAlign property of the canvas context when the text was originally drawn. The code below would be for the draw method of a object that draws text into a canvas context, as such it has properties for x, y, text size, horizontal alignment etc. Note that we always store the last piece of text drawn so we can clear an appropriately sized rectangle when the value is next changed.
this.draw = function() {
var metrics = this.ctx.measureText(this.lastValue),
rect = {
x: 0,
y: this.y - this.textSize / 2,
width: metrics.width,
height: this.textSize,
};
switch(this.hAlign) {
case 'center':
rect.x = this.x - metrics.width / 2;
break;
case 'left':
rect.x = this.x;
break;
case 'right':
rect.x = this.x - metrics.width;
break;
}
this.ctx.clearRect(rect.x, rect.y, rect.width, rect.height);
this.ctx.font = this.weight + ' ' + this.textSize + ' ' + this.font;
this.ctx.textAlign = this.hAlign;
this.ctx.fillText(this.value, this.x, this.y);
this.lastValue = this.value;
}

You need to use clearRect(x, y, w, h); More details at MDC

If you can't clear other drawings in the same area of the text, another solution is to have two canvas, one over the other:
<div style="position: relative;">
<canvas id="static" width="1350" height="540" style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
<canvas id="dynamic" width="1350" height="540" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
</div>
Then you can use the first for static drawings that don't need to be removed, and the other one with dynamic drawings. In your case you can put the text in the dynamic canvas and remove it with clearRect before drawing again.
context.clearRect(0, 0, canvas.width, canvas.height);

I'm not sure about how to clear the text off the image before you put the next piece of text.
If the background of the canvas is constant; and your only changing the text you could layer two canvas elements. The background, and a transparent top layer for text that can be removed and a new one inserted when you want to update the text.

not sure if it would work, but you could try redrawing the text in the background color

Here is the best approach and it worked for me. Clear function is just to clear the recaptcha. So just call this function when you refresh.
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge'>
<title>Page Title</title>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<link rel='stylesheet' type='text/css' media='screen' href='main.css'>
<script src='main.js'></script>
</head>
<body>
<h4>Canvas</h4><canvas width="200" height="100" id="cnv1"></canvas><br/>
<button id="clear_cnv">Clear</button> - <button id="setnr_cnv">Set Nr</button>
<script type="text/javascript">
// <![CDATA[
// function to clear the canvas ( https://coursesweb.net/ )
// cnv = the object with the canvas element
function clearCanvas(cnv) {
var ctx = cnv.getContext('2d'); // gets reference to canvas context
ctx.beginPath(); // clear existing drawing paths
ctx.save(); // store the current transformation matrix
// Use the identity matrix while clearing the canvas
ctx.setTransform(1, 0, 0, 1, 0, 0);
ctx.clearRect(0, 0, cnv.width, cnv.height);
ctx.restore(); // restore the transform
}
// sets and adds a random number in canvas
// cnv = the object with the canvas element
function addNrCnv(cnv) {
// gets a random number between 1 and 100
var nr = Math.floor(Math.random() * 100 + 1);
var ctx = cnv.getContext('2d'); // gets reference to canvas context
// create text with the number in canvas (sets text color, font type and size)
ctx.fillStyle = '#00f';
ctx.font = 'italic 38px sans-serif';
ctx.fillText(nr, 80, 64);
}
// get a reference to the <canvas> tag
var cnv1 = document.getElementById('cnv1');
// register onclick event for #clear_cnv button to call the clearCanvas()
document.getElementById('clear_cnv').onclick = function() { clearCanvas(cnv1); }
// register onclick event for #setnr_cnv button to call the addNrCnv()
document.getElementById('setnr_cnv').onclick = function() { addNrCnv(cnv1); }
// ]]>
</script>
</body>
</html>

Related

html5 canvas text slide in behind nothing

I want to have html5 canvas text slide in behind nothing, its an effect where text appears like coming out behind some obstacle, but the obstacle is invisible.
Here is some youtube video showing how to do it in after effect:
https://www.youtube.com/watch?v=KIYMy7vLLRo
I know how to slide a text along canvas, and one idea I got is having two canvases on top of each other, and top canvas is smaller and contains the text that is initially out of canvas and slides in. But if there is a way to do it with just one canvas that would be great.
You can using a clipping path to mask out part of the text.
Save the existing clipping path using the save() method. Create a shape/path and make it the new clipping path using the clip() method. Draw your text. Store the previous clipping path using the restore() method.
For example, suppose your canvas is 100 pixels by 100 pixels. The following will draw text on only the left side of the canvas.
context.save();
context.rect(0, 0, 50, 100);
context.clip();
context.fillText("Draw some text.", 30, 50);
context.restore();
jsFiddle : https://jsfiddle.net/CanvasCode/vgpov2yk/3
var c = document.getElementById('myCanvas');
var ctx = c.getContext("2d");
// Positions for the text startint off
var xText = -100;
var yText = 150;
// This will update the canvas as fast as possible (not good)
setInterval(function () {
// Clear the canvas
ctx.fillStyle = "#F0F";
ctx.fillRect(0, 0, c.width, c.height);
ctx.save()
// We create a clip rect
ctx.rect(200,0,400,400);
ctx.clip();
// Draw text
ctx.fillStyle = "#FFF";
ctx.font = "30px Arial";
ctx.fillText("Hello World", xText, yText);
ctx.restore();
// Increase the text x position
if (xText < 200) {
xText += 0.5;
}
}, 15);
All you have to do is use a clip rect which is like a mask in image editing.

clearRect not working?

I am a very beginner web designer and I have two questions about this code.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#canvas1{border: #666 3px solid;}
</style>
<script type="application/javascript" language="javascript">
function draw (x,y){
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillstyle = "rgb (0,200, 0)";
ctx.fillRect(x, 20, 50, 50);
ctx.restore();
x += 5;
var loop = setTimeout('draw('+x+', '+y+')', 100);
}
</script>
</head>
<body>
<button onclick="draw(0,0)">Start</button>
<canvas id="canvas1" width="400" height="400"</canvas>
</body>
</html>
Why does the block always turn out black? and Why if I try to press start again, the clearRect function doesn’t work?
When you click start you are starting a new loop that runs parallel to the one already started and depending on which one executes first your canvas would be cleared and filled twice (or as many times you started the loop - the more the more pronounced the flicker will be).
You need a mechanism to prevent the loop from starting several times. One way is to use a flag. I would also suggest you refactor the code a bit separating the loop and the drawing:
Live demo here
/// put these outside, no need to re-allocate them each time
var canvas = document.getElementById('canvas1');
var ctx = canvas.getContext('2d');
var w = canvas.width;
var h = canvas.height;
var x = 0;
var isRunning = false;
/// all loop-related here:
function loop() {
/// call draw from inside the loop instead
draw(x, 0); /// you are never using y so I just set 0 here...
x += 5;
if (isRunning && x <= w) {
requestAnimationFrame(loop); /// this is a better alternative
//setTimeout(loop, 100); /// optionally, but not recommended
} else {
isRunning = false; /// box is outside visible area so we'll stop..
}
}
/// keep draw() "clean", no loop code in here:
function draw(x, y) {
/// no need for save/restore here...
ctx.clearRect(0, 0, w, h);
ctx.fillStyle = "rgb(0, 200, 0)";
ctx.fillRect(x, 20, 50, 50);
}
Your fillStyle was typed wrong, your rgb(... must be without space (as mentioned in the other answer - but it would only result in the fill style being black in this case), in addition you're missing a closing bracket for your canvas tag in the html.
To check for button clicks this is a more recommended way instead of inlining the JS in the html:
/// check for button clicks (start):
document.getElementById('start').addEventListener('click', function() {
if (!isRunning) { /// are we running? if not start loop
isRunning = true; /// set flag so we can prevent multiple clicks
x = 0; /// reset x
loop(); /// now we start the *loop*
}
}, false);
And in your html:
<button id="start">Start</button>
Now you can easily make a pause button:
<button id="stop">Stop</button>
and add this to the script:
document.getElementById('stop').addEventListener('click', function() {
isRunning = false;
}, false);
Because you need to use:
ctx.fillStyle = "rgb(0,200,0)";
with a capital 'S' and no space between 'rgb' and the opening bracket: http://jsfiddle.net/dtHjf/
Then, in terms of why pressing 'Start' multiple times causes the square to flicker, that's because each time you press it you're starting another animation loop, but without cancelling the old one, so that you've got multiple loops fighting with each other. If you make sure to cancel any pre-existing loop before you start a new one, you should be fine:
http://jsfiddle.net/dtHjf/2/
HTML:
<button id="startAnim">Start</button><br />
<canvas id="canvas1" width="400" height="400"></canvas>
JS:
var canvas = document.getElementById('canvas1'),
ctx = canvas.getContext('2d'),
loop;
function draw(x, y) {
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "rgb(0,200,0)";
ctx.fillRect(x, 20, 50, 50);
ctx.restore();
x += 5;
loop = setTimeout(function(){draw(x,y)}, 100);
}
document.getElementById('startAnim').onclick = function(){
clearTimeout(loop);
draw(0,0);
};
Also, this is unrelated to your problem, but you might want to take a look at requestAnimationFrame:
https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/

is mouse in user drawn area on canvas

Basically, a user uploads a picture and then can paint on it, and save the result. Another user can then view the photo and if they click in the same area as painted, something happens.
So user 1 can make an area click-able for user 2 by drawing on the photo.
now the upload bit is fine, and painting with help from a tutorial and example I've got sussed out. But defining what area is click-able is a bit harder. For something like a rectangle its easy enough, I made an example.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var button = new Object();
button.x = 50;
button.y = 50;
button.width = 50;
button.height = 50;
button.rgb = "rgb(0, 0, 255)";
function drawbutton(buttonobject)
{
context.fillStyle = buttonobject.rgb;
context.fillRect (buttonobject.x, buttonobject.y, buttonobject.width, buttonobject.height);
context.strokeRect(buttonobject.x, buttonobject.y, buttonobject.width, buttonobject.height);
}
drawbutton(button);
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY)
{
if(((mouseX > buttonObj.x) && (mouseX < (buttonObj.x + buttonObj.width))) && ((mouseY > buttonObj.y) && (mouseY < (buttonObj.y + buttonObj.height))))
return true;
else
return false;
}
$("#myCanvas").click(function(eventObject) {
mouseX = eventObject.pageX - this.offsetLeft;
mouseY = eventObject.pageY - this.offsetTop;
if(checkIfInsideButtonCoordinates(button, mouseX, mouseY))
{
button.rgb = "rgb(0, 255, 0)";
drawbutton(button);
} else {
button.rgb = "rgb(255, 0, 0)";
drawbutton(button);
}
});
but when it comes to other shapes like circles, or just someone smothering the page, how would you go about detecting that ?
one thought I had was using the edited layer, making it hidden, and detecting a pixel color of say blue, from here but that limits the color use of the photo and im not entirely sure how to implement it. any other ideas ?
EDIT:
I figured out circles after some tinkering, using Pythagoras theorem to see if mouse coordinates are smaller than the radius, but this assumes circle center of 0,0, so then offset mouse by circles actual center. example
function checkIfInsideButtonCoordinates(buttonObj, mouseX, mouseY) {
actualX = mouseX - buttonObj.x
actualY = mouseY - buttonObj.y
mousesqX = actualX * actualX
mousesqY = actualY * actualY
sqR = buttonObj.r * buttonObj.r
sqC = mousesqX + mousesqY
if (sqC < sqR) return true;
else return false;
}
Here’s how to test whether user#2 is inside user#1’s paintings
Create a second canvas used to hit-test whether user#2 is inside of user#1’s paintings.
The hit-test canvas is the same size as the drawing canvas, but it only contains user#1’s paintings…not the image.
When user#1 is painting, also draw their paintings on the hit canvas.
When user#1 is done painting, save all their paintings from the hit canvas.
You have at least 2 ways to save user#1’s paintings from the hit canvas:
Serialize all the canvas commands needed to recreate the shapes/paths that user#1 paints.
Save the hit canvas as an image using canvas.toDataURL.
When user#2 clicks, check if the corresponding pixel on the hit canvas is filled or is transparent (alpha>0).
// getImageData for the hit-test canvas (this canvas just contains user#1's paintings)
imageDataData=hitCtx.getImageData(0,0,hit.width,hit.height).data;
// look at the pixel under user#2's mouse
// return true if that pixel is filled (not transparent)
function isHit(x,y){
var pixPos=(x+y*hitWidth)*4+3;
return( imageDataData[pixPos]>10)
}
Here is code and a Fiddle: http://jsfiddle.net/m1erickson/etA5a/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; padding:15px; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var hit=document.getElementById("hit");
var hitCtx=hit.getContext("2d");
var user2=document.getElementById("user2");
var ctx2=user2.getContext("2d");
var canvasOffset=$("#user2").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var imageDataData;
var hitWidth=hit.width;
var img=document.createElement("img");
img.onload=function(){
// left canvas: image+user#1 paintings
ctx.globalAlpha=.25;
ctx.drawImage(img,0,0);
ctx.globalAlpha=1.00;
scribble(ctx,"black");
// mid canvas: just user#1 paintings (used for hittests)
scribble(hitCtx,"black");
// right canvas: user#2
ctx2.drawImage(img,0,0);
imageDataData=hitCtx.getImageData(0,0,hit.width,hit.height).data;
}
img.src="https://dl.dropboxusercontent.com/u/139992952/stackoverflow/colorhouse.png";
function scribble(context,color){
context.beginPath();
context.moveTo(70,2);
context.lineTo(139,41);
context.lineTo(70,41);
context.closePath();
context.rect(39,54,22,30);
context.arc(73,115,3,0,Math.PI*2,false);
context.fillStyle=color;
context.fill();
}
function handleMouseMove(e){
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
// If user#2 has a hit on user#1's painting, mid-canvas turns red
var color="black";
if(isHit(mouseX,mouseY)){ color="red"; }
scribble(hitCtx,color);
}
function isHit(x,y){
var pixPos=(x+y*hitWidth)*4+3;
return( imageDataData[pixPos]>10)
}
$("#user2").mousemove(function(e){handleMouseMove(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Left: original image with user#1 painting</p>
<p>Mid: user#1 painting only (used for hit-testing)</p>
<p>Right: user#2 (move mouse over hit areas)</p>
<canvas id="canvas" width=140 height=140></canvas>
<canvas id="hit" width=140 height=140></canvas>
<canvas id="user2" width=140 height=140></canvas><br>
</body>
</html>

HTML5 Canvas, shadowColor & shadowBlur

My question is regarding this shadowBlur feature used on the 2nd (outer) rectangle below. The shadowBlur feature is applied to every shape after this rectangle. (If you comment out the shadowColor and shadowBlur lines 21 & 22, and then uncomment the shadowColor and shadowBlur lines on lines 14 & 15, you should see what I mean.) My question is, how do I apply shadowBlur to one specific portion of the Canvas drawing without applying the feature to every succeeding portion of the Canvas. In this example I have tried creating separate variable for each canvas and context, but the problem still persists.
Attribution: These examples are based on examples from html5canvastutorials.com
<!DOCTYPE html>
<html lang="en"
<head>
<script type="text/javascript">
function addRect(){
var canvas1=document.getElementById("myCanvas");
var ctx=canvas1.getContext("2d");
var canvas3=document.getElementById("myCanvas");
var ctx3=canvas3.getContext("2d");
ctx.rect(60,60,180,80);
ctx.fillStyle="green";
//ctx.shadowColor="black";
//ctx.shadowBlur = 10;
ctx.fill();
ctx3.lineWidth = 3;
ctx3.strokeStyle='red';
ctx3.shadowColor="black";
ctx3.shadowBlur = 10;
ctx3.strokeRect(45,45,210,110);
}
function addOval(){
var canvas2=document.getElementById("myCanvas");
var context=canvas2.getContext("2d");
// define center of oval
var centerX = 288;
var centerY = 250;
// define size of oval
var height = 100;
var width = 250;
var controlRectWidth = width * 1.33;
context.beginPath();
context.moveTo(centerX,centerY - height/2);
// draw left side of oval
context.bezierCurveTo(centerX-controlRectWidth/2,centerY-height/2,
centerX-controlRectWidth/2,centerY+height/2,
centerX,centerY+height/2);
// draw right side of oval
context.bezierCurveTo(centerX+controlRectWidth/2,centerY+height/2,
centerX+controlRectWidth/2,centerY-height/2,
centerX,centerY-height/2);
context.fillStyle="red";
context.fill();
context.lineWidth=5;
context.strokeStyle="blue";
context.stroke();
context.closePath();
}
</script>
</head>
<body onload="addRect(); addOval();">
<canvas id="myCanvas" width="700" height="400">
Your browser does not support the canvas element.
</canvas>
</body>
</html>
Use either this:
ctx.save();
ctx.shadowColor="black";
ctx.shadowBlur = 10;
ctx.strokeRect(45,45,210,110);
ctx.restore();
Or this:
ctx.shadowColor="black";
ctx.shadowBlur = 10;
ctx.strokeRect(45,45,210,110);
ctx.shadowColor= undefined;
ctx.shadowBlur = undefined;
I am not sure about 'undefined' in second case - something to nullify/reset the value.
var canvas3=document.getElementById("myCanvas");
var ctx3=canvas1.getContext("2d");
change canvas1 to canvas3 in the second line. Your ctx3 is actually pointing to canvas1 which i think is wrong.
You can also consider setting the shadow color to "transparent" instead of undefined or null. This also seems to do the trick.

How to change the opacity (alpha, transparency) of an element in a canvas element?

Using the HTML5 <canvas> element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it in. I have figured out how to load the image and draw it to the canvas, but I don't know how to change its opacity.
Here's the code I have so far:
var canvas = document.getElementById('myCanvas');
if (canvas.getContext)
{
var c = canvas.getContext('2d');
c.globalAlpha = 0;
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
}
img.src = 'image.jpg';
}
Will somebody please point me in the right direction like a property to set or a function to call that will change the opacity?
I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing.
//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
I have concluded that setting the globalCompositeOperation works with images.
//works with images
ctx.globalCompositeOperation = "lighter";
I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.
EDIT:
After further digging I have concluded that you can set the transparency of an image by setting the globalAlpha parameter BEFORE you draw the image:
//works with images
ctx.globalAlpha = 0.5
If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the setTimeout function, look that up to create a loop from which you alter the alpha over time.
Some simpler example code for using globalAlpha:
ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore();
If you need img to be loaded:
var img = new Image();
img.onload = function() {
ctx.save();
ctx.globalAlpha = 0.4;
ctx.drawImage(img, x, y);
ctx.restore()
};
img.src = "http://...";
Notes:
Set the 'src' last, to guarantee that your onload handler is called on all platforms, even if the image is already in the cache.
Wrap changes to stuff like globalAlpha between a save and restore (in fact use them lots), to make sure you don't clobber settings from elsewhere, particularly when bits of drawing code are going to be called from events.
Edit: The answer marked as "correct" is not correct.
It's easy to do. Try this code, swapping out "ie.jpg" with whatever picture you have handy:
<!DOCTYPE HTML>
<html>
<head>
<script>
var canvas;
var context;
var ga = 0.0;
var timerId = 0;
function init()
{
canvas = document.getElementById("myCanvas");
context = canvas.getContext("2d");
timerId = setInterval("fadeIn()", 100);
}
function fadeIn()
{
context.clearRect(0,0, canvas.width,canvas.height);
context.globalAlpha = ga;
var ie = new Image();
ie.onload = function()
{
context.drawImage(ie, 0, 0, 100, 100);
};
ie.src = "ie.jpg";
ga = ga + 0.1;
if (ga > 1.0)
{
goingUp = false;
clearInterval(timerId);
}
}
</script>
</head>
<body onload="init()">
<canvas height="200" width="300" id="myCanvas"></canvas>
</body>
</html>
The key is the globalAlpha property.
Tested with IE 9, FF 5, Safari 5, and Chrome 12 on Win7.
This suggestion is based on pixel manipulation in canvas 2d context.
From MDN:
You can directly manipulate pixel data in canvases at the byte level
To manipulate pixels we'll use two functions here - getImageData and putImageData.
getImageData usage:
var myImageData = context.getImageData(left, top, width, height);
The putImageData syntax:
context.putImageData(myImageData, x, y);
Where context is your canvas 2d context, and x and y are the position on the canvas.
So to get red green blue and alpha values, we'll do the following:
var r = imageData.data[((x*(imageData.width*4)) + (y*4))];
var g = imageData.data[((x*(imageData.width*4)) + (y*4)) + 1];
var b = imageData.data[((x*(imageData.width*4)) + (y*4)) + 2];
var a = imageData.data[((x*(imageData.width*4)) + (y*4)) + 3];
Where x is the horizontal offset, y is the vertical offset.
The code making image half-transparent:
var canvas = document.getElementById('myCanvas');
var c = canvas.getContext('2d');
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
var ImageData = c.getImageData(0,0,img.width,img.height);
for(var i=0;i<img.height;i++)
for(var j=0;j<img.width;j++)
ImageData.data[((i*(img.width*4)) + (j*4) + 3)] = 127;//opacity = 0.5 [0-255]
c.putImageData(ImageData,0,0);//put image data back
}
img.src = 'image.jpg';
You can make you own "shaders" - see full MDN article here
You can. Transparent canvas can be quickly faded by using destination-out global composite operation. It's not 100% perfect, sometimes it leaves some traces but it could be tweaked, depending what's needed (i.e. use 'source-over' and fill it with white color with alpha at 0.13, then fade to prepare the canvas).
// Fill canvas using 'destination-out' and alpha at 0.05
ctx.globalCompositeOperation = 'destination-out';
ctx.fillStyle = "rgba(255, 255, 255, 0.05)";
ctx.beginPath();
ctx.fillRect(0, 0, width, height);
ctx.fill();
// Set the default mode.
ctx.globalCompositeOperation = 'source-over';
I think this answers the question best, it actually changes the alpha value of something that has been drawn already. Maybe this wasn't part of the api when this question was asked.
Given 2d context c.
function reduceAlpha(x, y, w, h, dA) {
let screenData = c.getImageData(x, y, w, h);
for(let i = 3; i < screenData.data.length; i+=4){
screenData.data[i] -= dA; //delta-Alpha
}
c.putImageData(screenData, x, y );
}
Set global Alpha draw the object that has opacity then set back to normal.
//////////////////////// circle ///////////////////////
ctx.globalAlpha = 0.75;
ctx.beginPath();
ctx.arc(x1, y1, r1, 0, Math.PI*2);
ctx.fillStyle = colour;
ctx.fill();
ctx.closePath();
ctx.globalAlpha = 1;
How i made it..on canvas i first draw rect in a selfrun function 0,0,canvas.width,canvas.height as a background of canvas and i set globalAlpha to 1 .then i draw other shapes in ather own functions and set their globalAlpha to 0.whatever number they dont affect each other even images.
Like Ian said, use c.globalAlpha = 0.5 to set the opacity, type up the rest of the settings for the square, then follow up with c.save();. This will save the settings for the square then you can c.rect and c.fillStyle the square how you want it. I chose not to wrap it with c.restore afterwards and it worked well
If you use jCanvas library you can use opacity property when drawing. If you need fade effect on top of that, simply redraw with different values.
You can't. It's immediate mode graphics. But you can sort of simulate it by drawing a rectangle over it in the background color with an opacity.
If the image is over something other than a constant color, then it gets quite a bit trickier. You should be able to use the pixel manipulation methods in this case. Just save the area before drawing the image, and then blend that back on top with an opacity afterwards.