Heim > Fragen und Antworten > Hauptteil
<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>
淡淡烟草味2017-07-05 10:48:45
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<p id="main"></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);
window.ctxs.drawImage(source,110,110);
}.bind(this);
return this.canvas;
}
source = new load_source('http://htmljs.b0.upaiyun.com/uploads/1382542991440-2angles.png',300,100);
GED('main').appendChild(source);
canvas = document.createElement('canvas')
canvas.id='ff'
canvas.width = 300;
canvas.height = 100;
GED('main').appendChild(canvas);
ctxs= GED('ff').getContext('2d');
</script>
</body>
</html>
上面这段代码是正常的,因为你的图片在load_source
的时候,是通过img.onload
异步画到load_source
里面的canvas
上的,然而,在那个时间之前,img
上是没有图像的,所以load_source
里面的canvas也是没图像的。
但是,在那个时间之前,DOM里的canvas已经就绪,而且执行了ctxs.drawImage(source,110,110)
。由于此时的load_source
里的canvas还是空的(里面的图还没加载完毕,里面的画布也就没有内容),所以source
也就是空的,所以ctx.drawImage(source,110,110)
画上去的东西也是空的。
为情所困2017-07-05 10:48:45
试一哈下面这段代码,感觉是在做课程设计的样子
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="main">
<canvas id="myCanvas" width="400px" height="300px" style="border: 1px solid red;">
</canvas>
</p>
<script type="text/javascript">
var canvas = document.getElementById("myCanvas");
if(canvas.getContext){
//获取对应的CanvasRenderingContext2D对象(画笔)
var ctx = canvas.getContext("2d");
//创建新的图片对象
var img = new Image();
//指定图片的URL
img.src = "http://htmljs.b0.upaiyun.com/uploads/1382542991440-2angles.png";
//浏览器加载图片完毕后再绘制图片
img.onload = function(){
//以Canvas画布上的坐标(10,10)为起始点,绘制图像
ctx.drawImage(img, 10, 10);
};
}
</script>
</html>