Skip to content

Latest commit

 

History

History
1451 lines (1015 loc) · 33.9 KB

File metadata and controls

1451 lines (1015 loc) · 33.9 KB

API List


Concept


concept MBC Mode

MBC Instance
  |- View Mode
  |- Edit Mode (basicEdit)
    |- FreeTransform Mode (need `loadCvScript`)
    |- Brush Mode

reference: isEditing(), getMode()

explanation:

All function in parent mode can be processed in son mode. But not all gesturers in parent mode is valid in son mode.

For example, FreeTransform mode is a son mode of Edit mode. Function .rotateLeft() can still be called. However, you can't double click to zoom in or zoom out the canvas.


Global


constructor MBC()

Syntax: new MBC(license)

parameter type description
license String

example:

// MBC without a license can be used for evaluation purposes. It is not stable for long time usage.
var painter = new MBC();
// MBC need a license in production environments.
painter = new MBC('xxxxx');




function .getHtmlElement()

Syntax: .getHtmlElement()

parameter type description
(return value) HTMLDivElement

example:

var painterDom = painter.getHtmlElement();
painterDom.style.width = '100%';
painterDom.style.height = '100%';
document.getElementById('painter-container').appendChild(painterDom);




function .getCurIndex()

Get the current showing image index a in MBC instance.

Syntax: .getCurIndex()

parameter type description
(return value) Number




function .getCount()

Get the image count in a MBC instance.

Syntax: .getCount()

parameter type description
(return value) Number




function .isEditing()

Identify whether the MBC instance is in Edit mode.

Syntax: .isEditing()

parameter type description
(return value) boolean




function .getMode()

Identify whether the MBC instance is in Edit mode.

Syntax: .getMode()

parameter type description
(return value) string view, basicEdit, freeTransform or brush




function .getImage()

Syntax: .getImage(isOri, index)

parameter type description
(return value) HTMLImageElement
isOri (optinal) boolean
index (optinal) Number

example:

// A way to access to inner data. Don't modify it if you are not sure.
var imgOri = painter.getImage(true);
// This image can be used in any place and free to modify it.
var imgCopyed = painter.getImage();
imgCopyed.style.width = '100px';
imgCopyed.style.height = '100px';
document.getElementById('image-container').appendChild(imgCopyed);




event .onStartLoading

Binding a function that would be called when starting an expensive operation.

Syntax: function(){}

example:

painter.onStartLoading = function(){
    document.getElementById('animation').show();
};




event .onFinishLoading

Binding a function that would be called when finishing an expensive operation.

Syntax: function(){}

example:

painter.onFinishLoading = function(){
    document.getElementById('animation').hide();
};




static String .cvFolder

Tell this painter the directory where you place cv-wasm.js and cv-wasm.wasm.

Syntax: MBC.cvFolder = 'js';




static function .loadCvScript

You should call MBC.loadCvScript() first before use Free Transform and Brush module.

Syntax: MBC.loadCvScript()

parameter type description
(return value) Promise(resolve(), reject(ex))

example:

MBC.loadCvScript().then(function(){
    console.log('load cv script success.');
    painter.enterFreeTransformMode();
}, function(ex){
    console.log('load cv script fail.'+(ex.message||ex));
});




Image Store


function .showFileChooseWindow()

Show file choose window by click the hidden file input. Can't process during Edit mode.

Syntax: .showFileChooseWindow()

parameter type description
(return value) boolean

example:

document.getElementById('btn-add-image').addEventListener('click', function(){
    painter.showFileChooseWindow();
});




HTMLInputElement .defaultFileInput

example:

// warning: never redefine it if you are not sure
// painter.defaultFileInput = document.createElement('input');
painter.defaultFileInput.accept = "image/png";
painter.defaultFileInput.multiple = false;




event .beforeAddImgFromFileChooseWindow

Binding a function that would be called when defaultFileInput change by showFileChooseWindow().

Syntax: function(event, callback){}

example:

painter.beforeAddImgFromFileChooseWindow = function(ev, callback){
    var files = ev.target.files;
    var newBlobs = [];
    var finishedIndex = 0;
    for(var i = 0; i < files.length; ++i){
        var file = files[i];
        doSomeWorkToGetANewBlob(file, function(blob){
            newBlobs.push(blob);
            if(files.length == ++finishedIndex){
                callback(newBlobs);
            }
        });
    }
};




event .afterAddImgFromFileChooseWindow

Binding a function that would be called after adding image from defaultFileInput.

Syntax: function(bSuccess, addResult){}

example:

