# How to create transparency in images with canvas

Estimated reading time: 2 minutes ( save for later )

### 3. Get the canvas’ dataURL, tada

Doesn’t look too hard, does it? Let’s have a look at a possible implementation! :)

### Step 1: kids stuff

First we have to create a canvas element, add it to the document’s body, set the canvas size to the image size (we have a 500×200 img) and add the image to the canvas.

```// get the image
var img = document.getElementById("your-image");
// create and customize the canvas
var canvas = document.createElement("canvas");
canvas.width = 500;
canvas.height = 200;
document.body.appendChild(canvas);
// get the context
var ctx = canvas.getContext("2d");
// draw the image into the canvas
ctx.drawImage(img, 0, 0);
```

### Step 2: the interesting part

Ok this is the more interesting part of the solution. We have to access the image data, loop thru all pixels of the image and set the alpha values to the value of our choice. A pixel in the imagedata is represented by four values: red, green, blue, alpha (rgba) therefore we have to change every fourth value.

```// get the image data object
var image = ctx.getImageData(0, 0, 500, 200);
// get the image data values
var imageData = image.data,
length = imageData.length;
// set every fourth value to 50
for(var i=3; i < length; i+=4){
imageData[i] = 50;
}
// after the manipulation, reset the data
image.data = imageData;
// and put the imagedata back to the canvas
ctx.putImageData(image, 0, 0);
```

The alpha value could be 0 to 255 just like the r,g,b values. 0 <= alpha <= 255, therefore if you like to set a percentage you have to calculate (255/ (100/percentage value))

### Step 3: the relief

Finally you can access the new image data with the toDataURL function and set it to the image

```img.src = canvas.toDataURL();
```

Keep in mind the default data url image type is .PNG, therefore you can have transparency :) If you set another image type in the dataURL (such as “image/jpg”) the transparency is lost.

Hope you enjoyed the article. Cheers, Patrick