javascript - Which way to create a canvas pattern from a dataToURL-image string as directly as possible? -


i'm using image had made by

var patternimageasdataurl= canvasobject.todataurl('image/png'); 

in later stage want make canvas pattern object. following code doesn't work - assume image not loaded when going last line, needed in createpattern function.

var img = document.createelement('img'); img.src = patternimageasdataurl; // canvasctx created somewhere else in program pattern = canvasctx.createpattern(img,'repeat'); 

i error: ns_error_not_available: on last line. (and when using console.log on width , heigth of img between 2 last lines, see when it's not working dimensions 0.)

when later on same operation done same dataurl, work. though image (img) should created anew. (only reason can see it's because of internal optimization in firefox. that's offtopic here, unless know answer.) width , height when printing them out console correct then.

while quite program pattern handling service, should solve this, question in general , speed concerns , simplicity. (if use code 20 50 objects patterns, prefer lean solution on memory or time saving function.)

could somehow use dataurl more directly (and faster) createpattern function? and: force program wait after img.src = patternimageasdataurl; command until image loaded, , go on processing code? (like in synchronous mode of xmlrequests.)

(using onload event of image isn't feasible in current program flow.)

this running on firefox 32, win 7.

a faster, more direct way create pattern

you can use second canvas element source pattern.

this allows skip interim step of creating imageurl , image source canvas pattern creation faster.

enter image description here

var canvas=document.getelementbyid("canvas");  var ctx=canvas.getcontext("2d");  var cw=canvas.width;  var ch=canvas.height;    // make temporary canvas template pattern  var pc=document.createelement('canvas');  var px=pc.getcontext('2d');  pc.width=4;  pc.height=4;  px.fillstyle='palegreen';  px.fillrect(0,0,2,2);  px.fillrect(2,2,2,2);    // use temporary canvas image source "createpattern"  var pattern=ctx.createpattern(pc,'repeat');  ctx.fillstyle=pattern;  ctx.fillrect(50,50,100,75);  ctx.strokerect(50,50,100,75);
body{ background-color: ivory; }  #canvas{border:1px solid red;}
<h4>using temporary canvas source pattern.</h4>  <canvas id="canvas" width=300 height=300></canvas>


Popular posts from this blog