painter.afterAddImgFromFileChooseWindow = function(bSuccess, addResult){
    if(bSuccess){console.log('The new image(s) has been added from file choose window.');}
};




event .beforeAddImgFromDropFile

Syntax: function(event, callback){}

example:

painter.beforeAddImgFromDropFile = function(ev, callback){
    var files = ev.dataTransfer.files;
    var newBlobs = [];
    var finishedIndex = 0;
    for(var i = 0; i < files.length; ++i){
        var file = files[i];
        doSomeWorkToGetANewBlob(file, function(blob){
            newBlobs.push(blob);
            if(files.length == ++finishedIndex){
                callback(newBlobs);
            }
        });
    }
};




event .afterAddImgFromDropFile

Syntax: function(bSuccess, addResult){}

example:

painter.afterAddImgFromDropFile = function(bSuccess){
    if(bSuccess){console.log('The new image(s) has been added from dropping.');}
};




function .addImage()

Add image(s) to the MBC instance. Can only process in View mode.

Syntax: .addImage(imgData)

parameter type description
(return value) Promise(resolve(addResult), reject(ex))
imgData Blob, HTMLCanvasElement, HTMLImageElement, String(url), Array(a array of source), FileList

example:

painter.addImage(image).then(function(){
    console.log('Add success');
},function(){
    console.log('Add error');
});




Number .addedImageMaxWH

The image whose width or height larger than addedImageMaxWH would be compressed when adding.

Syntax: .addedImageMaxWH = 4096;




boolean .isShowNewImgWhenAdd

Whether changePage to the new added image.

Syntax: .isShowNewImgWhenAdd = true;




function .updateUIOnResize()

Update the htmlElement of a MBC instance. Should call it manually when the htmlElement resize.

Syntax: .updateUIOnResize(isLazy)

parameter type description
isLazy (optional) boolean Default false. Set true to avoid to update too frequently.

Syntax: .updateUIOnResize()

parameter type description
(return value) boolean

Syntax: .updateUIOnResize(true)

parameter type description
(return value) Promise(resolve(), reject(ex))

example:

window.addEventListener('resize',function(){
    painter.updateUIOnResize(true).then(function(){
        console.log('painter update');
    }, function(ex){
        console.log('painter update');
    });
});




event .onNumChange

Binding a function that would be called when current image index or total length change.

Syntax: function(Number curIndex, Number length){}

example:

painter.onNumChange = function(curIndex, length){
    console.log('curIndex: '+curIndex+', length:'+length);
};




function .changePage()

Change index of the current page. Can only process in View mode.

Syntax: .changePage(cmd)

parameter type description
(return value) boolean
cmd Number(index), String('f', 'p', 'n', 'l') Index number, or command string of 'f'(first), 'p'(pre), 'n'(next), 'l'(last).

example:

document.getElementById('btn-first').addEventListener('click', function(){
    painter.changePage('f');
});
document.getElementById('btn-pre').addEventListener('click', function(){
    painter.changePage('p');
});
document.getElementById('btn-next').addEventListener('click', function(){
    painter.changePage('n');
});
document.getElementById('btn-last').addEventListener('click', function(){
    painter.changePage('l');
});
document.getElementById('btn-toThisPage').addEventListener('click', function(){
    painter.changePage(parseInt(document.getElementById('ipt-page').value));
});




function .movePage()

Move page from source index to aim index. Can only process in View mode.

Syntax: .movePage(toIndex)

parameter type description
(return value) boolean
toIndex Number(index)

Syntax: .movePage(fromIndex, toIndex)

parameter type description
(return value) boolean
fromIndex Number(index)
aimIndex Number(index)




function .del()

Delete a image. Can only process in View mode.

Syntax: .del(index)

parameter type description
(return value) boolean
index (optional) Number Default current index.




function .getWidth()

Get width of current image in the MBC instance.

Syntax: .getWidth(index)

parameter type description
(return value) Number
index (optional) Number Default current index.




function .getHeight()

Get height of current image in the MBC instance.

Syntax: .getHeight(index)

parameter type description
(return value) Number
index (optional) Number Default current index.




function .getBlob()

Get the image data in Blob type.

Syntax: .getBlob(index)

parameter type description
(return value) Blob
index (optional) Number Default current index.




function .download()

Download the image to users' local system. The function should be invoked directly by the user. Async invoking may have problems.

Syntax: .download(filename, index)

parameter type description
(return value) String filename
filename (optional) String
index (optional) Number Default current index.

example:

document.getElementById('btn-download').addEventListener('click', function(){
    for(var i = 0; i < painter.getCount(); ++i){
        painter.download(null, i);
    }
});




function .bindThumbnailBox()

