繁体   English   中英

HTML5 / JS画布显示图片

[英]HTML5/JS canvas displaying pictures

我在画布上显示图片时遇到了麻烦,尤其是在使用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);
        //...

    }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM