Guess that a job title might be needed for editing, but so far I don't know where the problems are. I read pages and answered similar questions, here and elsewhere. One answer is especially close, but I do not understand this.
I need a function to draw polygons on the canvas in the desired coordinates and fill them with some background image loaded from a file (large enough so that there is no need for a tile). Triangles would be good for a test. Apparently, I should use drawImage and the clip, and in order to provide the polygon with the border, I can use the same path for the clip and stroke. Also, apparently, I have to keep order
- define path - save - clip - drawImage - restore - stroke.
Also read somewhere that just uploading the image once is enough. (If you want me to quote sources for all of these assumptions, I will look for where I saw them. Most of them are in the stack overflow)
HTML is otherwise empty
<body onload = "main ();"></body>
The first approach, pretending that the browser will wait for the image to load:
var ctx, img; var image_path = 'bg.jpg'; function main () { var CANVAS_SIZE = 600; var view_field_cnv = document.createElement ('canvas'); view_field_cnv.width = CANVAS_SIZE; view_field_cnv.height = CANVAS_SIZE; view_field_cnv.style.border = "1px solid"; document.body.appendChild (view_field_cnv); ctx = view_field_cnv.getContext ('2d'); img = document.createElement ('img'); img.src = image_path; place_triangle (0, 0); place_triangle (300, 300); place_triangle (500, 500); place_triangle (0, 0); } function place_triangle (x, y) { console.log (x, y); ctx.beginPath (); ctx.moveTo (x + 10, y); ctx.lineTo (x + 110, y); ctx.lineTo (x + 60, y + 40); ctx.closePath (); img = document.createElement ('img'); img.src = image_path; ctx.save (); ctx.clip (); ctx.drawImage (img, x, y); ctx.restore (); ctx.stroke (); }
This draws all three triangles, but does not crop the image.
Second attempt, with drawImage inside image.onload:
var ctx; var image_path = 'bg.jpg'; function main () { var CANVAS_SIZE = 600; var view_field_cnv = document.createElement ('canvas'); view_field_cnv.width = CANVAS_SIZE; view_field_cnv.height = CANVAS_SIZE; view_field_cnv.style.border = "1px solid"; document.body.appendChild (view_field_cnv); ctx = view_field_cnv.getContext ('2d'); place_triangle (0, 0); place_triangle (300, 300); place_triangle (500, 500); place_triangle (0, 0); } function place_triangle (x, y) { console.log (x, y); var img; ctx.beginPath (); ctx.moveTo (x + 10, y); ctx.lineTo (x + 110, y); ctx.lineTo (x + 60, y + 40); ctx.closePath (); img = document.createElement ('img'); img.src = image_path; img.onload = function () { ctx.save (); ctx.clip (); ctx.drawImage (img, x, y); ctx.restore (); ctx.stroke (); } }
This picture draws a cropped image, but only one triangle, the last. Just commenting on save and restore does not help.
So, I donβt understand downloading images, saving, restoring and maybe a million other things. Where will the errors be?