Skip to content

Instantly share code, notes, and snippets.

@nicolsc
Last active December 17, 2015 12:39
Show Gist options
  • Save nicolsc/5611601 to your computer and use it in GitHub Desktop.
Save nicolsc/5611601 to your computer and use it in GitHub Desktop.
Draw a rectangle in a canvas, and output its "base64". Params : red, green,blue, alpha, width, height, target dom id, container dom id
function myrect(r,g,b,a,width,height, targetID,canvasContainerID){
/* Default values */
r = r || 0;
g = g ||0;
b = b || 0;
width = width || 100;
height = height || 100;
targetID = targetID || 'canvas';
/* Reset container, if asked to */
if (canvasContainerID){
//reset it
document.getElementById(canvasContainerID).innerHTML = ('<canvas id="'+targetID+'"></canvas>');
}
/* Get target canvas, and check if it exists & is a canvas */
var target = document.getElementById(targetID);
if (!target){
throw new Error('Target '+targetID+' not found');
}
if (target.tagName.toLowerCase()!='canvas'){
throw new Error('Target '+targetID+' must be a canvas, but is a '+target.tagName);
}
/* Set canvas size */
target.width=width;
target.width = height;
/* draw the canvas */
var ctx = document.getElementById(targetID).getContext('2d');
ctx.fillStyle = 'rgba('+r+', '+g+','+b+','+a+')';
ctx.fillRect(0,0,width,height);
/* output the png base64 of the rectangle in the console*/
console.log(document.getElementById('canvas').toDataURL('image/png'));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment