javascript - How can I give a background for an object on the canvas? -


i made little canvas , create square path drawing moveto() , lineto() orders.

so have square red borders , can give background color fillstyle , gets color fill().

it executes click.

var c = document.createelement('canvas'); c.id = 'mycanvas'; c.style.background = "#ffffff"; c.width = "100"; c.height = "50"; document.getelementbyid('container').appendchild(c);  var ctx = c.getcontext("2d"); ctx.beginpath(); ctx.moveto(0, 0); ctx.lineto(0, 80); ctx.lineto(50, 80); ctx.lineto(50, 0); ctx.lineto(0, 0);    ctx.strokestyle = "red"; ctx.stroke();  var getcolor2 = 0; var getcolor = 0;  c.addeventlistener("click", function(){        if(getcolor2 == 0){           ctx.fillstyle = "#ffffff";        }        if(getcolor2 == 1){           ctx.fillstyle = "#ff33df";        }        if(getcolor2 == 2){           ctx.fillstyle = "#bbbbbb";        }        if(getcolor2 == 3){           ctx.fillstyle = "#bb4563";        }        if(getcolor2 == 4){           ctx.fillstyle = "#234556";           getcolor2 = -1;         }         getcolor2++;        ctx.fill();  }); 

https://jsfiddle.net/mafb7qhh/2/

my problem is: executes when click on canvas well. execute clicking on square only.

everything draw inside canvas can't "selected" because not exist dom element. if need clickable areas maybe svg can come in handy instead of canvas, or else using invisible dom element on canvas same position/size of element drew

anyway, made little jsfiddle , checking list of rectangles if mouse on or not example if whish handle mouse events using canvas (only rectangles).

for more complex polygons have use (for example) ray casting algorithm. https://en.wikipedia.org/wiki/point_in_polygon


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -