0
votes

I am working on a project using HTML5 and javascript.I have a canvas on which document will be loaded.

canvas = document.getElementById('pdf');
ctx = canvas.getContext('2d');

In above canvas, document will be loaded. I have to draw different shapes on it as an individual canvas at runtime.So that on drawing i have to create a new canvas for each and every Shape (required).

MouseDown

function mouse_Pressed(e) {
     getMouse(e);//getting current X and Y position
 x1=mx; y1=my;
    var cords=getMousePos(canvas,e); 
    annCanvas=document.createElement('canvas'); //Creating 
    annCanvasContext=annCanvas.getContext('2d');
     isDraw=true;isDrawAnn=true;
}

MouseMove

function mouse_Dragged(e)
{
    if(isDraw)
    {
    getMouse(e);
    x2=mx; y2=my;
    calculatePoints(x1,y1,x2,y2);
    var width=endX-startX;
    var height=endY-startY;
    annCanvas.style.position = "absolute";
    annCanvas.width=4; //Width of square
    annCanvas.style.left=""+startX+"px";
    annCanvas.style.top=""+startY+"px";
    annCanvas.height=height;
    annCanvas.style.zIndex="100000";

    document.getElementById("canvas").appendChild(annCanvas);
    annCanvasContext.fillStyle='rgb(255,255,0)';
    annCanvasContext.lineWidth=borderWidth;
    annCanvasContext.strokeRect(0,0,width,height);
    annCanvasContext.stroke();
 }
} 

MouseReleased

function mouse_Released(e)
{
 isDrag = false;
 isDraw=false;
 isDrawAnn=false;
}

Main problem is that if i am drawing rectangle with border width 50 then its Canvas-outside part is going to cut because of less area of canvas(i.e. rect shape). So i want to calculate canvas height, width with its borderWidth.

1

1 Answers

0
votes

This should take into account the border width as well as width etc.

function init() {
    var canvas = document.getElementById("canvas");
    var ctx = canvas.getContext("2d");
    var s = size(canvas);
    alert(s[0]);
}


function size(el) {
    var clientHeight = (el.offsetHeight > el.clientHeight) ? el.offsetHeight : el.clientHeight;
    var clientWidth = (el.offsetWidth > el.clientWidth) ? el.offsetWidth : el.clientWidth;
    return [clientWidth, clientHeight];
};

HTML:

<body onload="init();">
<canvas id="canvas" width="200" height="300" style="width: 500px; height: 400px; border: 10px solid brown;"></canvas>
</body>