Syntax: .bindThumbnailBox(container, funWrap, maxWH)

parameter type description
(return value) boolean
container HTMLElement
funWrap (optional) HTMLElement function(HTMLCanvasElement cvs)
maxWH (optional) Number Default 256.

example:

painter.bindThumbnailBox(document.getElementById('div-thumbnailContainer'), function(cvs){
    console.log(cvs.className);// 'kPainterThumbnailCanvas', never remove this class
    var box = document.createElement('div');
    box.className = 'div-thumbnailBox';
    box.appendChild(cvs);
    box.addEventListener('click', function(){
        var idx = box.getKPainterIndex();// get index
        painter.changePage(idx);
    });
    return box;
});

//change the current selected box style
painter.onNumChange = function(curIndex, length){
    var container = document.getElementById('div-thumbnailContainer');
    var childNodes = container.childNodes;
    for(var i = 0; i < childNodes.length; ++i){
        var child = childNodes[i];
        child.removeAttribute('selected');
    }
    // An array called `kPainterThumbBoxArr` will be added after `bindThumbnailBox`. The array will update automatically
    container.kPainterThumbBoxArr[curIndex].setAttribute('selected','');
};




function .unbindThumbnailBox()

Syntax: .unbindThumbnailBox(container)

parameter type description
(return value) boolean
container HTMLElement

example:

painter.bindThumbnailBox(document.getElementById('div-thumbnailContainer'));




Gesturer


Number .leftDoubleClickZoomRate

Set the zoom rate when user left double click.

Syntax: .leftDoubleClickZoomRate = 2;




Number .rightDoubleClickZoomRate

Set the zoom rate when user right double click.

Syntax: .rightDoubleClickZoomRate = 0.5;




boolean .allowedTouchMoveSwitchImgOverBoundary

Whether allow switch from last to first or from first to last by touchmove gesture.

Syntax: .allowedTouchMoveSwitchImgOverBoundary = true;




event .onUpdateImgPosZoom

Binding a function that would be called when the performence of the current image or canvas(in Edit mode) update.

Syntax: function(){}

example:

painter.onUpdateImgPosZoom(function(){
    console.log(painter.getZoom());
    console.log(painter.getEditWidth());
    console.log(painter.getEditHeight());
});




function .getZoom()

Get the zoom of current image or canvas(in Edit mode).

Syntax: .getZoom()

parameter type description
(return value) Number




function .setZoom()

Set the zoom of current image or canvas(in Edit mode).

Syntax: .setZoom(num, isRate)

parameter type description
(return value) Number The finally effective zoom.
num Number
isRate boolean




Basic Editor


Number .stepImgsGCThreshold

The can-not-store step (freeTransform, brush) will generate a step image. If the step images' count over stepImgsGCThreshold, oldest not protected one would be GC.

Syntax: .stepImgsGCThreshold = 10;




function .addProtectedStep()

Add a protected step. Then this step would not be GC. Can only process in Edit mode.

Syntax: .addProtectedStep(index)

parameter type description
index Number

example:

/**
 *  sample code: save and give up editing about freeTransform mode 
 */

document.getElementById('btn-enterFreeTransformMode').addEventListener('click', function(){
    // pretect step when enter freeTransform mode
    painter.addProtectedStep(painter.getCurStep());
    // presume that `MBC.loadCvScript()` has been called and success
    painter.enterFreeTransformMode();
});

document.getElementById('btn-saveFreeTransform').addEventListener('click', function(){
    // remove the the last pretect step
    var protectedSteps = painter.getProtectedSteps();
    painter.removeProtectedStep(protectedSteps[protectedSteps.length - 1]);
    // transform and exitFreeTransformMode
    painter.freeTransform().then(function(){
        painter.exitFreeTransformMode();
    });
});

document.getElementById('btn-giveUpFreeTransform').addEventListener('click', function(){
    // pretect step when enter freeTransform mode
    var protectedSteps = painter.getProtectedSteps();
    var lastPretectedStep = protectedSteps[protectedSteps.length - 1];
    // remove the the last pretect step
    painter.removeProtectedStep(lastPretectedStep);
    // exitFreeTransformMode
    painter.exitFreeTransformMode().then(function(){
        // jump to the last pretect step
        painter.setCurStep(lastPretectedStep);
    });
});




function .removeProtectedStep()

Remove a protected step. Then this step can be GC. Can only process in Edit mode.

Syntax: .removeProtectedStep(index)

parameter type description
index Number




function .getProtectedSteps()

Get All protected steps. Can only process in Edit mode.

Syntax: .getProtectedSteps()

parameter type description
(return value) Array A array of the protected numbers.




