How do I make a transparent canvas in html5?
Canvases are transparent by default.
Try setting a page background image, and then put a canvas over it. If nothing is drawn on the canvas, you can fully see the page background.
Think of a canvas as like painting on a glass plate.
To clear a canvas after having drawn on it, just use clearRect
:
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
Make canvas transparent
One easy way, is using an offscreen canvas.
First set its context's globalAlpha
value to something between 0 and 1, this will determine how fast your previous drawings will disappear.
Then, in the animation loop, before doing the new drawings,
- clear the offscreen context,
- draw the visible canvas on the offscreen one,
- clear the visible canvas
- draw back the offscreen one on the visible one
In the process, your image will have lost opacity.
var clear = function(){ // clear the clone canvas cloneCtx.clearRect(0,0,canvasWidth, canvasHeight) // this should be needed at init and when canvas is resized but for demo I leave it here cloneCtx.globalAlpha = '.8'; // draw ou visible canvas, a bit less opaque cloneCtx.drawImage(context.canvas, 0,0) // clear the visible canvas context.clearRect(0,0,canvasWidth, canvasHeight) // draw back our saved less-opaque image context.drawImage(clone, 0,0)}
var canvas = document.getElementById('canvas'), context = canvas.getContext('2d'), // create an offscreen clone clone = canvas.cloneNode(), cloneCtx = clone.getContext('2d'), canvasWidth = canvas.width = clone.width =window.innerWidth, canvasHeight = canvas.height = clone.height = window.innerHeight, globalTick = 0, points = [], pointCount = 12, pointSpeed = 6, spacing = canvasWidth / pointCount, pointCount = pointCount + 2, verticalPointRange = 60, randomRange = function(min, max){ return Math.floor( (Math.random() * (max - min + 1) ) + min); }, iPath, iPoints;
var Point = function(x, y, alt){ this.x = x; this.y = y; this.yStart = y; this.alt = alt; } Point.prototype.update = function(i){ var range = (this.alt) ? verticalPointRange : -verticalPointRange; this.x += pointSpeed; this.y = (this.yStart) + Math.sin(globalTick/14) * -range; if(this.x > (canvasWidth + spacing)){ this.x = -spacing; var moved = points.splice(i, 1); points.unshift(moved[0]); }} var updatePoints = function(){ var i = points.length; while(i--){ points[i].update(i); }} for(iPoints = 0; iPoints < pointCount; iPoints++){ var alt = (iPoints % 2 === 0); var offset = (alt) ? verticalPointRange : -verticalPointRange; points.push(new Point(spacing * (iPoints-1), canvasHeight/2, alt)); }
var renderPath = function(){ context.beginPath(); context.moveTo(points[0].x, points[0].y); for(iPath = 1; iPath < pointCount; iPath++){ context.lineTo(points[iPath].x, points[iPath].y); } context.stroke(); } var loop = function(){ requestAnimationFrame(loop, canvas); clear(); updatePoints(); renderPath(); globalTick++;};
loop();
canvas { display: block; }body{ background-color: ivory;}
<canvas id="canvas"></canvas>
How to make the canvas background transparent
Canvas transparent by default.
But anyway this question could have a pretty easy solution, which not using globalAlpha, and not using a rgba() color. The simple, effective answer is:
context.clearRect(0,0,width,height);
How to draw transparent image with html5 canvas element
The canvas element has a global alpha attribute that lets you apply partial transparency to anything you draw.
Transparent Color HTML5 Canvas
This is because you don't clear the canvas at the start of each frame. With a solid-colour background this doesn't matter, but with transparent you must do this:
ctx.clearRect(0,0,canvas.width,canvas.height);
HTML5 Canvas Make Black Transparent
So you'll need to run through all the pixels and change the alpha value of all the black pixels.
https://jsfiddle.net/0kuph15a/2/
This code creates a buffer (empty canvas) to draw the original image to. Once thats done, it takes all the pixels of this buffer canvas and then iterates over all the pixels and checks their values. I add up the Red, Blue, and Green values to see if they are less then 10 (just incase some pixels aren't pure black 0), but would visually appear black to the human eye. If it is less then 10 it simply turns the alpha value of that pixel to 0.
var canvas = document.getElementById('main');
var ctx = document.getElementById('main').getContext('2d');
var tile = new Image();
tile.src = document.getElementById('image').src;
tile.onload = function() {
draw(tile);
}
function draw(img) {
var buffer = document.createElement('canvas');
var bufferctx = buffer.getContext('2d');
bufferctx.drawImage(img, 0, 0);
var imageData = bufferctx.getImageData(0,0,buffer.width, buffer.height);
var data = imageData.data;
var removeBlack = function() {
for (var i = 0; i < data.length; i += 4) {
if(data[i]+ data[i + 1] + data[i + 2] < 10){
data[i + 3] = 0; // alpha
}
}
ctx.putImageData(imageData, 0, 0);
};
removeBlack();
}
You can easily change this line if(data[i]+ data[i + 1] + data[i + 2] < 10){
to if(data[i]+ data[i+1] + data[i+2]==0){
if you know for a fact only #000 blacks are used.
Draw image with transparent background on canvas
Your code works perfectly - you just need an image with a transparent background - like this question mark:
var can = document.getElementById('canvasId');var ctx = can.getContext('2d');
ctx.fillRect(50,50,500,500); // something in the background
var img = new Image();img.onload = function() { ctx.drawImage(img, 0, 0);}img.src = "https://i.stack.imgur.com/RPEQQ.png"; //transparent png
<canvas id="canvasId"></canvas>
HTML5: Apply transparency to Canvas after drawing through JavaScript
To have a clear effect that will fade out the current canvas, you can use the 'destination-out' operation when completely filling with any color : this leaves the canvas untouched... Unless you lower the globalAlpha to x, then the resulting alpha will be multiplied by 1-x.
(http://dev.w3.org/fxtf/compositing-1/#porterduffcompositingoperators_srcout )
jsbin :
http://jsbin.com/cecavojepa/1/edit?js,output
core fading function :
function fadeCanvas() {
ctx.save();
ctx.globalAlpha = 0.1;
ctx.globalCompositeOperation='destination-out';
ctx.fillStyle= '#FFF';
ctx.fillRect(0,0,cv.width, cv.height);
ctx.restore();
}
transparent image background html5 canvas
Works fine for me with that image and the following code in the latest Firefox and Chrome beta on Mac. (Except the image itself has a few white non-transparent pixels, which you can see by opening on a dark background e.g. in Firefox.)
<!DOCTYPE HTML>
<html>
<head>
<script type="application/x-javascript">
var canvas, ctx;
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
var size=500;
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.fillStyle = 'yellow';
ctx.moveTo(0,0);
ctx.lineTo(size,0);
ctx.lineTo(size,size);
ctx.lineTo(0,size);
ctx.lineTo(0,0);
ctx.stroke();
ctx.fill();
var img = document.getElementById("img");
ctx.drawImage(img, 0, 0);
}
</script>
</head>
<body onload="init();">
<canvas id="canvas" width="500" height="500"></canvas>
<img id="img" src="test.gif" style="position:absolute; top:500px"></img>
</body>
</html>
Related Topics
Is It Considered Bad Practice to Use Absolute Positioning
CSS Grid - Maximum Number of Columns Without Media Queries
Bug with Firefox - Disabled Attribute of Input Not Resetting When Refreshing
How to Stretch Flex Child to Fill Height of the Container
Set Height 100% on Absolute Div
Using .Otf Fonts on Web Browsers
How to Center the Contents of an HTML Table
Is There Any Benefit to Adding Accept-Charset="Utf-8" to HTML Forms, If the Page Is Already in Utf-8
File Url "Not Allowed to Load Local Resource" in the Internet Browser
How to Set a Background in a Bootstrap Column That Oversizes the Div
How to Hide Columns in HTML Table
How to Remove "Invisible Space" from HTML
CSS Image Resize Percentage of Itself
With a Browser, How to Know Which Decimal Separator Does the Operating System Use
How to Set Div's Height in CSS and HTML