javascript在画布上绘制图像 [英] javascript draw a image on canvas

查看:136
本文介绍了javascript在画布上绘制图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试构建一个javascript代码,在画布上绘制图像,但我不知道在哪里出错。
这是我的代码:

I try to build a javascript code, to draw a image on canvas, but I don't know where go wrong. That is my code:

<body>
<canvas id = "my_canvas"></canvas>
<script>
function setup(){
    var canvas = document.getElementById('my_canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = 800;
    canvas.height = 600;
    var image = new Image();
    image.src = 'a.png';
    ctx.drawImage(image,5,5);
};
window.onload = setup;
setup();

</script>

问题是,如果我在结束时输入一行代码 setup(); ,然后图片正确绘制,我不知道为什么。

The question is, if I put a line of code setup(); at end then the image is correctly draw, I don't know why.

感谢。

推荐答案

问题是 image 异步地,所以如果你设置源并绘制它立即然后图像位还不可用,没有绘制。

The problem is that image is loaded asynchronously, so if you set the source and draw it immediately then the image bits are not yet available and nothing is drawn.

您必须等待图像加载之前

You have to wait for the image to load before being able to draw it on a canvas.

将代码更改为

image.onload = function() {
    ctx.drawImage(image, 5, 5);
};
image.src = "a.png";

应按预期工作。

这篇关于javascript在画布上绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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