javascript - [js]为什么画布里不出现图片呢?在线等

查看:154
本文介绍了javascript - [js]为什么画布里不出现图片呢?在线等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<body>
    <div id="main"></div>
</div>
<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>

解决方案

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="main"></div>
<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)画上去的东西也是空的。

这篇关于javascript - [js]为什么画布里不出现图片呢?在线等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