shabbir.rang
shabbir.rang

Reputation: 279

Working with canvas to display only the drawn image and not whole canvas

With the plugin i found earlier on stackoverflow. Drawing has become smooth and nice. What i want is to only get the image part which i draw cropped from the canvas as an output and not the complete canvas. Can somebody help. This is the code i am using for my canvas now: http://jsfiddle.net/sVsZL/1/

function canvasDisplay() {
var c=document.getElementById("canvas");
canvasImage=c.toDataURL("image/png");
document.getElementById("SSMySelectedImage").src=canvasImage;   
}

Upvotes: 0

Views: 142

Answers (1)

Loktar
Loktar

Reputation: 35309

Adding another answer because the other one was completely off.

Live Demo

What you need essentially is to keep track of a bounding box. What I do is create an object that holds the min values and max values of where you've drawn. This enables you to keep track of how big the image is and where it begins/ends.

this.dim = {minX : 9999, minY : 9999, maxX : 0, maxY : 0};

Then I created a function that checks the bounds.

this.setDimensions = function(x,y){
        if(x < this.dim.minX){
            this.dim.minX = x;   
        }

        if(y < this.dim.minY){
             this.dim.minY = y;   
        }

        if(x > this.dim.maxX){
             this.dim.maxX= x;   
        }

        if(y > this.dim.maxY){
             this.dim.maxY = y;   
        }
    }

Make sure to check during clicking or moving.

    this.mousedown = function(ev) {
        tool.setDimensions(ev._x,ev._y);
    };

    this.mousemove = function(ev) {
            tool.setDimensions(ev._x,ev._y);
    };

And this is just a sample function that draws the portion to a new canvas that you could then save with toDataUrl

var button = document.getElementsByTagName("input")[0];
        button.addEventListener("click", function(){
            var savedCanvas = document.createElement("canvas"),
                savedCtx = savedCanvas.getContext("2d"),
                minX = PEN.dim.minX,
                minY = PEN.dim.minY,
                maxX = PEN.dim.maxX,
                maxY = PEN.dim.maxY,
                width = maxX - minX,
                height = maxY - minY;

            savedCanvas.width = width;
            savedCanvas.height = height; 

           document.body.appendChild(savedCanvas);
           savedCtx.drawImage(canvas,minX,minY,width,height,0,0,width,height);  
        });

Upvotes: 1

Related Questions