[英]How can you overlay an image on a canvas, then draw on top of it?
I have all the code worked out to draw on a canvas in a separate .js
file, so now I just need to put the image on. 我已经完成了在单独的.js
文件中绘制画布的所有代码,所以现在我只需要将图像放在上面。
I can't get the image to work, though, the normal method isn't working. 我无法让图像工作,但是,正常的方法不起作用。 I've tried this: 我试过这个:
var canvasvar;
var contextvar;
canvasvar = document.getElementById("canvas");
contextvar = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "http://wannabevc.files.wordpress.com/2010/09/im-cool.jpg";
contextvar.drawImage(imageObj,10,10);
For one thing, should I put this inside the html
file, inside a <script></script>
at the end, or should I put it in the js
file that has the “draw stuff” code? 首先,我应该将它放在html
文件中,最后放在<script></script>
中,还是应该把它放在带有“绘制内容”代码的js
文件中? I can't get either to work, it runs with no errors but I don't see any image over the canvas. 我无法工作,它运行没有错误,但我没有在画布上看到任何图像。 So I can still draw, but no image appears. 所以我仍然可以画,但没有图像出现。 I'm guessing the image is under the canvas or something. 我猜这个图像是在画布下面的东西。
I'm guessing this is because I didn't just make a canvas – I made it with all this programming happening inside it in another js
file. 我猜这是因为我不只是制作一个画布 - 我在其他js
文件中发生了所有这些编程。
I also tried putting this code inside the initCanvas
function in my .js
code. 我也尝试将此代码放在我的.js
代码中的initCanvas
函数中。 This is what actually creates the canvas. 这是实际创建画布的内容。 Here is the code of initCanvas
function: 这是initCanvas
函数的代码:
// Retrieve canvas reference
canvas = document.getElementById("canvas");
// Size canvas
canvas.width = 600;
canvas.height = 400;
// Retrieve context reference, used to execute canvas drawing commands
context = canvas.getContext('2d');
context.lineCap = "round";
// Set control panel defaults
document.getElementById("thickness").selectedIndex = 0;
document.getElementById("color").selectedIndex = 1;
// Overlay image over the canvas. THIS PART IS WHAT I'M ASKING ABOUT. This is usually
// not in the code
var canvasvar;
var contextvar;
canvasvar = document.getElementById("canvas");
contextvar = canvas.getContext("2d");
var imageObj = new Image();
imageObj.src = "http://wannabevc.files.wordpress.com/2010/09/im-cool.jpg";
contextvar.drawImage(imageObj,10,10);
So the last part in this code is what I'm talking about. 所以这段代码的最后一部分就是我所说的。 It isn't working, though. 但它没有用。
Give your image time to load using imageObj.onload 使用imageObj.onload为您的映像加载时间
var canvasvar = document.getElementById("canvas");
var contextvar = canvas.getContext("2d");
var imageObj = new Image();
imageObj.onload=function(){
contextvar.drawImage(imageObj,10,10);
}
imageObj.src = "http://wannabevc.files.wordpress.com/2010/09/im-cool.jpg";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.