我在 Canvas 上显示图片时遇到问题,尤其是在使用 Chrome 时。
我有一个被调用的方法来绘制肖像(名称、img、边框),但是 context.drawImage()
似乎在 Chrome 中不起作用。有什么解决办法吗?
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();
};
最佳答案
您正在传递 img.onload
一个将异步执行的函数,这意味着其他代码行将在完成之前继续执行。将整个“绘制”包含在 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);
//...
}
};
关于javascript - HTML5/JS Canvas 显示图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33812261/