Javascript canvas: Set own color for two different objects (squares) -
i'm real frustrated problem. so, have following simple code:
var canvas = document.getelementbyid('canvasfield'); var ctx = canvas.getcontext('2d'); function square(x, y, sizeofside) { this.draw = function () { ctx.beginpath(); ctx.moveto(x,y); ctx.lineto(x + sizeofside, y); ctx.lineto(x + sizeofside, y + sizeofside); ctx.lineto(x, y + sizeofside); ctx.lineto(x,y); ctx.closepath(); ctx.stroke(); } this.setcolor = function (color) { ctx.fillstyle = color; ctx.fill(); } }
square object. can draw square , can set fill-color it. next code works fine.
var square1 = new square(100, 100, 100); var square2 = new square(250, 200, 100); square1.draw(); square1.setcolor('green'); square2.draw(); square2.setcolor('yellow');
https://i.stack.imgur.com/gz50k.png
but if change this:
var square1 = new square(100, 100, 100); var square2 = new square(250, 200, 100); square1.draw(); square2.draw(); square1.setcolor('green'); square2.setcolor('yellow');
it breaks down:
https://i.stack.imgur.com/qeojl.png
it seems me understand reason. 2 objects have same context. , square2 sets color yellow context , square1 loses color. maybe not right. expected 2 independent objects , i'll able manipulate conditions @ place in code. have no idea next. please help!
demo
var canvas = document.getelementbyid('canvasfield'); var ctx = canvas.getcontext('2d'); function square(x, y, sizeofside) { this.draw = function () { ctx.beginpath(); ctx.moveto(x,y); ctx.lineto(x + sizeofside, y); ctx.lineto(x + sizeofside, y + sizeofside); ctx.lineto(x, y + sizeofside); ctx.lineto(x,y); ctx.closepath(); ctx.stroke(); } this.setcolor = function (color) { this.draw(); ctx.fillstyle = color; ctx.fill(); } } //var square1 = new square(100, 100, 100); //var square2 = new square(250, 200, 100); //square1.draw(); //square1.setcolor('green'); //square2.draw(); //square2.setcolor('yellow'); var square1 = new square(100, 100, 100); var square2 = new square(250, 200, 100); //square1.draw(); //square2.draw(); square1.setcolor('green'); square2.setcolor('yellow');
canvas { border : 2px dotted blue; }
<canvas id='canvasfield' width=500 height=500></canvas>
call draw
function of object inside setcolor
function. draw square first fill using given color.
Comments
Post a Comment