<body>
<p id="main"></p>
</p>
<script type="text/javascript">
function GED(ele) {return document.getElementById(ele);}
function load_source(url, w, h) {
this.canvas = document.createElement('canvas');
this.canvas.width = w;
this.canvas.height = h;
this.ctx = this.canvas.getContext('2d');
this.img = new Image();
this.img.src = url;
this.img.onload = function () {
this.ctx.drawImage(this.img, 0, 0);
}.bind(this);
return this.canvas;
}
source = new load_source('http://htmljs.b0.upaiyun.com/uploads/1382542991440-2angles.png', 300, 100);
canvas = document.createElement('canvas')
canvas.id = 'ff'
canvas.width = 300;
canvas.height = 100;
GED('main').appendChild(canvas);
ctxs = GED('ff').getContext('2d');
ctxs.drawImage(source, 110, 110);
</script>
The above code is normal, because when your image is in
load_source
, it is drawn asynchronously to thecanvas
inload_source
throughimg.onload
. However, before that time,img There is no image on
, so the canvas inload_source
also has no image.However, before that time, the canvas in the DOM is ready, and
ctxs.drawImage(source,110,110)
is executed. Since the canvas inload_source
is still empty at this time (the image inside has not been loaded yet, the canvas inside has no content), sosource
is also empty, soctx.drawImage(source,110,110)
The things painted on are also empty.Try the following code, it feels like course design