function .undo()

Undo an editing step. Can only process in Edit mode.

Syntax: .undo()

parameter type description
(return value) Promise(resolve(), reject(ex))




function .redo()

Redo an editing step. Can only process in Edit mode.

Syntax: .redo()

parameter type description
(return value) Promise(resolve(), reject(ex))




function .getStepCount()

Get count of editing steps. Can only process in Edit mode.

Syntax: .getStepCount()

parameter type description
(return value) Number




function .getCurStep()

Get current editing step. Can only process in Edit mode.

Syntax: .getCurStep()

parameter type description
(return value) Number




function .setCurStep()

Set current editing step. Can only process in Edit mode.

Syntax: .setCurStep(index)

parameter type description
(return value) Promise(resolve(), reject(ex))
index Number




function .enterEdit()

Enter the Edit mode.

Syntax: .enterEdit()

parameter type description
(return value) Promise(resolve(), reject(ex))




function .cancelEdit()

Leave the Edit mode without saving change.

Syntax: .cancelEdit()

parameter type description
(return value) boolean




function .saveEdit()

Save change and leave the Edit mode.

Syntax: .saveEdit(isCover)

parameter type description
(return value) Promise(resolve(), reject(ex))
isCover boolean




function .rotateRight()

Rotate right. Can only process in Edit mode.

Syntax: .rotateRight()

parameter type description
(return value) boolean




function .rotateLeft()

Rotate left. Can only process in Edit mode.

Syntax: .rotateLeft()

parameter type description
(return value) boolean




function .mirror()

Mirror. Can only process in Edit mode.

Syntax: .mirror()

parameter type description
(return value) boolean




function .flip()

Flip. Can only process in Edit mode.

Syntax: .flip()

parameter type description
(return value) boolean




function .resize()

Resize. Can only process in Edit mode.

Syntax: .resize(newWidth, newHeight)

parameter type description
(return value) Promise(resolve(), reject(ex))
newWidth Number
newHeight Number




function .getEditWidth()

Get width of current editing canvas.

Syntax: .getEditWidth()

parameter type description
(return value) Number




function .getEditHeight()

Get height of current editing canvas.

Syntax: .getEditHeight()

parameter type description
(return value) Number




Crop


boolean .isAutoShowCropUI

Whether show Crop Rect UI when enter Edit mode

Syntax: .isAutoShowCropUI = true;




function .showCropRect()

Show Crop Rect. Can only process in Edit mode.

Syntax: .showCropRect()




function .hideCropRect()

Hide Crop Rect. Can only process in Edit mode.

Syntax: .hideCropRect()




function .setCropRectStyle()

Default 0. 0: touch/click moving inside Crop Rect will move the back canvas. 1: touch/click moving inside Crop Rect will move the Crop Rect.

Syntax: .setCropRectStyle(styleNo)

parameter type description
(return value) boolean
styleNo Number 0, 1




Number .cropRectMinW

Crop Rect min width.

Syntax: .cropRectMinW = 50;




Number .cropRectMinH

Crop Rect min height.

Syntax: .cropRectMinH = 50;




event .onCropRectChange

Binding a function that would be called when the Crop Rect change.

Syntax: function(){}

example:

painter.onCropRectChange = function(){
    var cropArea = painter.getCropRectArea(true);
    document.getElementById('cropWidth').innerText = cropArea[2] - cropArea[0];
    document.getElementById('cropHeight').innerText = cropArea[3] - cropArea[1];
};




function .setCropRectArea()

Set Crop Rect area. Can only process in Edit mode.

Syntax: .setCropRectArea()

Crop Rect select All.

parameter type description
(return value) boolean

Syntax: .setCropRectArea(left, top, right, bottom)

Crop Rect select an area.

parameter type description
(return value) boolean
left (optional) Number -0.5 ~ 0.5, default -0.5.
top (optional) Number -0.5 ~ 0.5, default -0.5.
right (optional) Number -0.5 ~ 0.5, default 0.5.
bottom (optional) Number -0.5 ~ 0.5, default 0.5.




function .getCropRectArea()

Syntax: .getCropRectArea(isAbsolute)

parameter type description
(return value) Array A array of [left, top, right, bottom].
isAbsolute boolean Default false, get precentage(-50% ~ 50%) array.




function .crop()

Crop the selected area. Can only process in Edit mode.

Syntax: .crop(array)

parameter type description
(return value) Promise(resolve([left, top, right, bottom]), reject(ex))
array (optional) Array A array of [left, top, right, bottom] (each -0.5 ~ 0.5). Default use an area accroding to Crop Rect.




