Define the borders of the shapes / graphics drawn on canvas

I have a simple HTML5 Canvas example that allows a user to draw paths on a canvas. Is there a way to define the rectangular borders of the path / shape that were drawn? (i.e. what is the width, height of the rectangular area surrounding the path).

I understand that I can do the math while the form is drawn to define the boundaries, but they wanted to see if it was easier / built-in.

+4
source share
2 answers

I assume that you are using LineTo, the only way I could think of would be to keep the min / max stored for height and width when the user draws the paths. Other than that, the only way to pull information off the canvas would be to use getImageData, which will give you only the initial pixel information.

A quick example showing this

http://jsfiddle.net/dEnAF/

note I just create a bunch of random dots. The main thing to remember is to set min / max vals for the coordinates of the first path that the user creates.

I think you knew that, although, so there is no real answer, unfortunately, there is currently no built-in for this.

+6
source

Despite the fact that you have to track it yourself, I would suggest wrapping it in reusable functions. Here is a minimal example tracking it only for moveTo and lineTo . See a live example here: http://phrogz.net/tmp/canvas_bounding_box.html

 function trackBBox( ctx ){ var begin = ctx.beginPath; ctx.beginPath = function(){ this.minX = this.minY = 99999999999; this.maxX = this.maxY = -99999999999; return begin.call(this); }; ctx.updateMinMax = function(x,y){ if (x<this.minX) this.minX = x; if (x>this.maxX) this.maxX = x; if (y<this.minY) this.minY = y; if (y>this.maxY) this.maxY = y; }; var m2 = ctx.moveTo; ctx.moveTo = function(x,y){ this.updateMinMax(x,y); return m2.call(this,x,y); }; var l2 = ctx.lineTo ctx.lineTo = function(x,y){ this.updateMinMax(x,y); return l2.call(this,x,y); }; ctx.getBBox = function(){ return { minX:this.minX, maxX:this.maxX, minY:this.minY, maxY:this.maxY, width:this.maxX-this.minX, height:this.maxY-this.minY }; }; } ... var ctx = myCanvas.getContext("2d"); // Cause the canvas to track its own bounding box for each path trackBBox(ctx); ctx.beginPath(); ctx.moveTo(40,40); for(var i=0; i<10; i++) ctx.lineTo(Math.random()*600,Math.random()*400); // Find the bounding box of the current path var bbox = ctx.getBBox(); ctx.strokeRect(bbox.minX,bbox.minY,bbox.width,bbox.height); 
+3
source

Source: https://habr.com/ru/post/1334700/


All Articles