javascript - HTML5/JS Canvas 显示图片

标签 javascript html canvas

我在 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/

相关文章:

javascript - meteor.js & spacebars - 在嵌套循环中传递变量

javascript - 在 AngularJS View 中的移动网络中显示原生广告时出现问题

html - 在 div 响应式 CSS 中制作图像

javascript - 如何使用 HTML5 canvas 绘制镜片横截面?

javascript - 如何重新初始化所需的模块?

javascript - Bootstrap 表 - Bootstrap 4 的多重排序被破坏

javascript - 检测未绑定(bind)的 native 函数,例如 `Array.push` ?

html - 为选定的 <li> 项添加颜色/覆盖 <ul> 样式

javascript - 如何使 Canvas 轮廓成为悬停发光的透明 png

javascript - 将带参数的方法添加到 javascript 对象