javascript - Checking to see if object is out of canvas (Raphael.js) -
currently using raphael.js drag , drop circle around canvas. however, disallow user drag circle out of canvas. code follows:
<script type="text/javascript" src="javascript/raphael.js"></script> <script type="text/javascript"> window.onload = function() { //create canvas matching image's dimensions var paper = new raphael(document.getelementbyid('canvas_container'), <%=width%>, <%=height%>); //put schematic image onto canvas paper.image("<%=path%>",0,0,<%=width%>,<%=height%>); //create marker on canvas var c = paper.circle(<%=markerx%>, <%=markery%>, 5).attr({ fill: "#800517", stroke: "none" }); var start = function () { // storing original coordinates this.ox = this.attr("cx"); this.oy = this.attr("cy"); }, move = function (dx, dy) { // move called dx , dy if (this.ox + dx >= <%=width%> || this.oy + dy >= <%=height%>){ this.attr({cx: <%=width%>, cy: <%=height%>}); }else{ this.attr({cx: this.ox + dx, cy: this.oy + dy}); } }, = function () { // restoring state }; c.drag(move, start, up); } </script>
i wondering if there out there has tried , managed right.
with if
statement, don't have if don't want move. also, don't forget radius of circle, , don't forget checking value being small, not big:
// if new position if (this.ox + dx <= width - radius && // not far right this.oy + dy <= height - radius && // , not far down this.ox + dx >= 0 + radius && // , not far left this.oy + dy >= 0 + radius) // , not far { // ... move this.attr({cx: this.ox + dx, cy: this.oy + dy}); } // else nothing
jsfiddle example
but use min
, max
more:
var nowx, nowy, w = ..., h=..., r=..., move = function (dx, dy) { // move called dx , dy // restrict movement of circle within boundaries // can combine following 4 lines 2 or 1, // left 4 readability. nowx = math.max(0 + r, this.ox + dx); nowy = math.max(0 + r, this.oy + dy); nowx = math.min(w - r, nowx); nowy = math.min(h - r, nowy); this.attr({cx: nowx, cy: nowy}); }
so, here's full working example (jsfiddle)
window.onload = function() { var nowx, nowy, w = 300, h=300, r=30, r = raphael("canvas", w, h), c = r.circle(100, 100, r).attr({ fill: "hsb(.8, 1, 1)", stroke: "none", opacity: .5, cursor: "move" }); var start = function () { // storing original coordinates this.ox = this.attr("cx"); this.oy = this.attr("cy"); this.attr({opacity: 1}); }, move = function (dx, dy) { // move called dx , dy // restrict movement of circle within boundaries nowx = math.max(0 + r, this.ox + dx); nowy = math.max(0 + r, this.oy + dy); nowx = math.min(w - r, nowx); nowy = math.min(h - r, nowy); this.attr({cx: nowx, cy: nowy}); }, = function () { // restoring state this.attr({opacity: .5}); }; c.drag(move, start, up); };
Comments
Post a Comment