画布不绘制图像 [英] canvas not drawing images

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

问题描述

我只是想弄清楚如何获取一个图像在画布上绘制。我按照W3学校的教程,但是当我试图在我自己的似乎没有工作。我将以下代码复制并粘贴到HTML文件中,并且该图片不会加载到画布中。我把图片下载到同一个目录下。我一直在问,看着网上,但没有人似乎知道什么问题是。
我正在使用更新版本的chrome(版本29.0.1547.76 m)。

I'm just trying to figure out how to get an image to draw on a canvas. I followed a tutorial on W3 schools, but when i tried it on my own it doesn't seem to be working. I copy and paste the code below into an HTML file, and the image never loads into the canvas. I downloaded the picture into the same directory. I've been asking around, and looked online, but no one seems to know what the problem is. I'm using an updated version of chrome (Version 29.0.1547.76 m).

<!DOCTYPE html>
<html>
<body>

<p>Image to use:</p>
<img id="scream" src="img_the_scream.jpg" alt="The Scream" width="220" height="277">

<p>Canvas:</p>
<canvas id="myCanvas" width="250" height="300" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
this.ctx.drawImage(img,10,10);

</script>

</body>
</html>


推荐答案

您的图片可能尚未完成载入您正在使用drawImage:

Your image probably hasn't finished loading at the point you are using drawImage:

HTML

在img标签中添加onload处理程序:

Add onload handler in img tag:

<img id="scream" onload="draw()" src="...

然后处理它的函数:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");

function draw() {
    ctx.drawImage(img,10,10);
}

在线演示

Online demo here

请注意将脚本放置在文档中的位置。

Be aware of that where you place the scripts in your document matters as well.

我建议您设置在JavaScript中的 src 属性,这使得它更安全地处理 onload img.addEventListener('load',... )。

I would recommend you setting the src attribute in JavaScript as well. That makes it more "safe" to handle the onload (or subscribed event with img.addEventListener('load', ...).

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

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