Guess the title of the post may need editing, but for now I don't know where the problems are. I have read pages and answers to similar questions, here and elsewhere. One Stack Overflow answer is especially close, but I don't understand it.
I want a function, to draw polygons on canvas at desired coordinates and to fill them with some background image loaded from a file (large enough that no tiling is needed). Triangles would be fine for a test. Apparently I should use drawImage and clip, and to give the polygon a border, I can resuse the same path for the clip and the stroke. Also apparently I should keep the order of
- define path
- save
- clip
- drawImage
- restore
- stroke.
Also read somewhere that it is enough to load the image once. (If uou want me to quote sources for all these assumptions, I will look for where I saw them. Most of them on Stack Overflow)
The HTML is an otherwise empty
<body onload = "main ();"></body>
First approach, pretending that the browser will wait for the picture 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 ();
}
That draws all three triangles but no clipped images.
Second try, 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 one does draw the clipped image, but only one triangle, the last one. Just commenting out save and restore doesn't help.
So, I don't understand loading images, saving, restoring and probably a million other things. Where be the bugs?