function .setCropRectWidthHeightRate()

Lock width/height == rate. Default unlock.

Syntax: .setCropRectWidthHeightRate(whRate)

parameter type description
whRate (optional) Number Rate of width/height need to lock. Miss the parameter or null/undefined will unlock the rate.

example:

// lock the rate, width == height
painter.setCropRectWidthHeightRate(1);
// unlock the rate, width/height can be any
painter.setCropRectWidthHeightRate();




Free Transform

You should call KPainter.loadCvScript() first before use FreeTransform mode.


function .documentDetect()

Detect a document. Would auto call setFreeTransformCornerPos() after detected. Can only process in FreeTransform mode.

Syntax: .documentDetect(importSrc)

parameter type description
(return value) Promise(resolve([[x0,y0], [x1,y1], [x2,y2], [x3,y3]]), reject(ex)) x0, y0... is from -0.5 to 0.5.
importSrc (optional) TUDO. Not easy enough to use now.




function .setFreeTransformCornerPos()

Set the FreeTransform corner position. Can only process in FreeTransform mode.

Syntax: .setFreeTransformCornerPos(cornerPoints)

parameter type description
cornerPoints Array A array of [[x0,y0], [x1,y1], [x2,y2], [x3,y3]]. x0, y0... is from -0.5 to 0.5.




function .getFreeTransformCornerPos()

Get the FreeTransform corner position.

Syntax: .getFreeTransformCornerPos()

parameter type description
(return value) Array A array of [[x0,y0], [x1,y1], [x2,y2], [x3,y3]]. x0, y0... is from -0.5 to 0.5.




event .onFreeTransformCornerPosChange

Binding a function that would be called when the FreeTransform corner position change.

Syntax: function()

example:

painter.onFreeTransformCornerPosChange = function(){
    console.log(painter.getFreeTransformCornerPos());
};




Number .freeTransformMaxWH

freeTransform() is a really expensive operation. freeTransformMaxWH would limit the max width and height of the result.

Syntax: .freeTransformMaxWH = 2048;




function .freeTransform()

Transform the quadrilateral surround by the FreeTransform corner into a rectangle. Can only process in FreeTransform mode.

Syntax: .freeTransform(cornerPoints, importSrc)

parameter type description
(return value) Promise(resolve(), reject(ex))
cornerPoints (optional) Array A array of [[x0,y0], [x1,y1], [x2,y2], [x3,y3]]. x0, y0... is from -0.5 to 0.5.
importSrc (optional) TUDO. Not show for user.




function .enterFreeTransformMode()

Enter FreeTransform mode. Can only process in Edit mode.

Syntax: .enterFreeTransformMode()

parameter type description
(return value) Promise(resolve(), reject(ex))




function .exitFreeTransformMode()

Exist FreeTransform mode.

Syntax: .exitFreeTransformMode()

parameter type description
(return value) Promise(resolve(), reject(ex))




Video


HTMLDivElement .videoHtmlElement

The html element of video module.

example:

// log the default video module 
console.log(painter.videoHtmlElement.innerHTML);
// custom your video module
painter.videoHtmlElement.innerHTML = '<video class="kPainterVideo" webkit-playsinline="true"></video>';
palnter.showVideo();




MediaStreamConstraints .videoSettings

A MediaStreamConstraints.

reference: getUserMedia




function .showVideo

Syntax: .showVideo(videoSettings)

parameter type description
(return value) Promise(resolve(), reject(ex))
videoSettings (optional) MediaStreamConstraints A MediaStreamConstraints. reference: getUserMedia




function .grabVideo

Syntax: .grabVideo(isAutoAdd)

parameter type description
isAutoAdd boolean Whether add image to instance automatically.

Syntax: .grabVideo()

Grab a image from the video and return the image.

parameter type description
(return value) HTMLCanvasElement

Syntax: .grabVideo(true)

Grab a image from the video and auto add image to the painter. Can only process in View mode.

parameter type description
(return value) Promise(resolve(addResult), reject(ex))




function .hideVideo

Syntax: .hideVideo()




event .beforeAddImgFromGrabVideoBtn

Syntax: function(canvas, callback){}

example:

painter.beforeAddImgFromGrabVideoBtn = function(canvas, callback){
    doSomeWorkToGetNewSrc(canvas, function(srcValidForAddImage){
        callback(srcValidForAddImage);
    });
};




event .afterAddImgFromGrabVideoBtn

Syntax: function(bSuccess, addResult){}

example:

painter.afterAddImgFromGrabVideoBtn = function(bSuccess, addResult){
    if(bSuccess){console.log('The new image(s) has been added from video.');}
};