Created
July 8, 2013 08:41
-
-
Save yckart/5947199 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Set the graphics attributes specified by the properties of the object o. | |
// Or, if no argument is passed, return the current attributes as an object. | |
// Note that this does not handle the transformation or clipping region. | |
CanvasRenderingContext2D.prototype.attr = function (key, val) { | |
var keyString = typeof key === 'string'; | |
var valUndefined = typeof val === 'undefined'; | |
var styles = { | |
fillStyle: this.fillStyle, | |
font: this.font, | |
globalAlpha: this.globalAlpha, | |
globalCompositeOperation: this.globalCompositeOperation, | |
lineCap: this.lineCap, | |
lineDashOffset: this.lineDashOffset, | |
lineJoin: this.lineJoin, | |
lineWidth: this.lineWidth, | |
miterLimit: this.miterLimit, | |
shadowBlur: this.shadowBlur, | |
shadowColor: this.shadowColor, | |
shadowOffsetX: this.shadowOffsetX, | |
shadowOffsetY: this.shadowOffsetY, | |
strokeStyle: this.strokeStyle, | |
textAlign: this.textAlign, | |
textBaseline: this.textBaseline | |
}; | |
// get | |
if (keyString && valUndefined) { | |
return styles[key]; | |
} | |
// set | |
if (keyString && !valUndefined) { | |
this[key] = val; | |
return this; | |
} | |
// set all | |
if (key && !val) { | |
for (var a in key) this[a] = key[a]; | |
return this; | |
} | |
// get all | |
return styles; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var canvas = document.body.appendChild(document.createElement('canvas')); | |
var ctx = canvas.getContext('2d'); | |
// set single | |
ctx.attr('globalAlpha', 0.5); | |
// get single | |
console.log( ctx.attr('globalAlpha') ); | |
// set multiple | |
ctx.attr({ | |
fillStyle: 'red' | |
}); | |
// get multiple | |
console.log( ctx.attr() ); | |
// draw | |
ctx.fillRect(0, 0, 100, 100); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment