HTML Canvas Using Transparency
We can set the transparency of the text and shapes we draw in two ways. The first is to specify a fillStyle or strokeStyle value using the rgba() function instead of rgb(). We can also use the globalAlpha drawing state property, which is applied universally. The following code shows the use of the globalAlpha property. Using the globalAlpha property. let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "lightgrey"; ctx.strokeStyle = "black"; ctx.lineWidth = 3; ctx.font = "100px sans-serif"; ctx.fillText("Hello", 10, 100); ctx.strokeText("Hello", 10, 100); ctx.fillStyle = "red"; ctx.globalAlpha = 0.5; ctx.fillRect(100, 10, 150, 100);
Open in separate window
View full source code <html> <head> <style> canvas {border: thin solid black} body > * {float:left;} </style> </head> <body> <canvas id="canvas" width="300" height="120"> Your browser doesn't support the <code>canvas</code> element </canvas> <script> let ctx = document.getElementById("canvas").getContext("2d"); ctx.fillStyle = "lightgrey"; ctx.strokeStyle = "black"; ctx.lineWidth = 3;<!-- w w w. d e m o 2 s .c o m--> ctx.font = "100px sans-serif"; ctx.fillText("Hello", 10, 100); ctx.strokeText("Hello", 10, 100); ctx.fillStyle = "red"; ctx.globalAlpha = 0.5; ctx.fillRect(100, 10, 150, 100); </script> </body> </html> The value for the globalAlpha values may range from 0 (completely transparent) to 1 (completely opaque, which is the default value). In this example, we draw some text, set the globalAlpha property to 0.5 and then fill a rectangle partly over the text.HTML Canvas Global alpha
Before any object is drawn to the canvas, an alpha value is applied to it that matches that of the globalAlpha property. The value assigned to globalAlpha must range between 0.0 (transparent) and 1.0 (opaque); the default value is 1.0. The globalAlpha property will affect how transparent the objects that you're drawing will be. For example, you could draw a half transparent square like so: context.fillStyle = "rgb(63, 169, 245)"; context.fillRect(50, 50, 100, 100); context.globalAlpha = 0.5; context.fillStyle = "rgb(255, 123, 172)"; context.fillRect(100, 100, 100, 100);
Open in separate window
View full source code <html> <body> <canvas style='border: medium double black;' id="canvas" width="500" height="180"> <!-- Insert fallback content here --> </canvas> <script type="text/javascript"> let context = document.getElementById("canvas").getContext("2d"); context.fillStyle = "rgb(63, 169, 245)"; context.fillRect(50, 50, 100, 100); context.globalAlpha = 0.5; context.fillStyle = "rgb(255, 123, 172)"; context.fillRect(100, 100, 100, 100); </script> </body> </html> Because you set the globalAlpha property after drawing the blue square, only the pink square will be affected by the alpha value. The result will be a pink square with the blue square slightly showing through behind it. You could produce the same effect by setting the fillStyle to an rgba value that includes an alpha value less than 1. globalAlpha sets the global alpha value. For example, if the globalAlpha is 0.5 and you then apply a fillStyle with an rgba of alpha 0.5, the resulting alpha will actually be 0.25. The global alpha value of the 2d rendering context (0.5) acts as the baseline for calculating other alpha values (0.5 * 0.5 = 0.25).HTML Canvas Using Composition
We can use transparency in conjunction with the globalCompositeOperation property to control the way that shapes and text are drawn onto the canvas. The allowed values for this property are described in the following table. For this property, the source consists of any operations performed once the property has been set and the destination image is the state of the canvas at the time that the property was set. The allowed globalCompositeOperation values.
Value | Description |
---|---|
copy | Draw the source over the destination, ignoring any transparency |
destination-atop | Displays the destination image on top of the source image. The part of the destination image that is outside the source image is not shown |
destination-in | Same as source-in but using the destination image instead of the source image and vice versa |
destination-over | Same as source-over but using the destination image instead of the source image and vice versa |
destination-out | Same as source-out but using the destination image instead of the source image and vice versa |
lighter | Display the sum of the source image and destination image, with color values approaching 255 (100%) as a limit. |
source-atop | Display the source image wherever both images are opaque. Display the destination image wherever the destination image is opaque but the source image is transparent. Display transparency elsewhere |
source-in | Display the source image wherever both the source image and destination image are opaque. Display transparency elsewhere. |
source-out | Display the source image wherever the source image is opaque and the destination image is transparent. Display transparency elsewhere |
source-over | Display the source image wherever the source image is opaque. Display the destination image elsewhere |
xor | Exclusive OR of the source image and destination image. |
Name | Description | Returns |
---|---|---|
scale(<x_Scale>, <y_Scale>) | Scales the canvas by x_Scale in the x-axis and y_Scale in the y-axis | void |
rotate(<angle>) | Rotates the canvas clockwise around the point (0, 0) by the specified number of radians. | void |
translate(<x>, <y>) | Translates the canvas by x along the x-axis and y along the y-axis. | void |
transform(a, b, c, d, e, f) | Combines the existing transformation with the matrix specified by the values a-f. | void |
setTransform(a, b, c, d, e, f) | Replaces the existing transformation with the matrix specified by the values a-f. | void |
Method | Description |
---|---|
addColorStop() | Add Color Stop to gradient |
arc() | Draw arc |
arcTo() | Draw arc with radius |
beginPath() | Start Path Drawing |
bezierCurveTo() | Draw bezier Curve |
clearRect() | clear Rectangle area |
clip() | clip an area |
closePath() | close Path for drawing |
createImageData() | create Image Data for drawing |
createLinearGradient() | create Linear Gradient for drawing |
createPattern() | create Pattern for drawing |
createRadialGradient() | create Radial Gradient for drawing |
drawImage() | drawImage() Method |
fill() | fill a shape or path |
fillRect() | fill Rectangle |
fillStyle | Change fill Style Property |
fillText() | fill Text |
font | font Property |
getImageData() | get Image Data for Drawing |
globalAlpha | set global Alpha Property |
globalCompositeOperation | Get and Set global Composite Operation Property |
ImageData data | Get and Set ImageData data Property |
ImageData height | Get canvas ImageData height Property |
ImageData width | Get ImageData width Property |
isPointInPath() | isPointInPath() Method |
lineCap | Get and Set line Cap Property |
lineJoin | Get and Set line Join Property |
lineTo() | use lineTo() Method to draw lines |
lineWidth | Get and Set line Width Property |
measureText() | Use measure Text Method to get text size |
miterLimit | Get and Set miter Limit Property |
moveTo() | use moveTo() Method to move drawing point |
putImageData() | Use putImageData() Method to paint image data |
quadraticCurveTo() | Draw quadratic Curve |
rect() | Draw rectangle |
rotate() | rotate coordinates |
scale() | scale Coordinates |
setTransform() | set Transform matrix |
shadowBlur | Get and Set shadow Blur Property |
shadowColor | Get and Set shadow Color Property |
shadowOffsetX | Get and Set shadow Offset X Property |
shadowOffsetY | Get and Set shadow Offset Y Property |
stroke() | Drawing with stroke() Method |
strokeRect() | Drawing rectangle using strokeRect() Method |
strokeStyle | Get and Set stroke Style Property |
strokeText() | Draw text with strokeText() Method |
textAlign | Get and Set text align Property |
textBaseline | Get and Set text Base line Property |
transform() | transform coordinates |
translate() | translate coordinates |
Method | Description |
---|---|
concat() | append array together |
copyWithin() | copy elements |
entries() | Create Iterator for each key/value pair |
every() | checks if all elements in an array pass a test |
fill() | fill array element |
filter() | filter element by condition |
find() | search for elements by a function and return the first match |
findIndex() | search element for index via a function |
forEach() | Call a function once for each element |
from() | Create array from values |
flat() | Flat array element |
flatMap() | flat Map an array |
includes() | Search array for an element |
indexOf() | Find element index by value |
join() | Join arrays together |
keys() | Create Iterator object containing the keys |
lastIndexOf() | find element index from end |
length Property | get length |
map() | map each element by a function |
pop() | remove and return the last element |
push() | add new items to the end and return new length |
reduce() | Reduce to a single value |
reduceRight() | Reduce to a single value from end |
reverse() | reverse element order |
shift() | Remove the first element from start |
slice() | Get sub array |
some() | checks if any of the elements pass a test |
sort() | sort by a function |
splice() | adds/removes items to/from an array |
toString() | convert to string |
unshift() | Add element before the first element |
valueOf() | return itself |
Method | Description |
---|---|
assert() | console assert value Method |
clear() | console clear Method |
count() | console count times Method |
error() | console error message Method |
group() | console group message Method |
groupCollapsed() | console group message Collapsed Method |
groupEnd() | console group message End Method |
show() | console show information Method |
log() | console log message Method |
table() | console display table Method |
time() | console time Method |
timeEnd() | console time End Method |
trace() | console trace Method |
warn() | console warn message Method |
Method | Description |
---|---|
getDate() | Javascript Date get day of the month (from 1 to 31) |
getDay() | Javascript Date day of the week from 0 to 6 |
getFullYear() | Javascript Date get year value in four digits |
getHours() | Javascript Date Get hour value from 0 to 23 |
getMilliseconds() | Javascript Date get the milliseconds from 0 to 999 |
getMinutes() | Javascript Date Get Minute from 0 to 59 |
getMonth() | Javascript Date get the month value from 0 to 11 |
getSeconds() | Javascript Date get second value from 0 to 59 |
getTime() | Javascript Date get the number of milliseconds since midnight January 1, 1970 |
getTimezoneOffset() | Javascript Date get time zone offset from UTC |
getUTCDate() | Javascript Date get day of the month from 1 to 31 in UTC |
getUTCDay() | Javascript Date get day of the week from 0 to 6, according to universal time UTC. |
getUTCFullYear() | Javascript Date get the year in four digits, according to universal time UTC. |
getUTCHours() | Javascript Date Get hour from 0 to 23, according to universal time UTC. |
getUTCMilliseconds() | Javascript Date Get milliseconds from 0 to 999, according to universal time UTC. |
getUTCMinutes() | Javascript Date get minutes from 0 to 59, according to universal time UTC. |
getUTCMonth() | Javascript Date get month from 0 to 11, according to universal time UTC. |
getUTCSeconds() | Javascript Date get seconds from 0 to 59, according to universal time UTC. |
now() | Javascript Date get number of milliseconds since January 1, 1970 00:00:00 UTC. |
Date parse() | Javascript Date Parse String to Date object |
setDate() | Javascript Date set the day of the month |
setFullYear() | Javascript Date sets the year in four digits |
setHours() | Javascript Date sets the hour of a date object |
setMilliseconds() | Javascript Date set the milliseconds of a date object |
setMinutes() | Javascript Date set the minutes of a date object |
setMonth() | Javascript Date set the month of a date object |
setSeconds() | Javascript Date set the seconds of a date object |
setTime() | Javascript Date Set by number of milliseconds |
setUTCDate() | Javascript Date set the day of the month, according to the UTC time. |
setUTCFullYear() | Javascript Date sets the year in four digits, according the UTC time |
setUTCHours() | Javascript Date set the hour of a date object, according to the UTC time. |
setUTCMilliseconds() | Javascript Date set the milliseconds from 0 to 999, according to universal time UTC. |
setUTCMinutes() | Javascript Date Set minutes of a date object, according to UTC time. |
setUTCMonth() | Javascript Date Set month from 0 to 11, according to universal time UTC. |
setUTCSeconds() | Javascript Date Set seconds of a date object, according to UTC time. |
toDateString() | Javascript Date Convert to readable String |
toISOString() | Javascript Date Convert to String in ISO format |
toJSON() | Javascript Date Convert to JSON String |
toLocaleDateString() | Javascript Date Convert date part only to String by current locale |
toLocaleString() | Javascript Date Convert to String by current Locale |
toLocaleTimeString() | Javascript Date Convert time part to String by current Locale |
Date toString() | Javascript Date Convert to String |
toTimeString() | Javascript Date convert to time string |
toUTCString() | Javascript Date convert to UTC String |
UTC() | Javascript Date Get the number of milliseconds from midnight of January 1, 1970, according to universal time. |
Date valueOf() | Javascript Date Convert number of millisecond since midnight January 1, 1970 UTC. |
Property | Description |
---|---|
message | Get Error message Property |
name | Get Error name Property |
Method/Properties | Description |
---|---|
abs() | Calculate the absolute value of a number |
acos() | Calculate arccosine of a number |
acosh() | Calculate hyperbolic arccosine of a number |
asin() | Calculate arcsine of a number |
asinh() | Calculate hyperbolic arcsine of a number |
atan() | Calculate arctangent of a specified number |
atan2() | Calculate angle in radians between that point and X axis |
atanh() | Calculate hyperbolic arctangent of a specified number |
cbrt() | Calculate cubic root of a number |
ceil() | Round a number upward to its nearest integer |
cos() | Calculate cosine of a number |
cosh() | Calculate hyperbolic cosine of a number |
E | Get Euler's number |
exp() | Calculate exponential value of a number |
expm1() | Calculate exponential value of a number - 1 |
floor() | Round a number downward to its nearest integer |
fround() | Round float numbers to nearest |
LN10 | Calculate natural logarithm of 10 |
LN2 | Get natural logarithm of 2 |
log() | Calculate natural logarithm of the number two |
log10() | Calculate base-10 logarithm of the number two |
LOG10E | Get base-10 logarithm of E |
log1p() | Calculate natural logarithm (base E) of 1 + different numbers |
log2() | Javascript Math Calculate base 2 logarithm of a number |
LOG2E | Get base-2 logarithm of E |
max() | Get number highest value from a list of numbers |
min() | Get lowest value from a list of numbers |
PI | get PI value |
pow() | Calculate value of x to the power of y |
random() | Get random number between two values |
round() | Round a number to the nearest integer |
sign() | Find if a number is negative or positive |
sin() | Calculate sine of a number |
sinh() | Calculate hyperbolic sine of a number |
sqrt() | Calculate square root of a number |
SQRT1_2 | Get square root of 1/2 |
SQRT2 | Get square root of 2 |
tan() | Calculate tangent of a number |
tanh() | hyperbolic tangent of a number |
trunc() | get integer part of a number |
Method Name | Description |
---|---|
anchor() | Create anchor link |
big() | Create big font |
blink() | Create blinking String |
bold() | create bold font text |
charAt() | Get character from String by index |
charCodeAt() | get unicode from String by index |
concat() | append String values together |
endsWith() | Check if string ends with a certain value |
fixed() | Create teletype text |
fontcolor() | Display String with font color |
fontsize() | Display Text in large font size |
fromCharCode() | Convert Unicode number into a character |
includes() | Search String by sub string |
indexOf() | Search String and get sub string index |
italics() | Display text in italics font |
lastIndexOf() | search String from the end and return index |
length Property | Get String length |
link() | Create anchor link from text |
localeCompare() | Compare String using current Locale |
match() | Match String with Regular Expressions |
repeat() | copy by repeating the String value |
replace() | replace a sub string |
search() | search String using Regular Expressions |
slice() | get sub string |
small() | display String in smaller font |
split() | split string by separator |
startsWith() | Check if string starts with a certain value |
strike() | display String with line through as struck out |
sub() | display String in sub script font |
substr() | get sub string from start or from end |
substring() | get sub string |
sup() | display String in super script font |
toLocaleLowerCase() | Convert to lower case using current locale |
toLocaleUpperCase() | Convert to upper case using current locale |
toLowerCase() | convert to lower case |
toString() | convert to String |
toUpperCase() | convert String to upper case |
trim() | remove empty space |
valueOf() | convert to primitive String value |
Name | Description | Returns |
---|---|---|
clear() | Removes the stored key/value pairs | void |
getItem(<key>) | Retrieves the value associated with the specified key | string |
key(<index>) | Retrieves the key at the specified index | string |
length | Returns the number of stored key/value pairs | number |
removeItem(<key>) | Removes the key/value pair with the specified key | string |
setItem(<key>, <value>) | Adds a new key/value pair or updates the value if the key has already been used | void |
[<key>] | Array-style access to retrieve the value associated with the specified key | string |
Name | Description | Returns |
---|---|---|
key | Returns the key that has been changed | string |
oldValue | Returns the old value associated with the key | string |
newValue | Returns the new value associated with the key | string |
url | Returns the URL of the document that made the change | string |
storageArea | Returns the Storage object which has changed | Storage |
Property | Description |
---|---|
length | Web Storage length Property |
Method | Description |
---|---|
clear() | Web Storage clear() Method |
getItem() | Web Storage getItem() Method |
key() | Web Storage key() Method |
removeItem() | Web Storage removeItem() Method |
setItem() | Web Storage setItem() Method |
Property | Description |
---|---|
key | StorageEvent key Property |
newValue | StorageEvent newValue Property |
oldValue | StorageEvent oldValue Property |
url | StorageEvent url Property |
storageArea | StorageEvent storageArea Property |
Name | Description | Returns |
---|---|---|
getCurrentPosition(callback, error_Callback, options) | Get the current position | void |
watchPosition(callback, error, options) | Start monitoring the current position | number |
clearWatch(id) | Stop monitoring the current position | void |
Name | Description | Returns |
---|---|---|
coords | Returns the coordinates for the current position | Coordinates |
timestamp | Returns the time that the coordinate information was obtained | string |
Name | Description | Returns |
---|---|---|
latitude | Returns the latitude in decimal degrees | number |
longitude | Returns the longitude in decimal degrees | number |
altitude | Returns the height in meters | number |
accuracy | Returns the accuracy of the coordinates in meters | number |
altitudeAccuracy | Returns the accuracy of the altitude in meters | number |
heading | Returns the direction of travel in degrees | number |
speed | Returns the speed of travel in meters/second | number |
Name | Description | Returns |
---|---|---|
code | Returns a code indicating the type of error | number |
message | Returns a string that describes the error | string |
Value | Description |
---|---|
1 | The user did not grant permission to use the geolocation feature |
2 | The position could not be determined |
3 | The attempt to request the location timed out |
Name | Description | Returns |
---|---|---|
enableHighAccuracy | Tells the browser that we would like the best possible result | boolean |
timeout | Sets a limit on how many milliseconds a position request can take before a timeout error is reported | number |
maximumAge | Tells the browser that we are willing to accept a cached location, as long as it is no older than the specified number of milliseconds | number |
Property | Description |
---|---|
coordinates | Geolocation coordinates Property |
position | Geolocation position Property |
Value | Numeric Value | Description |
---|---|---|
UNSENT | 0 | The XMLHttpRequest object has been created. |
OPENED | 1 | The open method has been called. |
HEADERS_RECEIVED | 2 | The headers of the server response have been received. |
LOADING | 3 | The response from the server is being received. |
DONE | 4 | The response is complete or has failed. |
Name | Description | Event Type |
---|---|---|
abort | Triggered when the requested is aborted | ProgressEvent |
error | Triggered when the request fails | ProgressEvent |
load | Triggered when the request completes successfully | ProgressEvent |
loadend | Triggered when the request completes, either successfully or with an error | ProgressEvent |
loadstart | Triggered when the request starts | ProgressEvent |
progress | Triggered to indicate progress during the request | ProgressEvent |
readystatechange | Triggered at different stages in the request life cycle | Event |
timeout | Triggered if the request times out | ProgressEvent |
Name | Description | Event Type |
---|---|---|
lengthComputable | Returns true if the total length of the data stream can be calculated | boolean |
loaded | Returns the amount of data that has been loaded so far | number |
total | Returns the total amount of data available | number |
Method | Description | Returns |
---|---|---|
setRequestHeader(<header>, <value>) | Sets the header to the specified value | void |
getResponseHeader(<header>) | Gets the value of the specified header | string |
getAllResponseHeaders() | Gets all of the headers in a single string | string |
Method | Description | Returns |
---|---|---|
parse(<json>) | Parses a JSON-encoded string and creates an object | object |
stringify(<object>) | Creates a JSON-encoded representation of the specified object | string |
Value | Description |
---|---|
true | The element can be dragged |
false | The element cannot be dragged |
auto | The browser may decide if an element can be dragged |
Name | Description |
---|---|
dragstart | Triggered when the element is first dragged |
drag | Triggered repeatedly as the element is being dragged |
dragend | Triggered when the drag operation is completed |
Name | Description |
---|---|
dragenter | Triggered when a dragged element enters the screen space occupied by the drop zone |
dragover | Triggered when a dragged element moves within the drop zone |
dragleave | Triggered when a dragged element leaves the drop zone without being dropped |
drop | Triggered when a dragged element is dropped in the drop zone |
Name | Description | Returns |
---|---|---|
dataTransfer | Returns the object used to transfer data to the drop zone | DataTransfer |
Name | Description | Returns |
---|---|---|
types | Returns the formats for the data | string[] |
getData(<format>) | Returns the data for a specific format | string |
setData(<format>, <data>) | Sets the data for a given format | void |
clearData(<format>) | Removes the data for a given format | void |
files | Returns a list of the files that have been dragged | FileList |
Name | Description | Returns |
---|---|---|
name | Gets the name of the file | string |
type | Gets the type of file, expressed as a MIME type | string |
size | Gets the size (in bytes) of the file | number |