Skip to content

Instantly share code, notes, and snippets.

@mcelotti
Last active November 5, 2015 13:09
Show Gist options
  • Save mcelotti/f11f742b3ec4516275d4 to your computer and use it in GitHub Desktop.
Save mcelotti/f11f742b3ec4516275d4 to your computer and use it in GitHub Desktop.
(function() {
var drawImage = function() {
var imageData = this.getImgData();
var maxWidth = this.getWidth();
var maxHeight = this.getHeight();
if (imageData && maxHeight && maxWidth) {
var img = document.createElement("img");
img.src = imageData;
var width = img.width,
height = img.height;
if (width > height) {
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
} else {
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
}
var canvas = this.getDomCanvas();
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, width, height);
} else {
this.resetCanvas();
}
};
Ext.define('Ext.ux.CanvasImage', {
extend : 'Ext.Component',
xtype : 'canvasimage',
config : {
imgData : null,
width : 400,
height : 300
},
template : [{
reference : 'canvas',
tag : 'canvas',
classList : [Ext.baseCSSPrefix + 'canvas']
}],
updateImgData : function() {
drawImage.call(this);
},
updateWidth : function() {
drawImage.call(this);
},
updateHeight : function() {
drawImage.call(this);
},
resetCanvas : function() {
var canvas = this.getDomCanvas(),
context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
},
getDomCanvas : function() {
return this.element.dom.firstChild;
},
toDataURL : function(quality) {
quality = quality || 0.7;
return this.getDomCanvas().toDataURL("image/jpeg", quality);
}
});
})();
@mcelotti
Copy link
Author

mcelotti commented Nov 5, 2015

Usage:

  {
    xtype : 'canvasimage',
    imgData : <your image data, use method "setImgData" to set canvas imagedata at runtime>
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment