[英]HTML5/JS canvas displaying pictures
I am having trouble displaying pictures on my canvas, especially when using Chrome. 我在画布上显示图片时遇到了麻烦,尤其是在使用Chrome时。
I have a method that is called to draw a portrait (name, img, borders), but context.drawImage()
doesn't seem to be working in Chrome. 我有一个用来绘制人像(名称,img,边框)的方法,但是
context.drawImage()
在Chrome中似乎不起作用。 Any solutions? 有什么办法吗?
Portrait.prototype.draw = function (context, x, y, tX, tY) {
context.save();
context.translate( tX, tY );
context.fillStyle = 'blue';
context.strokeStyle = 'black';
context.strokeRect(x, y, 160, 200);
context.fillRect(x, y, 160, 200);
context.stroke();
// adding the image
context.beginPath();
var img = new Image();
var link = this.getImageUrl();
img.src = link;
//context.drawImage(img,x+5,y+5); //works mozzila
img.onload = function () { context.drawImage(img,x+5,y+5); }
// partial work chrome but on refresh displays e.g two different portrait images in turn in a random portrait (if multiple portraits on canvas)
// text box
context.beginPath();
context.fillStyle = '#ffffff';
context.fillRect(x+5,y + 165,150,30);
// text
context.beginPath();
context.fillStyle = 'black';
var n = this.getName();
context.font = "25px Aerial";
context.fillText(n,x+5,y+190); // should give the name
context.restore();
};
You're passing img.onload
a function which will be executed asynchronously, meaning the other lines of code will proceed before it's done. 您正在传递
img.onload
一个将异步执行的函数,这意味着其他代码行将在完成之前继续进行。 Wrap the entire "draw" in your image.onload function. 将整个“绘制”包装在image.onload函数中。
Portrait.prototype.draw = function (context, x, y, tX, tY) {
var img = new Image();
var link = this.getImageUrl();
img.src = link;
img.onload = function () {
context.save();
context.translate( tX, tY );
context.fillStyle = 'blue';
context.strokeStyle = 'black';
context.strokeRect(x, y, 160, 200);
context.fillRect(x, y, 160, 200);
context.stroke();
context.drawImage(img,x+5,y+5);
//...
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.